OXYGENHUB

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

752 of 1627 lines run, 88 of 373 functions · run #180 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
1648×
    pub fn log(&self, job: i64, records: Vec<Record>) -> Result<()> {
1658×
        self.post(&format!("/flow/jobs/{job}/log"), &LogBatch { records })?;
1665×
        Ok(())
1678×
    }
168
169
    /// Upload artifact `name` of job `job` (spec §5.2); the hub keeps it as
170
    /// a blob of the job's repository and answers with its ObjectRef.
1710×
    pub fn artifact(&self, job: i64, name: &str, bytes: &[u8]) -> Result<String> {
1720×
        let url = format!("{}/api/v1/flow/jobs/{job}/artifacts/{name}", self.base);
1730×
        let r = retrying(&url, &PATIENT_DELAYS, true, || {
1740×
            self.agent
1750×
                .post(&url)
1760×
                .timeout(Duration::from_secs(600))
1770×
                .set("Authorization", &format!("Bearer {}", self.token))
1780×
                .set("Content-Type", "application/octet-stream")
1790×
                .send_bytes(bytes)
1800×
                .map_err(Box::new)
1810×
        })?;
1820×
        let v: serde_json::Value = r.into_json()?;
1830×
        v["blob"].as_str().map(String::from).context("the hub named no blob")
1840×
    }
185
186
    /// Keep a checkpoint of job `job` (oxygenflow#77) as its runner hands
187
    /// it back: the hub answers with its blob, which the next attempt's
188
    /// claim names.
1890×
    pub fn save_checkpoint(&self, job: i64, bytes: &[u8]) -> Result<String> {
1900×
        let url = format!("{}/api/v1/flow/jobs/{job}/checkpoint", self.base);
1910×
        let r = retrying(&url, &PATIENT_DELAYS, true, || {
1920×
            self.agent
1930×
                .post(&url)
1940×
                .timeout(Duration::from_secs(600))
1950×
                .set("Authorization", &format!("Bearer {}", self.token))
1960×
                .set("Content-Type", "application/octet-stream")
1970×
                .send_bytes(bytes)
1980×
                .map_err(Box::new)
1990×
        })?;
2000×
        let v: serde_json::Value = r.into_json()?;
2010×
        v["blob"].as_str().map(String::from).context("the hub named no blob")
2020×
    }
203
204
    /// The checkpoint an earlier attempt of job `job` saved (oxygenflow#77),
205
    /// which the caller checks against the blob its claim names.
2060×
    pub fn checkpoint(&self, job: i64) -> Result<Vec<u8>> {
2070×
        let url = format!("{}/api/v1/flow/jobs/{job}/checkpoint", self.base);
2080×
        let r = retrying(&url, &PATIENT_DELAYS, false, || {
2090×
            self.agent
2100×
                .get(&url)
2110×
                .timeout(Duration::from_secs(600))
2120×
                .set("Authorization", &format!("Bearer {}", self.token))
2130×
                .call()
2140×
                .map_err(Box::new)
2150×
        })?;
2160×
        let mut bytes = Vec::new();
2170×
        std::io::Read::read_to_end(&mut std::io::Read::take(r.into_reader(), crate::checkpoint::MAX_BYTES as u64 + 1), &mut bytes)?;
2180×
        Ok(bytes)
2190×
    }
220
221
    /// Input `index` of job `job` (oxygenflow#58): the bytes of the
222
    /// producing job's artifact, which the caller checks against the blob the
223
    /// claim names.
2240×
    pub fn input(&self, job: i64, index: usize) -> Result<Vec<u8>> {
2250×
        let url = format!("{}/api/v1/flow/jobs/{job}/inputs/{index}", self.base);
2260×
        let r = retrying(&url, &PATIENT_DELAYS, false, || {
2270×
            self.agent
2280×
                .get(&url)
2290×
                .timeout(Duration::from_secs(600))
2300×
                .set("Authorization", &format!("Bearer {}", self.token))
2310×
                .call()
2320×
                .map_err(Box::new)
2330×
        })?;
2340×
        let mut bytes = Vec::new();
2350×
        let mut reader = r.into_reader();
2360×
        std::io::Read::read_to_end(&mut std::io::Read::take(&mut reader, MAX_INPUT_BYTES as u64 + 1), &mut bytes)?;
2370×
        if bytes.len() > MAX_INPUT_BYTES {
2380×
            bail!("larger than {} MiB", MAX_INPUT_BYTES >> 20);
2390×
        }
2400×
        Ok(bytes)
2410×
    }
242
243
    /// Upload file `path` of report `name` of job `job` (oxygenhub#127);
244
    /// the hub keeps it as a blob and answers with its ObjectRef. The
245
    /// report's manifest follows through [`Hub::artifact`].
2460×
    pub fn report_file(&self, job: i64, name: &str, path: &str, bytes: &[u8]) -> Result<String> {
2470×
        let url = format!("{}/api/v1/flow/jobs/{job}/reports/{name}/files", self.base);
2480×
        let r = retrying(&url, &PATIENT_DELAYS, true, || {
2490×
            self.agent
2500×
                .post(&url)
2510×
                .timeout(Duration::from_secs(600))
2520×
                .set("Authorization", &format!("Bearer {}", self.token))
2530×
                .set("Content-Type", "application/octet-stream")
2540×
                .set("X-Flow-Report-Path", path)
2550×
                .send_bytes(bytes)
2560×
                .map_err(Box::new)
2570×
        })?;
2580×
        let v: serde_json::Value = r.into_json()?;
2590×
        v["blob"].as_str().map(String::from).context("the hub named no blob")
2600×
    }
261
262
    /// Report a job's end until the hub has it (oxygenhub#71): while the hub
263
    /// cannot be reached or fails (5xx), try again after `first_wait`,
264
    /// doubling to a minute, for up to `patience`. A refusal (4xx: the job was ended
265
    /// already, say) is final. A result lost here leaves the job running
266
    /// on the hub until its time limit.
2672×
    pub fn finish_until_accepted(&self, job: i64, f: &Finish, patience: Duration, first_wait: Duration) -> Result<()> {
2682×
        let url = format!("{}/api/v1/flow/jobs/{job}/finish", self.base);
2692×
        let deadline = std::time::Instant::now() + patience;
2702×
        let mut wait = first_wait;
271
        loop {
2726×
            let why = match self.agent.post(&url).set("Authorization", &format!("Bearer {}", self.token)).send_json(f) {
2731×
                Ok(_) => return Ok(()),
2745×
                Err(ureq::Error::Status(code, r)) if code < 500 => {
2751×
                    bail!("{url}: HTTP {code}: {}", r.into_string().unwrap_or_default())
276
                }
2774×
                Err(ureq::Error::Status(code, _)) => format!("HTTP {code}"),
2780×
                Err(e) => e.to_string(),
279
            };
2804×
            if std::time::Instant::now() + wait > deadline {
2810×
                bail!("{url}: gave up after {} minutes: {why}", patience.as_secs() / 60);
2824×
            }
2834×
            eprintln!("job {job}: the hub did not take the result ({why}); trying again in {} s", wait.as_secs());
2844×
            std::thread::sleep(wait);
2854×
            wait = (wait * 2).min(Duration::from_secs(60));
286
        }
2872×
    }
288
}
289
290
/// How long a runner keeps trying to report a job's end.
291
const FINISH_PATIENCE: Duration = Duration::from_secs(2 * 3600);
292
293
/// Where a job's result waits until the hub has it, so a runner that
294
/// restarts still reports it.
2950×
fn pending_path(home: &Home, job: i64) -> PathBuf {
2960×
    home.root.join("pending").join(format!("{job}.json"))
2970×
}
298
299
/// Report `f`, keeping it on disk until the hub has it.
3000×
fn report_finish(home: &Home, hub: &Hub, job: i64, f: &Finish) {
3010×
    let path = pending_path(home, job);
3020×
    let kept = std::fs::create_dir_all(path.parent().unwrap())
3030×
        .and_then(|_| std::fs::write(&path, serde_json::to_vec(f).unwrap_or_default()))
3040×
        .is_ok();
3050×
    match hub.finish_until_accepted(job, f, FINISH_PATIENCE, Duration::from_secs(5)) {
3060×
        Ok(()) => {}
3070×
        Err(e) => eprintln!("job {job}: reporting failed: {e:#}"),
308
    }
3090×
    if kept {
3100×
        let _ = std::fs::remove_file(&path);
3110×
    }
3120×
}
313
314
/// Results a previous run of the runner could not report, to send again.
3150×
fn report_pending(home: &Home) -> Vec<(i64, Finish)> {
3160×
    let Ok(dir) = std::fs::read_dir(home.root.join("pending")) else {
3170×
        return Vec::new();
318
    };
3190×
    dir.filter_map(|e| {
3200×
        let p = e.ok()?.path();
3210×
        let job: i64 = p.file_stem()?.to_str()?.parse().ok()?;
3220×
        let f: Finish = serde_json::from_slice(&std::fs::read(&p).ok()?).ok()?;
3230×
        Some((job, f))
3240×
    })
3250×
    .collect()
3260×
}
327
328
/// `flow runner register`: exchange a one-time registration token from
329
/// the hub for this runner's credential, binding the runner's signing key,
330
/// and keep hub, credential and name in runner.toml.
3311×
pub fn register(home: &Home, hub: &str, token: &str, name: &str, ca: Option<PathBuf>, labels: Vec<String>) -> Result<Registered> {
3321×
    if home.config.runner.is_some() && !home.root.join(crate::home::RUNNER_TOML).is_file() {
3330×
        bail!("flow.toml already has a [runner] section; remove it to register this runner instead");
3341×
    }
3351×
    let key = home.runner_key(name)?;
3361×
    let hub = hub.trim_end_matches('/').to_string();
3371×
    let tls = oxy_core::protocol::tls_client_config(ca.as_deref()).map_err(|e| anyhow::anyhow!("{e}"))?;
3381×
    let agent = ureq::AgentBuilder::new().tls_config(tls).timeout(Duration::from_secs(60)).build();
3391×
    let req = Register {
3401×
        token: token.trim().to_string(),
3411×
        name: name.to_string(),
3421×
        identity: hex::encode(key.identity.encode()),
3431×
        info: RunnerInfo { version: env!("OXY_VERSION_LONG").into(), ..RunnerInfo::here(labels.clone(), 1, None, None) },
3441×
    };
3451×
    let url = format!("{hub}/api/v1/flow/runners/register");
3461×
    let got: Registered = match agent.post(&url).send_json(&req) {
3471×
        Ok(r) => r.into_json()?,
3480×
        Err(ureq::Error::Status(code, r)) => bail!("{url}: HTTP {code}: {}", r.into_string().unwrap_or_default()),
3490×
        Err(e) => bail!("{url}: {e}"),
350
    };
3511×
    let mut text = format!(
352
        "# Written by `flow runner register`; the credential is secret.\nhub = {hub:?}\ntoken = {:?}\nname = {:?}\n",
353
        got.credential, got.name
354
    );
3551×
    if let Some(ca) = &ca {
3560×
        text.push_str(&format!("ca = {:?}\n", ca.display().to_string()));
3571×
    }
3581×
    if !labels.is_empty() {
3591×
        text.push_str(&format!("labels = {labels:?}\n"));
3601×
    }
3611×
    let path = home.root.join(crate::home::RUNNER_TOML);
362
    {
363
        use std::io::Write;
364
        use std::os::unix::fs::OpenOptionsExt;
3651×
        let tmp = path.with_extension("toml.tmp");
3661×
        let mut f = std::fs::OpenOptions::new().write(true).create(true).truncate(true).mode(0o600).open(&tmp)?;
3671×
        f.write_all(text.as_bytes())?;
3681×
        f.sync_all()?;
3691×
        std::fs::rename(&tmp, &path)?;
370
    }
3711×
    Ok(got)
3721×
}
373
374
/// Waits before trying a hub request again after a server error.
375
const RETRY_DELAYS: [Duration; 3] = [Duration::from_secs(1), Duration::from_secs(2), Duration::from_secs(4)];
376
377
/// Waits for what a job leaves behind (oxygenflow#49): three minutes in
378
/// all, longer than a hub takes to restart.
379
/// Check an input's bytes against the blob the producing job's receipt
380
/// names, then write them at its path under `tree` (the workspace's `/src`).
3816×
fn place_input(tree: &Path, i: &flow_core::api::ArtifactInput, bytes: &[u8]) -> Result<[u8; 32]> {
3826×
    let Some(rel) = i.path.strip_prefix("/src/").filter(|r| r.split('/').all(|p| !p.is_empty() && p != "." && p != ".." && p != ".oxy"))
383
    else {
3844×
        bail!("path {:?} is not a clean path under /src", i.path);
385
    };
3862×
    let blob = Repo::blob_ref(bytes);
3872×
    if blob.to_hex() != i.blob {
3881×
        bail!("it is not what {}'s receipt names (blob {}, not {})", i.from, &blob.to_hex()[..12], &i.blob[..i.blob.len().min(12)]);
3891×
    }
3901×
    let dest = tree.join(rel);
3911×
    if let Some(dir) = dest.parent() {
3921×
        std::fs::create_dir_all(dir)?;
3930×
    }
3941×
    std::fs::write(&dest, bytes)?;
3951×
    Ok(blob.0)
3966×
}
397
398
/// The largest input a job takes: the hub's artifact limit.
399
pub const MAX_INPUT_BYTES: usize = 512 << 20;
400
401
const PATIENT_DELAYS: [Duration; 15] = {
402
    let mut d = [Duration::from_secs(15); 15];
403
    d[0] = Duration::from_secs(1);
404
    d[1] = Duration::from_secs(2);
405
    d[2] = Duration::from_secs(4);
406
    d[3] = Duration::from_secs(8);
407
    d
408
};
409
410
/// Send a request until the hub answers, waiting `delays` in turn after a
411
/// server error (5xx: nothing was committed) and, when `connection`, after
412
/// the hub could not be reached at all. A refusal (4xx) is final, as a
413
/// [`Refused`] the caller can look at.
41414×
fn retrying(
41514×
    url: &str,
41614×
    delays: &[Duration],
41714×
    connection: bool,
41814×
    mut send: impl FnMut() -> Result<ureq::Response, Box<ureq::Error>>,
41914×
) -> Result<ureq::Response> {
42014×
    let mut delays = delays.iter();
421
    loop {
42223×
        let why = match send().map_err(|e| *e) {
4238×
            Ok(r) => return Ok(r),
4249×
            Err(ureq::Error::Status(code, r)) if code < 500 => {
4252×
                let text = r.into_string().unwrap_or_default();
4262×
                return Err(anyhow::Error::new(Refused { code, text }).context(url.to_string()));
427
            }
4287×
            Err(ureq::Error::Status(code, r)) => format!("HTTP {code}: {}", r.into_string().unwrap_or_default()),
4293×
            Err(e) if connection => e.to_string(),
4303×
            Err(e) => bail!("{url}: {e}"),
431
        };
43210×
        match delays.next() {
4339×
            Some(d) => std::thread::sleep(*d),
4341×
            None => bail!("{url}: {why}"),
435
        }
436
    }
43714×
}
438
439
/// What the runner may run at once (flow.toml `[runner]`): at most
440
/// `max_jobs` jobs, whose sandboxes together fit `memory_mib` and `cpus`.
441
#[derive(Debug, Default, PartialEq, Eq)]
442
pub struct Budget {
443
    pub max_jobs: usize,
444
    pub memory_mib: Option<u32>,
445
    pub cpus: Option<u32>,
446
}
447
448
/// What is in use now.
449
#[derive(Debug, Default, Clone, Copy, PartialEq, Eq)]
450
pub struct Used {
451
    pub jobs: usize,
452
    pub memory_mib: u32,
453
    pub cpus: u32,
454
}
455
456
impl Budget {
4570×
    pub fn of(cfg: &RunnerConfig) -> Budget {
4580×
        Budget { max_jobs: cfg.max_jobs.unwrap_or(1).max(1), memory_mib: cfg.memory_mib, cpus: cfg.cpus }
4590×
    }
460
461
    /// The room to ask the hub for, or `None` when no job more can start.
462
    /// A lone job may use the whole budget even if it asks for more, so a
463
    /// large sandbox is never starved.
4647×
    pub fn room(&self, used: Used) -> Option<(Option<u32>, Option<u32>)> {
4657×
        if used.jobs >= self.max_jobs {
4662×
            return None;
4675×
        }
4685×
        if used.jobs == 0 {
4692×
            return Some((None, None));
4703×
        }
4713×
        let mem = self.memory_mib.map(|m| m.saturating_sub(used.memory_mib));
4723×
        let cpus = self.cpus.map(|c| c.saturating_sub(used.cpus));
4733×
        if mem == Some(0) || cpus == Some(0) {
4741×
            return None;
4752×
        }
4762×
        Some((mem, cpus))
4777×
    }
478
}
479
480
/// The isolation tiers this machine can honour now (spec §11.1): the
481
/// MicroVM tier when `/dev/kvm` opens for reading and writing and
482
/// flow.toml pins Firecracker; the syscall tier when this binary may use
483
/// user namespaces, Landlock and seccomp and manage a delegated cgroup.
484
/// `Err` says why there are none; the reasons for missing tiers come back
485
/// with the ones there are.
4863×
pub fn tiers(home: &Home) -> std::result::Result<(Vec<String>, Vec<String>), String> {
4873×
    let mut have = Vec::new();
4883×
    let mut missing = Vec::new();
4893×
    let kvm = std::fs::OpenOptions::new().read(true).write(true).open("/dev/kvm");
4903×
    match (kvm, home.config.microvm.is_some()) {
4910×
        (Ok(_), true) => have.push("microvm".to_string()),
4920×
        (Ok(_), false) => missing.push("microvm: flow.toml has no [microvm] section".to_string()),
4933×
        (Err(e), _) => missing.push(format!(
494
            "microvm: /dev/kvm cannot be opened ({e}); the tier needs hardware virtualisation and this user in the kvm group"
495
        )),
496
    }
4973×
    match crate::syscall::available() {
4980×
        Ok(()) => have.push("syscall".to_string()),
4993×
        Err(e) => missing.push(format!("syscall: {e}")),
500
    }
501
    // wasmtime runs on every machine this binary does (oxygenflow#75).
5023×
    have.push("wasm".to_string());
5033×
    if have.is_empty() {
5040×
        return Err(format!("no isolation tier can run here: {}", missing.join("; ")));
5053×
    }
5063×
    Ok((have, missing))
5073×
}
508
509
/// Fetch `claim`'s image from the hub when this home lacks it
510
/// (oxygenflow#39), saying so in the job's log. A hub that does not hold it
511
/// leaves it missing, and the preflight declines the job as before.
5120×
fn fetch_image(home: &Home, hub: &Hub, cfg: &RunnerConfig, swarm: Option<&crate::swarm::Swarm>, claim: &Claim) {
5130×
    let hash = &claim.sandbox.rootfs;
5140×
    if hash.is_empty() || home.rootfs(hash).is_file() || !jet::images::is_hash(hash) {
5150×
        return;
5160×
    }
5170×
    let note = |text: String| {
5180×
        eprintln!("job {}: {text}", claim.job_id);
5190×
        hub.log(claim.job_id, vec![Record { t: 0, stream: "flow".into(), text }]).ok();
5200×
    };
521
    // One fetch of an image at a time: two jobs wanting it wait for one.
522
    static FETCHING: std::sync::Mutex<()> = std::sync::Mutex::new(());
5230×
    let _one = FETCHING.lock().unwrap_or_else(|p| p.into_inner());
5240×
    if home.rootfs(hash).is_file() {
5250×
        return;
5260×
    }
5270×
    let client = match crate::images::Client::new(&cfg.hub, &cfg.token, cfg.ca.as_deref()) {
5280×
        Ok(c) => c,
5290×
        Err(e) => return note(format!("image {}: cannot reach the hub: {e:#}", &hash[..12])),
530
    };
5310×
    let fetched = match swarm {
5320×
        Some(sw) => {
5330×
            note(format!("image {} is not on this runner: fetching it from its peers and the hub", &hash[..12]));
5340×
            sw.fetch(home, hash)
535
        }
536
        None => {
5370×
            note(format!("image {} is not on this runner: fetching it from the hub", &hash[..12]));
5380×
            client.fetch(home, hash)
539
        }
540
    };
5410×
    match fetched {
5420×
        Ok(Some(m)) => note(format!(
543
            "image {}: fetched {} chunks, {}{} in {:.1} s",
5440×
            &hash[..12],
545
            m.chunks,
5460×
            crate::images::human(m.bytes),
5470×
            if swarm.is_some() { format!(" ({} from peers)", crate::images::human(m.peer_bytes)) } else { String::new() },
5480×
            m.elapsed.as_secs_f64()
549
        )),
5500×
        Ok(None) => note(format!("image {}: the hub does not hold it either", &hash[..12])),
5510×
        Err(e) => note(format!("image {}: fetch failed: {e:#}", &hash[..12])),
552
    }
5530×
}
554
555
/// Why this runner cannot run `claim` now (spec §11.5), checked before
556
/// anything is fetched: the tier, the architecture, the image and the
557
/// memory. The hub chose it from what the runner last said, which may be
558
/// out of date.
5590×
fn preflight(home: &Home, claim: &Claim) -> Option<String> {
5600×
    let sb = &claim.sandbox;
5610×
    match sb.runtime {
562
        flow_core::Runtime::Microvm => {
5630×
            if let Err(e) = std::fs::OpenOptions::new().read(true).write(true).open("/dev/kvm") {
5640×
                return Some(format!("the MicroVM tier needs /dev/kvm, which cannot be opened here ({e})"));
5650×
            }
5660×
            if home.config.microvm.is_none() {
5670×
                return Some("the MicroVM tier is not set up here (flow.toml has no [microvm] section)".into());
5680×
            }
569
        }
570
        flow_core::Runtime::Syscall => {
5710×
            if let Err(e) = crate::syscall::available() {
5720×
                return Some(format!("the syscall tier cannot run here: {e}"));
5730×
            }
574
        }
575
        // No image and no architecture: only the memory matters.
576
        flow_core::Runtime::Wasm => {
5770×
            return available_memory_mib()
5780×
                .filter(|free| *free < u64::from(sb.memory_mib))
5790×
                .map(|free| format!("only {free} MiB of memory is free here; the sandbox needs {} MiB", sb.memory_mib));
580
        }
581
    }
5820×
    sandbox_problem(home, sb, std::env::consts::ARCH, available_memory_mib())
5830×
}
584
585
/// What stops `sb` running on this home's images, on a machine of
586
/// architecture `here` with `free_mib` of memory free.
5878×
fn sandbox_problem(home: &Home, sb: &flow_core::Sandbox, here: &str, free_mib: Option<u64>) -> Option<String> {
5888×
    if let Some(want) = sb.arch.as_deref().filter(|a| *a != here) {
5891×
        return Some(format!("the sandbox needs {want}; this runner is {here}"));
5907×
    }
5917×
    let short = &sb.rootfs[..12.min(sb.rootfs.len())];
5927×
    let image = home.rootfs(&sb.rootfs);
5937×
    if !image.is_file() {
5941×
        return Some(format!("rootfs {short} is not on this runner"));
5956×
    }
5966×
    if let Some(arch) = home.image_arch(&sb.rootfs).filter(|a| a != here) {
5972×
        return Some(format!("rootfs {short} is for {arch}; this runner is {here}"));
5984×
    }
5994×
    if let Err(e) = home.verified(&image, &sb.rootfs) {
6001×
        return Some(format!("rootfs {short} does not verify here: {e:#}"));
6013×
    }
6023×
    if let Some(free) = free_mib.filter(|free| *free < u64::from(sb.memory_mib)) {
6031×
        return Some(format!("only {free} MiB of memory is free here; the sandbox needs {} MiB", sb.memory_mib));
6042×
    }
6052×
    None
6068×
}
607
608
/// `MemAvailable` from /proc/meminfo, in MiB.
6090×
fn available_memory_mib() -> Option<u64> {
6100×
    let info = std::fs::read_to_string("/proc/meminfo").ok()?;
6110×
    let kib: u64 = info.lines().find_map(|l| l.strip_prefix("MemAvailable:"))?.trim().trim_end_matches("kB").trim().parse().ok()?;
6120×
    Some(kib / 1024)
6130×
}
614
6150×
pub fn serve(home: &Home) -> Result<()> {
6160×
    drain_on_stop();
6170×
    serve_until_drained(home)
6180×
}
619
620
/// The runner as a library, as the Android app runs it (oxygenhub-android#8):
621
/// no signal handlers; [`stop`] drains it, and this returns once the jobs
622
/// it holds are done and reported. It may be started again afterwards.
6230×
pub fn serve_embedded(home: &Home) -> Result<()> {
6240×
    STOPS.store(0, std::sync::atomic::Ordering::SeqCst);
6250×
    *LEAVING.lock().unwrap_or_else(|p| p.into_inner()) = None;
6260×
    serve_until_drained(home)
6270×
}
628
629
/// A departure ([`leave_within`]): why, and when the runner must be gone.
630
#[derive(Clone, Debug)]
631
struct Leave {
632
    reason: String,
633
    by: Instant,
634
}
635
636
/// Set once the runner is leaving: a job whose expected rest fits before
637
/// the deadline finishes; the others are stopped and handed back
638
/// (oxygenflow#76).
639
static LEAVING: std::sync::Mutex<Option<Leave>> = std::sync::Mutex::new(None);
640
6410×
fn leaving() -> Option<String> {
6420×
    LEAVING.lock().unwrap_or_else(|p| p.into_inner()).as_ref().map(|l| l.reason.clone())
6430×
}
644
645
/// Ask a runner started with [`serve_embedded`] to leave now: claim nothing
646
/// more, stop the jobs it holds and hand them back to the hub, which queues
647
/// them ahead of new work for another runner (oxygenflow#76), then return.
648
/// For a departure with no time to finish: a phone off the allowed network.
6490×
pub fn leave(reason: &str) {
6500×
    leave_within(reason, Duration::ZERO);
6510×
}
652
653
/// [`leave`], with `notice`: a job the hub expects to finish within it
654
/// (the claim's `expected_ms`, less the time it has run) finishes and is
655
/// reported; the others, and any still running when the notice is up, are
656
/// handed back. For a phone taken off charge, a spot reclaim.
6570×
pub fn leave_within(reason: &str, notice: Duration) {
6580×
    *LEAVING.lock().unwrap_or_else(|p| p.into_inner()) = Some(Leave { reason: reason.to_string(), by: Instant::now() + notice });
6590×
    stop();
6600×
}
661
662
/// Ask a runner started with [`serve_embedded`] to drain: claim nothing
663
/// more, finish and report what it holds, then return (oxygenflow#76's
664
/// drain, for a phone taken off charge or off the allowed network).
6651×
pub fn stop() {
6661×
    STOPS.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
6671×
}
668
6690×
fn serve_until_drained(home: &Home) -> Result<()> {
6700×
    let cfg = home.config.runner.clone().context("flow.toml has no [runner] section")?;
671
    // A runner offers only what it can run: a machine without KVM claims
672
    // nothing rather than taking MicroVM jobs and failing them (#36).
6730×
    let (runtimes, missing) = tiers(home).map_err(|why| anyhow::anyhow!("flow runner: {why}"))?;
6740×
    for why in &missing {
6750×
        eprintln!("flow runner: not offering {why}");
6760×
    }
6770×
    let hub = Hub::new(&cfg)?;
6780×
    let name = cfg.name.clone().unwrap_or_else(|| "flow".into());
6790×
    let budget = Budget::of(&cfg);
6800×
    let key = home.runner_key(&name)?;
681
    // The swarm (docs/jetstream.md §8.1): a runner that cannot serve its
682
    // peers still runs jobs, fetching images from the hub alone.
6830×
    let swarm = crate::swarm::Swarm::start(home, &cfg).unwrap_or_else(|e| {
6840×
        eprintln!("flow runner: not joining the swarm: {e:#}");
6850×
        None
6860×
    });
6870×
    eprintln!(
688
        "flow runner {name}: polling {} (up to {} jobs at once, tiers {}), signing receipts as {}",
689
        cfg.hub,
690
        budget.max_jobs,
6910×
        runtimes.join(", "),
6920×
        key.identity.hash().to_hex()
693
    );
6940×
    if let Some(addr) = &cfg.metrics {
6950×
        crate::metrics::serve(addr, cfg.metrics_token.clone(), name.clone());
6960×
    }
6970×
    let used = std::sync::Mutex::new(Used::default());
6980×
    let mut idle = Duration::from_secs(2);
6990×
    let pending = report_pending(home);
700
    // The jobs held now, told to the hub at each claim so it can end the
701
    // ones this runner lost: a job is held from its claim until its result
702
    // is reported.
7030×
    let held = std::sync::Mutex::new(std::collections::BTreeSet::<i64>::new());
7040×
    held.lock().unwrap().extend(pending.iter().map(|(job, _)| *job));
7050×
    std::thread::scope(|scope| {
7060×
        for (job, f) in pending {
7070×
            let (hub, held) = (&hub, &held);
7080×
            scope.spawn(move || {
7090×
                eprintln!("job {job}: reporting the result kept from before the restart");
7100×
                report_finish(home, hub, job, &f);
7110×
                held.lock().unwrap().remove(&job);
7120×
            });
713
        }
714
        // The speed (spec §11.1): measured now, and again every 15 minutes
715
        // while no job runs, so a job never shares the CPU with it.
7160×
        let measure = || {
7170×
            let (speed, ms) = crate::facts::bench();
7180×
            eprintln!("flow runner {name}: speed {speed} (class {}), benchmark {ms} ms", flow_core::api::Facts::class_of(speed));
7190×
            speed
7200×
        };
7210×
        let mut speed = measure();
7220×
        let mut benched = Instant::now();
7230×
        let mut said_draining = false;
724
        // When the hub last heard from us (oxygenhub#243): a claim, or a
725
        // heartbeat while there is no room to claim.
7260×
        let mut heard = Instant::now();
7270×
        let beat = |heard: &mut Instant| {
7280×
            if heard.elapsed() >= HUB_HEARTBEAT {
7290×
                if let Err(e) = hub.heartbeat() {
7300×
                    eprintln!("flow runner {name}: heartbeat: {e:#}");
7310×
                }
7320×
                *heard = Instant::now();
7330×
            }
7340×
        };
735
        loop {
736
            // Draining (oxygenflow#50): told to stop, claim nothing more and
737
            // stop once every job held is done and reported.
7380×
            if stopping() {
7390×
                let (jobs, holding) = (used.lock().unwrap().jobs, held.lock().unwrap().len());
7400×
                if jobs == 0 && holding == 0 {
7410×
                    eprintln!("flow runner {name}: drained, stopping");
7420×
                    break;
7430×
                }
7440×
                if !said_draining {
7450×
                    eprintln!("flow runner {name}: draining: claiming nothing more, stopping when the {jobs} job(s) held are done (stop again to stop now)");
7460×
                    said_draining = true;
7470×
                }
7480×
                beat(&mut heard);
7490×
                std::thread::sleep(Duration::from_millis(500));
7500×
                continue;
7510×
            }
7520×
            if used.lock().unwrap().jobs == 0 && benched.elapsed() >= Duration::from_secs(15 * 60) {
7530×
                speed = measure();
7540×
                benched = Instant::now();
7550×
            }
7560×
            let room = budget.room(*used.lock().unwrap());
7570×
            let Some((free_memory_mib, free_cpus)) = room else {
7580×
                beat(&mut heard);
7590×
                std::thread::sleep(Duration::from_millis(500));
7600×
                continue;
761
            };
7620×
            heard = Instant::now();
7630×
            let cache_times = crate::cache::Pool::new(&home.root, cfg.cache_gb).slot_times();
7640×
            let req = ClaimRequest {
7650×
                runner: name.clone(),
7660×
                runtimes: runtimes.clone(),
7670×
                free_memory_mib,
7680×
                free_cpus,
7690×
                info: Some(RunnerInfo {
7700×
                    version: env!("OXY_VERSION_LONG").into(),
7710×
                    ..RunnerInfo::here(cfg.offered_labels(), budget.max_jobs as u32, cfg.memory_mib, cfg.cpus)
7720×
                }),
773
                // Read each time: an image imported while the runner runs counts.
7740×
                images: Some(home.images()),
7750×
                image_archs: Some(home.image_archs()),
7760×
                holding: Some(held.lock().unwrap().iter().copied().collect()),
777
                fetches_images: true,
7780×
                facts: Some(crate::facts::now(home, Some(speed))),
7790×
                swarm: swarm.as_ref().map(|s| s.addr.clone()),
7800×
                caches: Some(cache_times.keys().cloned().collect()),
7810×
                cache_times: Some(cache_times),
782
            };
7830×
            match hub.claim(&req) {
7840×
                Ok(Some(claim)) => {
7850×
                    idle = Duration::from_secs(2);
7860×
                    crate::metrics::CLAIMS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
7870×
                    let (mem, cpus) = (claim.sandbox.memory_mib, claim.sandbox.cpus);
7880×
                    {
7890×
                        let mut u = used.lock().unwrap();
7900×
                        u.jobs += 1;
7910×
                        u.memory_mib += mem;
7920×
                        u.cpus += cpus;
7930×
                    }
7940×
                    held.lock().unwrap().insert(claim.job_id);
7950×
                    let (home, hub, cfg, used, key, held, swarm) = (home, &hub, &cfg, &used, &key, &held, swarm.as_ref());
7960×
                    scope.spawn(move || {
7970×
                        let id = claim.job_id;
7980×
                        fetch_image(home, hub, cfg, swarm, &claim);
7990×
                        if let Some(why) = preflight(home, &claim) {
8000×
                            eprintln!("job {id}: declined: {why}");
8010×
                            crate::metrics::DECLINED.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
8020×
                            if let Err(e) = hub.decline(id, &why) {
8030×
                                eprintln!("job {id}: decline: {e:#}");
8040×
                            }
8050×
                            held.lock().unwrap().remove(&id);
8060×
                            let mut u = used.lock().unwrap();
8070×
                            u.jobs -= 1;
8080×
                            u.memory_mib -= mem;
8090×
                            u.cpus -= cpus;
8100×
                            return;
8110×
                        }
8120×
                        eprintln!(
813
                            "job {id}: {} {} on {}",
814
                            claim.repo,
815
                            claim.job.name,
8160×
                            claim.heads.first().map(|h| &h[..12]).unwrap_or("-")
817
                        );
8180×
                        crate::metrics::RUNNING.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
8190×
                        let finish = run_claim(home, hub, cfg, key, &claim).unwrap_or_else(|e| Finish {
8200×
                            exit_code: None,
821
                            duration_ms: 0,
8220×
                            receipt: None,
8230×
                            signed_receipt: None,
8240×
                            error: Some(format!("{e:#}")),
8250×
                            peak_disk_mib: None,
8260×
                            peak_memory_mib: None,
8270×
                        });
8280×
                        eprintln!(
829
                            "job {id}: exit {:?}{}",
830
                            finish.exit_code,
8310×
                            finish.error.as_deref().map(|e| format!(" ({e})")).unwrap_or_default()
832
                        );
8330×
                        crate::metrics::RUNNING.fetch_sub(1, std::sync::atomic::Ordering::Relaxed);
8340×
                        let cancelled = finish.error.as_deref() == Some(CANCELLED);
8350×
                        crate::metrics::finished(finish.exit_code, finish.error.as_deref(), finish.duration_ms, cancelled);
8360×
                        match leaving() {
837
                            // Stopped as the runner leaves: another runner takes it.
8380×
                            Some(why) if cancelled => {
8390×
                                eprintln!("job {id}: handed back: {why}");
8400×
                                if let Err(e) = hub.release(id, &why) {
8410×
                                    eprintln!("job {id}: handing back: {e:#}; the hub requeues it once this runner's lease lapses");
8420×
                                }
843
                            }
8440×
                            _ if !cancelled => report_finish(home, hub, id, &finish),
8450×
                            _ => {}
846
                        }
8470×
                        held.lock().unwrap().remove(&id);
8480×
                        let mut u = used.lock().unwrap();
8490×
                        u.jobs -= 1;
8500×
                        u.memory_mib -= mem;
8510×
                        u.cpus -= cpus;
8520×
                    });
853
                }
8540×
                Ok(None) => std::thread::sleep(idle),
8550×
                Err(e) => {
8560×
                    eprintln!("claim: {e:#}");
8570×
                    std::thread::sleep(idle);
8580×
                    idle = (idle * 2).min(Duration::from_secs(60));
8590×
                }
860
            }
861
        }
8620×
        Ok(())
8630×
    })
8640×
}
865
866
/// Pack and keep a handed-back job's checkpoints (oxygenflow#77); what
867
/// happened goes to its log, and a failure only means the next attempt
868
/// starts again.
869
#[allow(clippy::too_many_arguments)]
8700×
fn save_checkpoint(hub: &Hub, id: i64, job: &flow_core::Job, scratch: &Path, dir_tier: bool, wasm: bool, mut say: impl FnMut(String)) {
8710×
    if !dir_tier {
8720×
        say("checkpoint: only the WASM and syscall tiers save one yet; the next attempt starts again".into());
8730×
        return;
8740×
    }
8750×
    let dirs: Vec<(String, PathBuf)> = job
8760×
        .checkpoints
8770×
        .iter()
8780×
        .filter_map(|c| crate::checkpoint::host_dir(c, job, &scratch.join("tree"), scratch, wasm).map(|d| (c.clone(), d)))
8790×
        .collect();
8800×
    match crate::checkpoint::pack(&dirs).and_then(|(bytes, n)| Ok((hub.save_checkpoint(id, &bytes)?, n))) {
8810×
        Ok((blob, n)) => {
8820×
            say(format!("checkpoint {}: {} files, {} bytes, kept for the next attempt", &blob[..12.min(blob.len())], n.files, n.bytes))
883
        }
8840×
        Err(e) => say(format!("checkpoint: not kept ({e:#}); the next attempt starts again")),
885
    }
8860×
}
887
888
/// How many times the runner was told to stop (SIGTERM or SIGINT).
889
static STOPS: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
890
8911×
extern "C" fn on_stop(_: libc::c_int) {
892
    // A second stop means now: only async-signal-safe calls here.
8931×
    if STOPS.fetch_add(1, std::sync::atomic::Ordering::SeqCst) >= 1 {
8940×
        unsafe { libc::_exit(143) };
8951×
    }
8961×
}
897
898
/// Drain instead of dying on the first SIGTERM or SIGINT (oxygenflow#50),
899
/// so restarting a runner never kills the job it runs: the unit's
900
/// `KillMode=mixed` sends the signal to the runner alone, not its microVMs.
9010×
fn drain_on_stop() {
9020×
    let handler = on_stop as extern "C" fn(libc::c_int) as libc::sighandler_t;
9030×
    unsafe {
9040×
        libc::signal(libc::SIGTERM, handler);
9050×
        libc::signal(libc::SIGINT, handler);
9060×
    }
9070×
}
908
9093×
fn stopping() -> bool {
9103×
    STOPS.load(std::sync::atomic::Ordering::SeqCst) > 0
9113×
}
912
913
/// Batches records to the hub every second (or every 200 lines). A quiet
914
/// job's sink still asks the hub every few seconds whether the job runs,
915
/// with an empty batch; once the hub answers 409 the job is not wanted.
916
struct LogSink<'a> {
917
    hub: &'a Hub,
918
    job: i64,
919
    buf: Vec<Record>,
920
    last: Instant,
921
    gone: bool,
922
    /// Set when the runner leaves ([`LEAVING`]): the job stops, to be
923
    /// handed back, unless its expected rest fits the notice.
924
    leaving: &'a std::sync::Mutex<Option<Leave>>,
925
    /// When the job started, and how long the hub expects it to take.
926
    started: Instant,
927
    expected: Option<Duration>,
928
}
929
930
/// The most log lines sent at once, as a busy job's sink flushes them.
931
const BATCH: usize = 200;
932
933
/// The most log lines kept while the hub cannot be reached.
934
const MAX_UNSENT: usize = 50_000;
935
936
/// How often a quiet job asks whether it was cancelled.
937
const HEARTBEAT: Duration = Duration::from_secs(5);
938
939
impl microvm::Sink for LogSink<'_> {
9401×
    fn record(&mut self, r: Record) {
9411×
        self.push(r)
9421×
    }
943
94410×
    fn cancelled(&mut self) -> bool {
94510×
        let leave = self.leaving.lock().unwrap_or_else(|p| p.into_inner()).clone();
94610×
        if let Some(l) = leave {
947
            // Finished if what is left of it fits the notice; else handed
948
            // back as the runner leaves, what the job said so far first.
9495×
            let now = Instant::now();
9505×
            let fits = self.expected.is_some_and(|e| now + e.saturating_sub(self.started.elapsed()) <= l.by);
9515×
            if !fits || now >= l.by {
9524×
                self.flush();
9534×
                return true;
9541×
            }
9555×
        }
9566×
        if !self.gone && self.last.elapsed() >= HEARTBEAT {
9572×
            self.send();
9584×
        }
9596×
        self.gone
96010×
    }
961
}
962
963
impl LogSink<'_> {
9641×
    fn push(&mut self, mut r: Record) {
9651×
        if self.gone {
9661×
            return;
9670×
        }
9680×
        if r.text.len() > MAX_RECORD_TEXT {
9690×
            let mut cut = MAX_RECORD_TEXT;
9700×
            while !r.text.is_char_boundary(cut) {
9710×
                cut -= 1;
9720×
            }
9730×
            r.text.truncate(cut);
9740×
        }
9750×
        self.buf.push(r);
9760×
        if self.buf.len() >= BATCH || self.last.elapsed() >= Duration::from_secs(1) {
9770×
            self.flush();
9780×
        }
9791×
    }
980
9815×
    fn flush(&mut self) {
9825×
        if !self.buf.is_empty() {
9831×
            self.send();
9844×
        }
9855×
        self.last = Instant::now();
9865×
    }
987
988
    /// Send what is buffered, even nothing, in batches of at most
989
    /// `BATCH` lines.
9906×
    fn send(&mut self) {
991
        loop {
9928×
            if self.gone {
9930×
                return;
9948×
            }
9958×
            let n = self.buf.len().min(BATCH);
9968×
            let batch: Vec<Record> = self.buf.drain(..n).collect();
9978×
            match self.hub.log(self.job, batch.clone()) {
9985×
                Ok(()) => {}
9993×
                Err(e) if job_gone(&e) => self.gone = true,
10002×
                Err(e) => {
1001
                    // The hub is away (a restart, say): keep the lines for
1002
                    // the next batch, up to a bound, so the log loses none
1003
                    // (oxygenflow#49).
10042×
                    eprintln!("job {}: log: {e:#}; kept for the next batch", self.job);
10052×
                    let mut kept = batch;
10062×
                    kept.append(&mut self.buf);
10072×
                    let over = kept.len().saturating_sub(MAX_UNSENT);
10082×
                    if over > 0 {
10091×
                        kept.drain(..over);
10101×
                        kept.insert(
10111×
                            0,
10121×
                            Record {
10131×
                                t: 0,
10141×
                                stream: "flow".into(),
10151×
                                text: format!("({over} log lines lost while the hub could not be reached)"),
10161×
                            },
10171×
                        );
10181×
                    }
10192×
                    self.buf = kept;
10202×
                    break;
1021
                }
1022
            }
10236×
            if self.buf.is_empty() {
10244×
                break;
10252×
            }
1026
        }
10276×
        self.last = Instant::now();
10286×
    }
1029
}
1030
1031
/// How often a runner with no room to claim tells the hub it is there:
1032
/// well inside the hub's 90 s before it shows a runner offline.
1033
const HUB_HEARTBEAT: Duration = Duration::from_secs(30);
1034
1035
/// Held while a job takes its cache disks and images its workspace (see
1036
/// `run_claim`): one job at a time on the runner's disk and cache pool.
1037
static PREPARE: std::sync::Mutex<()> = std::sync::Mutex::new(());
1038
1039
/// Held while the first clone of any repository passes its token through
1040
/// the process environment.
1041
static CLONE: std::sync::Mutex<()> = std::sync::Mutex::new(());
1042
1043
/// One lock per cached repository: fetches into it, and exports from it,
1044
/// never overlap, while jobs of other repositories go on. A slow repository
1045
/// (one kept in a bucket, say) once held every job on the runner waiting
1046
/// behind a single global lock.
10470×
fn repo_lock(name: &str) -> std::sync::Arc<std::sync::Mutex<()>> {
1048
    static LOCKS: std::sync::OnceLock<std::sync::Mutex<std::collections::HashMap<String, std::sync::Arc<std::sync::Mutex<()>>>>> =
1049
        std::sync::OnceLock::new();
10500×
    let mut locks = LOCKS.get_or_init(Default::default).lock().unwrap_or_else(|p| p.into_inner());
10510×
    locks.entry(name.to_string()).or_default().clone()
10520×
}
1053
1054
/// Seconds, to one decimal place, for the job's log.
10550×
fn secs(d: std::time::Duration) -> String {
10560×
    format!("{:.1} s", d.as_secs_f64())
10570×
}
1058
10590×
fn run_claim(home: &Home, hub: &Hub, cfg: &RunnerConfig, key: &RunnerKey, claim: &Claim) -> Result<Finish> {
10600×
    let started = Instant::now();
10610×
    let mut sink = LogSink {
10620×
        hub,
10630×
        job: claim.job_id,
10640×
        buf: Vec::new(),
10650×
        last: Instant::now(),
10660×
        gone: false,
10670×
        leaving: &LEAVING,
10680×
        started: Instant::now(),
10690×
        expected: claim.expected_ms.map(Duration::from_millis),
10700×
    };
10710×
    let note =
10720×
        |sink: &mut LogSink, text: String| sink.push(Record { t: started.elapsed().as_millis() as u64, stream: "flow".into(), text });
10730×
    let heads: Vec<ChangeHash> = claim.heads.iter().map(|h| ChangeHash::from_hex(h).context("bad head")).collect::<Result<_>>()?;
10740×
    note(&mut sink, format!("fetching {} for state {}", claim.repo, claim.heads.iter().map(|h| &h[..12]).collect::<Vec<_>>().join("+")));
1075
    // Preparing a workspace: fetches into a cached repository, and exports
1076
    // from it, are one job at a time per repository (`repo_lock`); taking
1077
    // cache disks and imaging the workspace are one job at a time on the
1078
    // runner (`PREPARE`); a first clone, whose token goes through the process
1079
    // environment, one at a time (`CLONE`).
10800×
    let main_lock = repo_lock(&claim.repo);
10810×
    let asked = Instant::now();
10820×
    let mut main_guard = Some(main_lock.lock().unwrap_or_else(|p| p.into_inner()));
10830×
    if asked.elapsed().as_secs() >= 2 {
10840×
        note(&mut sink, format!("waited {} for another job fetching {}", secs(asked.elapsed()), claim.repo));
10850×
    }
10860×
    let fetching = Instant::now();
10870×
    let repo = cached_repo(home, cfg, claim)?;
10880×
    let fetched = fetching.elapsed();
10890×
    let mut preparing = None;
10900×
    let scratch = home.root.join("work").join(format!("job-{}", claim.job_id));
10910×
    let _ = std::fs::remove_dir_all(&scratch);
10920×
    std::fs::create_dir_all(scratch.join("tree"))?;
10930×
    let result = (|| -> Result<Finish> {
10940×
        let exporting = Instant::now();
10950×
        let mut files = workspace::export_state(&repo, &heads, &scratch.join("tree"))?;
10960×
        main_guard.take();
10970×
        note(&mut sink, format!("fetched in {}, {} files exported in {}", secs(fetched), files.len(), secs(exporting.elapsed())));
1098
        // Pinned subrepos (Oxygen spec §7.8), at their paths, as part of the
1099
        // workspace and of the scope hash.
11000×
        for sub in &claim.subrepos {
11010×
            if sub.path.split('/').any(|p| p.is_empty() || p == "." || p == ".." || p == ".oxy") {
11020×
                bail!("subrepo path {:?} is not a clean relative path", sub.path);
11030×
            }
11040×
            note(
11050×
                &mut sink,
11060×
                format!(
1107
                    "fetching subrepo {} at {} for {}",
1108
                    sub.repo,
11090×
                    sub.heads.iter().map(|h| &h[..12]).collect::<Vec<_>>().join("+"),
1110
                    sub.path
1111
                ),
1112
            );
11130×
            let sub_lock = repo_lock(&sub.repo);
11140×
            let asked = Instant::now();
11150×
            let sub_guard = sub_lock.lock().unwrap_or_else(|p| p.into_inner());
11160×
            if asked.elapsed().as_secs() >= 2 {
11170×
                note(&mut sink, format!("waited {} for another job fetching {}", secs(asked.elapsed()), sub.repo));
11180×
            }
11190×
            let sub_repo = cached_repo_at(home, cfg, &sub.repo, &sub.clone_url, &claim.token)?;
11200×
            let sub_heads: Vec<ChangeHash> =
11210×
                sub.heads.iter().map(|h| ChangeHash::from_hex(h).context("bad subrepo head")).collect::<Result<_>>()?;
11220×
            let dir = scratch.join("tree").join(&sub.path);
11230×
            std::fs::create_dir_all(&dir)?;
11240×
            let sub_files = workspace::export_state(&sub_repo, &sub_heads, &dir)?;
11250×
            drop(sub_guard);
11260×
            files.extend(sub_files.into_iter().map(|(p, h)| (format!("{}/{p}", sub.path), h)));
1127
        }
11280×
        let scope_hash = scope_tree_hash(&claim.job.scope, files.iter().map(|(p, h)| (p.as_str(), *h)));
1129
        // Inputs (oxygenflow#58): each producing job's artifact, checked
1130
        // against the blob its receipt names, then put at its path. Not part
1131
        // of the scope: they are the run's, not the repository's.
11320×
        let mut input_blobs = Vec::new();
11330×
        for (index, i) in claim.inputs.iter().enumerate() {
11340×
            let what = format!("input {} from {}", i.artifact, i.from);
11350×
            let bytes = hub.input(claim.job_id, index).with_context(|| format!("{what}: fetching it"))?;
11360×
            let blob = place_input(&scratch.join("tree"), i, &bytes).with_context(|| what.clone())?;
11370×
            note(&mut sink, format!("{what}: {} bytes at {}, blob {} as its receipt names", bytes.len(), i.path, &i.blob[..12]));
11380×
            input_blobs.push(blob);
1139
        }
1140
        // The syscall tier runs on the tree itself; a microVM gets an image.
11410×
        let syscall_tier = claim.sandbox.runtime == flow_core::Runtime::Syscall;
11420×
        let wasm_tier = claim.sandbox.runtime == flow_core::Runtime::Wasm;
1143
        // The syscall and WASM tiers see the job's files as a directory;
1144
        // the MicroVM tier as an ext4 image.
11450×
        let dir_tier = syscall_tier || wasm_tier;
11460×
        let job = claim.job.in_sandbox(&claim.sandbox).with_flow_env(&claim.flow_env());
1147
        // Disk mounts that name a cache start from a kept disk (#28): a
1148
        // microVM takes an image already in place as it is, the syscall tier
1149
        // a directory (#70). Taken before the workspace is imaged: the
1150
        // sources the disk was built from give unchanged files their old
1151
        // times back (#52).
11520×
        let asked = Instant::now();
11530×
        preparing = Some(PREPARE.lock().unwrap_or_else(|p| p.into_inner()));
11540×
        if asked.elapsed().as_secs() >= 2 {
11550×
            note(&mut sink, format!("waited {} for another job imaging its workspace", secs(asked.elapsed())));
11560×
        }
11570×
        let pool = crate::cache::Pool::new(&home.root, cfg.cache_gb);
11580×
        let form = if dir_tier { crate::cache::Form::Dir } else { crate::cache::Form::Image };
11590×
        let cache_ctx =
11600×
            crate::cache::Ctx { repo: &claim.repo, bookmark: &claim.bookmark, job: &claim.job.name, image: &claim.sandbox.rootfs, form };
11610×
        let mut cached: Vec<(usize, String, String)> = Vec::new();
11620×
        let mut built_from: Option<crate::cache::Sources> = None;
11630×
        for (i, m) in job.mounts.iter().filter(|m| m.source == flow_core::pipeline::MountSource::Disk).enumerate() {
11640×
            let Some(name) = &m.cache else { continue };
11650×
            let key = crate::cache::Pool::key(&cache_ctx, m, |p| files.iter().find(|(f, _)| f == p).map(|(_, h)| hex::encode(h)));
11660×
            let how = match pool.take(&cache_ctx, m, &key, &crate::cache::disk_path(form, &scratch, i)) {
11670×
                Some(t) => {
11680×
                    if built_from.is_none() {
11690×
                        built_from = t.sources;
11700×
                    }
11710×
                    t.how
1172
                }
11730×
                None => format!("cache {name}: none kept yet, an empty disk"),
1174
            };
11750×
            note(&mut sink, format!("{} ({})", how, m.target));
1176
            // What the job reads is seen when the disk is pruned (#72).
11770×
            if let Err(e) = crate::cache::forget_reads(form, &crate::cache::disk_path(form, &scratch, i)) {
11780×
                note(&mut sink, format!("cache {name}: {e:#}"));
11790×
            }
11800×
            cached.push((i, key, how));
1181
        }
1182
        // What the job reads or writes on its cache from now on is what it
1183
        // used; the rest may be pruned before the cache is kept (#72).
11840×
        let cache_started = if cached.is_empty() { std::time::SystemTime::now() } else { flow_init::prune::start_clock() };
11850×
        let sources = if cached.is_empty() {
11860×
            crate::cache::Sources::new()
1187
        } else {
11880×
            let (sources, restored) = workspace::restore_times(&scratch.join("tree"), &files, built_from.as_ref());
11890×
            if built_from.is_some() {
11900×
                note(
11910×
                    &mut sink,
11920×
                    format!(
11930×
                        "cache: {restored} of {} files and directories unchanged since the cached build, their times kept",
11940×
                        sources.len()
11950×
                    ),
11960×
                );
11970×
            }
11980×
            sources
1199
        };
1200
        // An earlier attempt's checkpoint (oxygenflow#77): back in place,
1201
        // over the cache, before the same exec runs again; the receipt
1202
        // lists it among the job's inputs.
12030×
        if let Some(blob) = &claim.checkpoint {
12040×
            if dir_tier {
12050×
                let bytes = hub.checkpoint(claim.job_id).context("fetching the checkpoint")?;
12060×
                if Repo::blob_ref(&bytes).to_hex() != *blob {
12070×
                    bail!("the checkpoint fetched is not blob {}, as the claim names", &blob[..12.min(blob.len())]);
12080×
                }
12090×
                let place = |root: &str| crate::checkpoint::host_dir(root, &job, &scratch.join("tree"), &scratch, wasm_tier);
12100×
                let n = crate::checkpoint::unpack(&bytes, &job.checkpoints, place)?;
12110×
                note(
12120×
                    &mut sink,
12130×
                    format!("restored checkpoint {}: {} files, {} bytes, from the attempt handed back", &blob[..12], n.files, n.bytes),
12140×
                );
12150×
                input_blobs.push(Repo::blob_ref(&bytes).0);
12160×
            } else {
12170×
                note(&mut sink, "a checkpoint was saved, but only the WASM and syscall tiers restore one yet: starting again".into());
12180×
            }
12190×
        }
12200×
        if !dir_tier {
12210×
            workspace::image(&scratch.join("tree"), &scratch.join("workspace.ext4"))?;
12220×
            std::fs::remove_dir_all(scratch.join("tree"))?;
12230×
        }
12240×
        preparing.take();
1225
        // Cancelled while it was being prepared: no sandbox.
12260×
        if microvm::Sink::cancelled(&mut sink) {
12270×
            return Ok(cancelled());
12280×
        }
12290×
        if wasm_tier {
12300×
            note(&mut sink, format!("starting WASM (wasmtime {}): {} MiB", crate::wasm::WASMTIME, claim.sandbox.memory_mib));
12310×
        } else {
12320×
            note(
12330×
                &mut sink,
12340×
                format!(
1235
                    "{}: {} {}, {} MiB, rootfs {}",
12360×
                    if syscall_tier { "starting a syscall sandbox" } else { "booting a microVM" },
1237
                    claim.sandbox.cpus,
12380×
                    if syscall_tier { "CPU" } else { "vCPU" },
1239
                    claim.sandbox.memory_mib,
12400×
                    &claim.sandbox.rootfs[..12]
1241
                ),
1242
            );
1243
        }
12440×
        let timeout = Duration::from_secs(claim.timeout_s);
12450×
        let mut outcome = if wasm_tier {
12460×
            crate::wasm::run(&claim.sandbox, &job, &scratch.join("tree"), &scratch, timeout, &mut sink)?
12470×
        } else if syscall_tier {
12480×
            let group = format!("job-{}", claim.job_id);
12490×
            crate::syscall::run(home, &claim.sandbox, &job, &claim.secrets, &scratch.join("tree"), &scratch, timeout, &mut sink, &group)?
1250
        } else {
12510×
            microvm::run(home, &claim.sandbox, &job, &claim.secrets, &scratch.join("workspace.ext4"), &scratch, timeout, &mut sink)?
1252
        };
12530×
        if outcome.cancelled {
1254
            // Handed back as the runner leaves: its checkpoints first, for
1255
            // the next attempt (oxygenflow#77).
12560×
            if leaving().is_some() && !job.checkpoints.is_empty() {
12570×
                save_checkpoint(hub, claim.job_id, &job, &scratch, dir_tier, wasm_tier, |t| note(&mut sink, t));
12580×
            }
12590×
            return Ok(cancelled());
12600×
        }
1261
        // The receipt says what a cached disk started from.
12620×
        let disk_mounts: Vec<&flow_core::pipeline::Mount> =
12630×
            job.mounts.iter().filter(|m| m.source == flow_core::pipeline::MountSource::Disk).collect();
12640×
        for (i, key, how) in &cached {
12650×
            outcome.environment.parts.push((format!("cache {}", disk_mounts[*i].target), format!("{key}: {how}")));
12660×
        }
1267
        // A passing job's artifacts, read from its disks and uploaded; a
1268
        // declared artifact that cannot be kept fails the job. A failing
1269
        // job keeps only its `when "always"` ones (oxygenflow#37), outside
1270
        // its receipt, and one it cannot keep is only noted.
12710×
        let mut outputs = vec![];
12720×
        let mut output_error = None;
12730×
        let passed = outcome.exit_code == Some(0);
12740×
        let wanted = claim.job.outputs.iter().filter(|o| passed || o.always);
12750×
        for o in wanted {
12760×
            if o.kind == flow_core::OutputKind::Report {
12770×
                let read = if dir_tier {
12780×
                    let (dir, inner) = crate::outputs::locate_dir(&claim.job, &scratch.join("tree"), &scratch, &o.path);
12790×
                    crate::outputs::read_report_dir(&dir, &inner)
1280
                } else {
12810×
                    let (image, inner) = crate::outputs::locate(&claim.job, &scratch.join("workspace.ext4"), &scratch, &o.path);
12820×
                    crate::outputs::read_report(&image, &inner, &scratch)
1283
                };
12840×
                let kept = read.and_then(|files| upload_report(hub, claim.job_id, &o.name, &files));
12850×
                match kept {
12860×
                    Ok((blob, files, bytes)) => {
12870×
                        let unattested = if passed { "" } else { " (the job failed: not in its receipt)" };
12880×
                        let hex = blob.to_hex();
12890×
                        note(&mut sink, format!("report {}: {files} files, {bytes} bytes, manifest {}{unattested}", o.name, &hex[..12]));
12900×
                        if passed {
12910×
                            outputs.push(blob.0);
12920×
                        }
1293
                    }
12940×
                    Err(e) if passed => {
12950×
                        output_error = Some(format!("report {}: {e:#}", o.name));
12960×
                        break;
1297
                    }
12980×
                    Err(e) => note(&mut sink, format!("report {}: not kept: {e:#}", o.name)),
1299
                }
13000×
                continue;
13010×
            }
13020×
            let read = if dir_tier {
13030×
                let (dir, inner) = crate::outputs::locate_dir(&claim.job, &scratch.join("tree"), &scratch, &o.path);
13040×
                crate::outputs::read_dir_file(&dir, &inner)
1305
            } else {
13060×
                let (image, inner) = crate::outputs::locate(&claim.job, &scratch.join("workspace.ext4"), &scratch, &o.path);
13070×
                crate::outputs::read(&image, &inner, &scratch)
1308
            };
13090×
            let kept = read.and_then(|bytes| {
13100×
                let blob = Repo::blob_ref(&bytes);
13110×
                let named = hub.artifact(claim.job_id, &o.name, &bytes)?;
13120×
                if named != blob.to_hex() {
13130×
                    bail!("the hub kept it as {named}, not {}", blob.to_hex());
13140×
                }
13150×
                let unattested = if passed { "" } else { " (the job failed: not in its receipt)" };
13160×
                note(&mut sink, format!("artifact {}: {} bytes, blob {}{unattested}", o.name, bytes.len(), &named[..12]));
13170×
                Ok(blob.0)
13180×
            });
13190×
            match kept {
13200×
                Ok(b) if passed => outputs.push(b),
13210×
                Ok(_) => {}
13220×
                Err(e) if passed => {
13230×
                    output_error = Some(format!("artifact {}: {e:#}", o.name));
13240×
                    break;
1325
                }
13260×
                Err(e) => note(&mut sink, format!("artifact {}: not kept: {e:#}", o.name)),
1327
            }
1328
        }
13290×
        if let Some(e) = &output_error {
13300×
            note(&mut sink, e.clone());
13310×
        }
13320×
        let receipt = outcome.exit_code.filter(|_| output_error.is_none()).map(|code| Receipt {
13330×
            job_name: claim.job.name.clone(),
13340×
            pipeline_hash: hex32(&claim.pipeline_hash),
13350×
            scope_tree_hash: scope_hash,
13360×
            inputs: input_blobs.clone(),
13370×
            environment: outcome.environment.hash(),
13380×
            outputs,
13390×
            exit_code: code as u32,
13400×
            duration_ms: outcome.duration_ms,
13410×
        });
13420×
        let signed_receipt = match &receipt {
13430×
            Some(r) => {
13440×
                let mut signed = sign_receipt(&repo, &heads, cfg, key, claim, r)?;
13450×
                if cfg.keyless {
13460×
                    match sign_keyless(&repo, &heads, cfg, hub, claim, r) {
13470×
                        Ok(k) => signed = k,
13480×
                        Err(e) => {
13490×
                            note(&mut sink, format!("receipt: signed with the runner's key; a short-lived key was not certified: {e:#}"))
1350
                        }
1351
                    }
13520×
                }
13530×
                Some(hex::encode(signed.encode()))
1354
            }
13550×
            None => None,
1356
        };
1357
        // Measured before a cached disk leaves the scratch directory.
13580×
        let peak_disk_mib = crate::facts::allocated_mib(&scratch);
1359
        // A passing job's cached disks are pruned and kept (#72); a
1360
        // failing job's are thrown away, so nothing it wrote reaches a
1361
        // later job.
13620×
        let kept = passed && output_error.is_none();
13630×
        for (i, key, _) in &cached {
13640×
            let disk = crate::cache::disk_path(form, &scratch, *i);
13650×
            let m = disk_mounts[*i];
13660×
            let prune = crate::cache::Prune {
13670×
                started: cache_started,
13680×
                percent: cfg.cache_prune_percent.unwrap_or(flow_init::prune::DEFAULT_PERCENT),
13690×
                guest: outcome.pruned.iter().find(|(t, _)| *t == m.target).map(|(_, p)| p),
1370
            };
13710×
            match pool.settle(&cache_ctx, m, key, &disk, &sources, kept, &prune) {
13720×
                Ok(Some(line)) => note(&mut sink, line),
13730×
                Ok(None) => {}
13740×
                Err(e) => note(&mut sink, format!("cache: not {}: {e:#}", if kept { "kept" } else { "discarded" })),
1375
            }
1376
        }
1377
        Ok(Finish {
13780×
            exit_code: outcome.exit_code,
13790×
            duration_ms: started.elapsed().as_millis() as u64,
13800×
            receipt,
13810×
            signed_receipt,
13820×
            error: output_error.or_else(|| outcome.timed_out.then(|| "stopped at the time limit".to_string())),
1383
            // What the job took (oxygenflow#41): its disks are sparse files
1384
            // in the scratch directory, so their blocks now are their peak.
13850×
            peak_disk_mib,
13860×
            peak_memory_mib: outcome.peak_memory_mib,
1387
        })
1388
    })();
13890×
    let _ = workspace::remove_tree(&scratch);
13900×
    sink.flush();
13910×
    result
13920×
}
1393
1394
/// Bind `receipt` to the state of `heads` in `repo` and sign it as the
1395
/// runner (Oxygen spec §14.6). The state is computed here, not taken from
1396
/// the claim, so the runner vouches only for what it fetched.
1397
/// Upload a report's files, then its manifest under the report's name, and
1398
/// check the hub kept each as the blob it should (oxygenhub#127). Answers
1399
/// the manifest's blob, the file count and their total size.
14000×
fn upload_report(hub: &Hub, job: i64, name: &str, files: &[(String, Vec<u8>)]) -> Result<(oxy_core::hash::ObjectRef, usize, u64)> {
14010×
    let mut listed = Vec::with_capacity(files.len());
14020×
    let mut total = 0u64;
14030×
    for (path, bytes) in files {
14040×
        let blob = Repo::blob_ref(bytes).to_hex();
14050×
        let named = hub.report_file(job, name, path, bytes).with_context(|| format!("uploading {path}"))?;
14060×
        if named != blob {
14070×
            bail!("the hub kept {path} as {named}, not {blob}");
14080×
        }
14090×
        total += bytes.len() as u64;
14100×
        listed.push(serde_json::json!({ "path": path, "blob": blob, "size": bytes.len() }));
1411
    }
14120×
    let manifest = serde_json::to_vec(&serde_json::json!({ "version": 1, "files": listed }))?;
14130×
    let blob = Repo::blob_ref(&manifest);
14140×
    let named = hub.artifact(job, name, &manifest)?;
14150×
    if named != blob.to_hex() {
14160×
        bail!("the hub kept the manifest as {named}, not {}", blob.to_hex());
14170×
    }
14180×
    Ok((blob, files.len(), total))
14190×
}
1420
14210×
fn sign_receipt(
14220×
    repo: &Repo,
14230×
    heads: &[ChangeHash],
14240×
    cfg: &RunnerConfig,
14250×
    key: &RunnerKey,
14260×
    claim: &Claim,
14270×
    receipt: &Receipt,
14280×
) -> Result<oxy_core::receipt::SignedReceipt> {
14290×
    let state = state_of(heads);
14300×
    let run = format!("{}/{}/flow/{}", cfg.hub.trim_end_matches('/'), claim.repo, claim.run_number);
14310×
    Ok(oxy_core::receipt::SignedReceipt::sign(receipt.to_oxy(), repo.id()?, state, &run, &key.identity, &key.secret))
14320×
}
1433
1434
/// Sign `receipt` with a fresh key the hub certifies for this job now,
1435
/// just before signing, so the certificate covers the moment the hub
1436
/// accepts it (keyless, oxygenhub#241). The key is dropped with the
1437
/// receipt signed: nothing long-lived signs.
14380×
fn sign_keyless(
14390×
    repo: &Repo,
14400×
    heads: &[ChangeHash],
14410×
    cfg: &RunnerConfig,
14420×
    hub: &Hub,
14430×
    claim: &Claim,
14440×
    receipt: &Receipt,
14450×
) -> Result<oxy_core::receipt::SignedReceipt> {
14460×
    let sk = oxy_core::identity::SecretKey::generate();
14470×
    let now = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map(|d| d.as_millis() as u64).unwrap_or(0);
14480×
    let name = format!("{} job {}", cfg.name.as_deref().unwrap_or("runner"), claim.job_id);
14490×
    let id = sk.identity(&name, "", now);
14500×
    let proof = sk.sign_challenge(&id.hash(), &oxy_core::cert::certify_challenge(&claim.token)).map_err(|e| anyhow::anyhow!("{e}"))?;
14510×
    let (cert, issuer) = hub.certify(&claim.token, &id, &proof)?;
14520×
    let state = state_of(heads);
14530×
    let run = format!("{}/{}/flow/{}", cfg.hub.trim_end_matches('/'), claim.repo, claim.run_number);
14540×
    Ok(oxy_core::receipt::SignedReceipt::sign(receipt.to_oxy(), repo.id()?, state, &run, &id, &sk).with_certificate(cert, issuer))
14550×
}
1456
1457
/// The ObjectRef of the state whose heads are `heads` (Oxygen spec §10.1).
14580×
pub fn state_of(heads: &[ChangeHash]) -> oxy_core::hash::ObjectRef {
1459
    use oxy_core::hash::{hash_object, ObjectType};
14600×
    hash_object(ObjectType::State, &oxy_core::objects::StateObject::new(heads.to_vec()).encode())
14610×
}
1462
14630×
fn hex32(s: &str) -> [u8; 32] {
14640×
    let mut out = [0; 32];
14650×
    if let Ok(v) = hex::decode(s) {
14660×
        if v.len() == 32 {
14670×
            out.copy_from_slice(&v);
14680×
        }
14690×
    }
14700×
    out
14710×
}
1472
1473
/// Whether a network error is worth another try: DNS, a refused or reset
1474
/// connection, a timeout, or a gateway answering 502, 503 or 504 while the
1475
/// hub restarts (oxygenhub#111).
14768×
fn transient(msg: &str) -> bool {
14778×
    let m = msg.to_lowercase();
14788×
    [
14798×
        "dns failed",
14808×
        "name resolution",
14818×
        "connection refused",
14828×
        "connection reset",
14838×
        "timed out",
14848×
        "timeout",
14858×
        "http 502",
14868×
        "http 503",
14878×
        "http 504",
14888×
        "broken pipe",
14898×
        "unexpected eof",
14908×
    ]
14918×
    .iter()
149247×
    .any(|k| m.contains(k))
14938×
}
1494
1495
/// Run `f` again after a transient network error, waiting `waits` between
1496
/// tries (about a minute in all), and give up on any other error at once.
14973×
fn with_retries<T>(waits: &[Duration], mut f: impl FnMut() -> Result<T>) -> Result<T> {
14983×
    let mut tries = waits.iter();
1499
    loop {
15007×
        match f() {
15011×
            Ok(v) => return Ok(v),
15026×
            Err(e) => match tries.next() {
15035×
                Some(w) if transient(&format!("{e:#}")) => std::thread::sleep(*w),
15042×
                _ => return Err(e),
1505
            },
1506
        }
1507
    }
15083×
}
1509
1510
/// The waits between tries of a fetch: 2, 4, 8, 16 and 30 seconds.
1511
const FETCH_WAITS: [Duration; 5] =
1512
    [Duration::from_secs(2), Duration::from_secs(4), Duration::from_secs(8), Duration::from_secs(16), Duration::from_secs(30)];
1513
1514
/// The runner's copy of a repository, fetched up to date with the job's token.
15150×
fn cached_repo(home: &Home, cfg: &RunnerConfig, claim: &Claim) -> Result<Repo> {
15160×
    cached_repo_at(home, cfg, &claim.repo, &claim.clone_url, &claim.token)
15170×
}
1518
1519
/// The runner's copy of `repo`, cloned or fetched with `token`.
15200×
fn cached_repo_at(home: &Home, cfg: &RunnerConfig, repo_name: &str, clone_url: &str, token: &str) -> Result<Repo> {
15210×
    let dir: PathBuf = home.root.join("repos").join(repo_name.replace('/', "__"));
15220×
    let set_remote = |repo: &mut Repo| -> Result<()> {
15230×
        repo.config.set("remote.origin.url", clone_url).map_err(|e| anyhow::anyhow!("{e}"))?;
15240×
        repo.config.set("remote.origin.token", token).map_err(|e| anyhow::anyhow!("{e}"))?;
15250×
        if let Some(ca) = &cfg.ca {
15260×
            repo.config.set("remote.origin.ca", &ca.to_string_lossy()).map_err(|e| anyhow::anyhow!("{e}"))?;
15270×
        }
15280×
        repo.save_config().map_err(|e| anyhow::anyhow!("{e}"))
15290×
    };
15300×
    if dir.join(".oxy").is_dir() {
15310×
        let mut repo = Repo::open(&dir).map_err(|e| anyhow::anyhow!("{e}"))?;
15320×
        set_remote(&mut repo)?;
15330×
        with_retries(&FETCH_WAITS, || repo.fetch("origin").map(|_| ()).map_err(|e| anyhow::anyhow!("fetch {clone_url}: {e}")))?;
15340×
        return Ok(repo);
15350×
    }
1536
    // First job for this repository: clone with the job's token, which goes
1537
    // through the process environment, so one clone at a time.
15380×
    let _clone = CLONE.lock().unwrap_or_else(|p| p.into_inner());
15390×
    std::env::set_var("OXY_TOKEN", token);
15400×
    if let Some(ca) = &cfg.ca {
15410×
        std::env::set_var("OXY_CA", ca);
15420×
    }
15430×
    let cloned = with_retries(&FETCH_WAITS, || {
15440×
        let _ = std::fs::remove_dir_all(&dir);
15450×
        Repo::clone(clone_url, &dir).map_err(|e| anyhow::anyhow!("{e}"))
15460×
    });
15470×
    std::env::remove_var("OXY_TOKEN");
15480×
    std::env::remove_var("OXY_CA");
15490×
    let mut repo = cloned.map_err(|e| {
15500×
        let _ = std::fs::remove_dir_all(&dir);
15510×
        anyhow::anyhow!("clone {}: {e}", clone_url)
15520×
    })?;
15530×
    set_remote(&mut repo)?;
15540×
    Ok(repo)
15550×
}
1556
1557
#[cfg(test)]
1558
mod tests {
1559
1560
    #[test]
15611×
    fn an_input_is_placed_only_when_it_is_what_the_receipt_names() {
15621×
        let dir = tempfile::tempdir().unwrap();
15631×
        let bytes = b"the reviewed plan";
15641×
        let blob = Repo::blob_ref(bytes).to_hex();
15651×
        let input = |path: &str, blob: &str| flow_core::api::ArtifactInput {
15666×
            artifact: "tfplan".into(),
15676×
            from: "plan".into(),
15686×
            path: path.into(),
15696×
            blob: blob.into(),
15706×
        };
15711×
        let got = super::place_input(dir.path(), &input("/src/plans/tfplan", &blob), bytes).unwrap();
15721×
        assert_eq!(hex::encode(got), blob);
15731×
        assert_eq!(std::fs::read(dir.path().join("plans/tfplan")).unwrap(), bytes);
15741×
        let wrong = super::place_input(dir.path(), &input("/src/other", &"0".repeat(64)), bytes).unwrap_err();
15751×
        assert!(format!("{wrong:#}").contains("not what plan's receipt names"), "{wrong:#}");
15761×
        assert!(!dir.path().join("other").exists(), "nothing written when it does not match");
15774×
        for bad in ["/etc/passwd", "/src/../x", "/src/.oxy/x", "/src/"] {
15784×
            assert!(super::place_input(dir.path(), &input(bad, &blob), bytes).is_err(), "{bad}");
1579
        }
15801×
    }
1581
1582
    use super::*;
1583
1584
    #[test]
15851×
    fn a_runner_names_what_stops_a_sandbox() {
15861×
        let dir = tempfile::tempdir().unwrap();
15871×
        let home = Home::locate(Some(dir.path())).unwrap();
15881×
        let bytes = b"not really ext4";
15891×
        let hash = blake3::hash(bytes).to_hex().to_string();
15901×
        let mut sb: flow_core::Sandbox = serde_json::from_value(serde_json::json!({
15911×
            "name": "s", "runtime": "syscall", "rootfs": "ab".repeat(32), "memory_mib": 1024, "cpus": 1, "network": "isolated"
1592
        }))
15931×
        .unwrap();
15946×
        let problem = |sb: &flow_core::Sandbox, free| sandbox_problem(&home, sb, "x86_64", free);
15951×
        assert_eq!(problem(&sb, None).unwrap(), "rootfs abababababab is not on this runner");
15961×
        std::fs::write(home.rootfs(&hash), bytes).unwrap();
15971×
        sb.rootfs = hash.clone();
15981×
        assert_eq!(problem(&sb, Some(4096)), None);
15991×
        assert_eq!(problem(&sb, Some(512)).unwrap(), "only 512 MiB of memory is free here; the sandbox needs 1024 MiB");
16001×
        std::fs::write(home.image_manifest(&hash), r#"{"arch":"riscv64"}"#).unwrap();
16011×
        assert_eq!(problem(&sb, None).unwrap(), format!("rootfs {} is for riscv64; this runner is x86_64", &hash[..12]));
16021×
        sb.arch = Some("aarch64".into());
16031×
        assert_eq!(problem(&sb, None).unwrap(), "the sandbox needs aarch64; this runner is x86_64");
16041×
        sb.arch = None;
16051×
        std::fs::remove_file(home.image_manifest(&hash)).unwrap();
16061×
        std::fs::write(home.rootfs(&hash), b"changed").unwrap();
16071×
        assert!(problem(&sb, None).unwrap().contains("does not verify"));
16081×
    }
1609
1610
    #[test]
16111×
    fn a_runner_reads_an_unrecorded_images_architecture_and_declines_another() {
1612
        // An image fetched or imported with no recorded architecture, built
1613
        // for riscv64: the runner reads its shell, records it, and declines
1614
        // instead of running it and failing (spec §11.2, §11.5).
16151×
        let dir = tempfile::tempdir().unwrap();
16161×
        let home = Home::locate(Some(dir.path().join("home").as_path())).unwrap();
16171×
        let tree = dir.path().join("tree");
16181×
        std::fs::create_dir_all(tree.join("bin")).unwrap();
16191×
        let mut elf = vec![0u8; 64];
16201×
        elf[..7].copy_from_slice(b"\x7fELF\x02\x01\x01");
16211×
        elf[18..20].copy_from_slice(&0xF3u16.to_le_bytes());
16221×
        std::fs::write(tree.join("bin/sh"), &elf).unwrap();
16231×
        let img = dir.path().join("rootfs.ext4");
16241×
        let made = std::process::Command::new("mkfs.ext4").args(["-q", "-F", "-d"]).arg(&tree).arg(&img).arg("8M").status();
16251×
        if !made.is_ok_and(|s| s.success()) {
16260×
            eprintln!("mkfs.ext4 not found: skipped");
16270×
            return;
16281×
        }
16291×
        let hash = crate::home::hash_file(&img).unwrap();
16301×
        std::fs::create_dir_all(home.rootfs(&hash).parent().unwrap()).unwrap();
16311×
        std::fs::rename(&img, home.rootfs(&hash)).unwrap();
16321×
        assert!(!home.image_manifest(&hash).exists());
16331×
        let sb: flow_core::Sandbox = serde_json::from_value(serde_json::json!({
16341×
            "name": "s", "runtime": "syscall", "rootfs": hash, "memory_mib": 64, "cpus": 1, "network": "isolated"
1635
        }))
16361×
        .unwrap();
16371×
        assert_eq!(
16381×
            sandbox_problem(&home, &sb, "x86_64", None).unwrap(),
16391×
            format!("rootfs {} is for riscv64; this runner is x86_64", &hash[..12])
1640
        );
16411×
        assert_eq!(sandbox_problem(&home, &sb, "riscv64", None), None, "a riscv64 runner takes it");
1642
        // Learned: recorded once, and reported with the runner's claims.
16431×
        let manifest: serde_json::Value = serde_json::from_slice(&std::fs::read(home.image_manifest(&hash)).unwrap()).unwrap();
16441×
        assert_eq!(manifest["arch"], "riscv64");
16451×
        assert_eq!(home.image_archs().get(&hash).map(String::as_str), Some("riscv64"));
16461×
    }
1647
1648
    #[test]
16491×
    fn transient_network_errors_are_tried_again_and_others_are_not() {
16501×
        assert!(transient("fetch x: Dns Failed: resolve dns name 'oxygenhub.io:443': Temporary failure in name resolution"));
16511×
        assert!(transient("HTTP 503: the hub is restarting"));
16521×
        assert!(!transient("HTTP 404: no such repository"));
16531×
        let mut n = 0;
16543×
        let got: Result<u32> = with_retries(&[Duration::ZERO, Duration::ZERO], || {
16553×
            n += 1;
16563×
            if n < 3 {
16572×
                Err(anyhow::anyhow!("connection refused"))
1658
            } else {
16591×
                Ok(7)
1660
            }
16613×
        });
16621×
        assert_eq!((got.unwrap(), n), (7, 3), "two retries, then success");
16631×
        let mut m = 0;
16641×
        let got: Result<u32> = with_retries(&[Duration::ZERO; 4], || {
16651×
            m += 1;
16661×
            Err(anyhow::anyhow!("HTTP 403: forbidden"))
16671×
        });
16681×
        assert!(got.is_err());
16691×
        assert_eq!(m, 1, "a refusal is not tried again");
16701×
        let mut k = 0;
16713×
        let got: Result<u32> = with_retries(&[Duration::ZERO; 2], || {
16723×
            k += 1;
16733×
            Err(anyhow::anyhow!("timed out"))
16743×
        });
16751×
        assert!(got.is_err());
16761×
        assert_eq!(k, 3, "gives up after the last wait");
16771×
    }
1678
1679
    /// A hub that answers each request with the next of `codes`, counting them.
16809×
    fn fake_hub(codes: Vec<u16>) -> (String, std::sync::Arc<std::sync::atomic::AtomicUsize>) {
16819×
        fake_hub_on(std::net::TcpListener::bind("127.0.0.1:0").unwrap(), codes)
16829×
    }
1683
1684
    /// A hub at `listener` answering each request with the next of `codes`.
168511×
    fn fake_hub_on(listener: std::net::TcpListener, codes: Vec<u16>) -> (String, std::sync::Arc<std::sync::atomic::AtomicUsize>) {
1686
        use std::io::{Read, Write};
168711×
        let addr = listener.local_addr().unwrap();
168811×
        let seen = std::sync::Arc::new(std::sync::atomic::AtomicUsize::new(0));
168911×
        let count = seen.clone();
169011×
        std::thread::spawn(move || {
169123×
            for code in codes {
169223×
                let (mut s, _) = listener.accept().unwrap();
1693
                // Read the whole request (headers, then Content-Length bytes
1694
                // of body) before answering: closing early would reset the
1695
                // connection while the client is still sending.
169623×
                let mut req = Vec::new();
169723×
                let mut buf = [0u8; 8192];
1698
                loop {
169928×
                    let n = s.read(&mut buf).unwrap_or(0);
170028×
                    if n == 0 {
17010×
                        break;
170228×
                    }
170328×
                    req.extend_from_slice(&buf[..n]);
170428×
                    let text = String::from_utf8_lossy(&req);
170528×
                    if let Some(end) = text.find("\r\n\r\n") {
170628×
                        let len = text[..end]
170728×
                            .lines()
1708220×
                            .find_map(|l| {
1709220×
                                l.to_ascii_lowercase().strip_prefix("content-length:").map(|v| v.trim().parse::<usize>().unwrap_or(0))
1710220×
                            })
171128×
                            .unwrap_or(0);
171228×
                        if req.len() >= end + 4 + len {
171323×
                            break;
17145×
                        }
17150×
                    }
1716
                }
171723×
                count.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
171823×
                let reason = if code == 204 { "No Content" } else { "Error" };
171923×
                let _ = write!(s, "HTTP/1.1 {code} {reason}\r\nContent-Length: 0\r\nConnection: close\r\n\r\n");
1720
            }
172111×
        });
172211×
        (format!("http://{addr}"), seen)
172311×
    }
1724
1725
    /// A hub that answers one request with `body` (status 200) and hands
1726
    /// back what it was sent.
17271×
    fn fake_json_hub(body: &'static str) -> (String, std::sync::mpsc::Receiver<String>) {
1728
        use std::io::{Read, Write};
17291×
        let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
17301×
        let addr = listener.local_addr().unwrap();
17311×
        let (tx, rx) = std::sync::mpsc::channel();
17321×
        std::thread::spawn(move || {
17331×
            let (mut s, _) = listener.accept().unwrap();
17341×
            let mut req = Vec::new();
17351×
            let mut buf = [0u8; 65536];
1736
            loop {
17371×
                let n = s.read(&mut buf).unwrap_or(0);
17381×
                if n == 0 {
17390×
                    break;
17401×
                }
17411×
                req.extend_from_slice(&buf[..n]);
17421×
                let text = String::from_utf8_lossy(&req);
17431×
                if let Some(end) = text.find("\r\n\r\n") {
17441×
                    let len = text[..end]
17451×
                        .lines()
17467×
                        .find_map(|l| {
17477×
                            l.to_ascii_lowercase().strip_prefix("content-length:").map(|v| v.trim().parse::<usize>().unwrap_or(0))
17487×
                        })
17491×
                        .unwrap_or(0);
17501×
                    if req.len() >= end + 4 + len {
17511×
                        break;
17520×
                    }
17530×
                }
1754
            }
17551×
            tx.send(String::from_utf8_lossy(&req).into_owned()).unwrap();
17561×
            let _ = write!(
17571×
                s,
1758
                "HTTP/1.1 200 OK\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{body}",
17591×
                body.len()
1760
            );
17611×
        });
17621×
        (format!("http://{addr}"), rx)
17631×
    }
1764
1765
    #[test]
17661×
    fn registering_binds_the_key_and_keeps_the_credential_private() {
1767
        use std::os::unix::fs::PermissionsExt;
17681×
        let dir = tempfile::tempdir().unwrap();
17691×
        let home = Home::locate(Some(dir.path())).unwrap();
17701×
        let (hub, sent) = fake_json_hub(r#"{"id":7,"name":"plex","credential":"flowrunner_secret"}"#);
17711×
        let got = register(&home, &hub, " reg-token ", "plex", None, vec!["gpu".into()]).unwrap();
17721×
        assert_eq!((got.id, got.name.as_str()), (7, "plex"));
17731×
        let req = sent.recv().unwrap();
17741×
        assert!(req.starts_with("POST /api/v1/flow/runners/register"), "{req}");
17751×
        let body: Register = serde_json::from_str(&req[req.find("\r\n\r\n").unwrap() + 4..]).unwrap();
17761×
        assert_eq!((body.token.as_str(), body.info.labels.clone()), ("reg-token", vec!["gpu".to_string()]));
17771×
        let key = home.runner_key("plex").unwrap();
17781×
        assert_eq!(body.identity, hex::encode(key.identity.encode()), "the runner's signing identity");
17791×
        let path = dir.path().join(crate::home::RUNNER_TOML);
17801×
        assert_eq!(std::fs::metadata(&path).unwrap().permissions().mode() & 0o777, 0o600);
1781
        // The runner then starts from runner.toml.
17821×
        let again = Home::locate(Some(dir.path())).unwrap();
17831×
        let cfg = again.config.runner.unwrap();
17841×
        assert_eq!((cfg.hub.as_str(), cfg.token.as_str(), cfg.name.as_deref()), (hub.as_str(), "flowrunner_secret", Some("plex")));
17851×
        assert_eq!(cfg.labels, ["gpu"]);
17861×
    }
1787
1788
    /// A hub that answers certify with a certificate `sign_as` signs for
1789
    /// `cert_key`, and publishes `published` as its key: two requests.
17903×
    fn fake_certify_hub(
17913×
        sign_as: (oxy_core::identity::Identity, oxy_core::identity::SecretKey),
17923×
        cert_key: oxy_core::identity::Identity,
17933×
        published: oxy_core::identity::Identity,
17943×
    ) -> String {
1795
        use std::io::{Read, Write};
17963×
        let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
17973×
        let addr = listener.local_addr().unwrap();
17983×
        std::thread::spawn(move || {
17993×
            for _ in 0..2 {
18006×
                let Ok((mut s, _)) = listener.accept() else { return };
18016×
                let mut req = Vec::new();
18026×
                let mut buf = [0u8; 65536];
1803
                loop {
18048×
                    let n = s.read(&mut buf).unwrap_or(0);
18058×
                    if n == 0 {
18060×
                        break;
18078×
                    }
18088×
                    req.extend_from_slice(&buf[..n]);
18098×
                    let text = String::from_utf8_lossy(&req);
18108×
                    if let Some(end) = text.find("\r\n\r\n") {
18118×
                        let len = text[..end]
18128×
                            .lines()
181355×
                            .find_map(|l| {
181455×
                                l.to_ascii_lowercase().strip_prefix("content-length:").map(|v| v.trim().parse::<usize>().unwrap_or(0))
181555×
                            })
18168×
                            .unwrap_or(0);
18178×
                        if req.len() >= end + 4 + len {
18186×
                            break;
18192×
                        }
18200×
                    }
1821
                }
18226×
                let line = String::from_utf8_lossy(&req).lines().next().unwrap_or("").to_string();
18236×
                let body: Vec<u8> = if line.contains("/keyless/certify") {
18243×
                    let cert = oxy_core::cert::SignedCertificate::sign(
18253×
                        oxy_core::cert::Certificate {
18263×
                            key: cert_key.clone(),
18273×
                            issuer: sign_as.0.hash(),
18283×
                            subject: "repo:andy/demo:bookmark:main".into(),
18293×
                            claims: vec![],
18303×
                            scope: oxy_core::identity::Scope::SEAL,
18313×
                            not_before: 1,
18323×
                            expires: 600_001,
18333×
                            grant: None,
18343×
                        },
18353×
                        &sign_as.0,
18363×
                        &sign_as.1,
1837
                    );
18383×
                    serde_json::json!({ "certificate": oxy_core::dsse::base64(&cert.encode()) }).to_string().into_bytes()
1839
                } else {
18403×
                    published.encode()
1841
                };
18426×
                let _ = write!(s, "HTTP/1.1 200 OK\r\nContent-Length: {}\r\nConnection: close\r\n\r\n", body.len());
18436×
                let _ = s.write_all(&body);
1844
            }
18453×
        });
18463×
        format!("http://{addr}")
18473×
    }
1848
1849
    /// keyless (oxygenhub#241): the runner takes a certificate only when it
1850
    /// is for its fresh key and signed by the key the hub publishes.
1851
    #[test]
18521×
    fn a_certificate_is_taken_only_for_this_key_from_the_hubs_key() {
1853
        use oxy_core::identity::SecretKey;
18541×
        let hub_sk = SecretKey::generate();
18551×
        let hub_id = hub_sk.identity("hub", "", 1);
18561×
        let sk = SecretKey::generate();
18571×
        let id = sk.identity("earth-1 job 7", "", 1);
18581×
        let proof = sk.sign_challenge(&id.hash(), &oxy_core::cert::certify_challenge("flowjob_x")).unwrap();
1859
18601×
        let base = fake_certify_hub((hub_id.clone(), hub_sk.clone()), id.clone(), hub_id.clone());
18611×
        let (cert, issuer) = hub_at(base).certify("flowjob_x", &id, &proof).unwrap();
18621×
        assert_eq!((cert.cert.key_id(), issuer.hash()), (id.hash(), hub_id.hash()));
1863
18641×
        let mallory_sk = SecretKey::generate();
18651×
        let mallory = mallory_sk.identity("mallory", "", 1);
18661×
        let base = fake_certify_hub((mallory.clone(), mallory_sk), id.clone(), hub_id.clone());
18671×
        let e = hub_at(base).certify("flowjob_x", &id, &proof).unwrap_err().to_string();
18681×
        assert!(e.contains("not signed by the hub's published key"), "{e}");
1869
18701×
        let other = SecretKey::generate().identity("other", "", 1);
18711×
        let base = fake_certify_hub((hub_id.clone(), hub_sk), other, hub_id);
18721×
        let e = hub_at(base).certify("flowjob_x", &id, &proof).unwrap_err().to_string();
18731×
        assert!(e.contains("another key"), "{e}");
18741×
    }
1875
187614×
    fn hub_at(base: String) -> Hub {
187714×
        Hub { base, token: "t".into(), agent: ureq::AgentBuilder::new().timeout(Duration::from_secs(5)).build() }
187814×
    }
1879
1880
    /// oxygenhub#71: a job's result is offered until the hub takes it,
1881
    /// through server errors, and a refusal ends the trying at once.
1882
    #[test]
18831×
    fn a_result_is_reported_until_the_hub_takes_it() {
18841×
        let f = Finish {
18851×
            exit_code: Some(0),
18861×
            duration_ms: 1,
18871×
            receipt: None,
18881×
            signed_receipt: None,
18891×
            error: None,
18901×
            peak_disk_mib: None,
18911×
            peak_memory_mib: None,
18921×
        };
18931×
        let quick = Duration::from_millis(10);
18941×
        let (base, seen) = fake_hub(vec![502, 503, 500, 500, 204]);
18951×
        hub_at(base).finish_until_accepted(7, &f, Duration::from_secs(30), quick).unwrap();
18961×
        assert_eq!(seen.load(std::sync::atomic::Ordering::SeqCst), 5, "kept trying through four server errors");
18971×
        let (base, seen) = fake_hub(vec![409]);
18981×
        assert!(hub_at(base).finish_until_accepted(7, &f, Duration::from_secs(30), quick).is_err());
18991×
        assert_eq!(seen.load(std::sync::atomic::Ordering::SeqCst), 1, "a refusal is final");
19001×
    }
1901
1902
    #[test]
19031×
    fn server_errors_are_tried_again_and_client_errors_are_not() {
19041×
        let quick = [Duration::from_millis(10); 3];
19051×
        let (base, seen) = fake_hub(vec![500, 503, 204]);
19061×
        let r = hub_at(base).post_with("/flow/jobs/1/log", &serde_json::json!({}), &quick).unwrap();
19071×
        assert!(r.is_none());
19081×
        assert_eq!(seen.load(std::sync::atomic::Ordering::SeqCst), 3, "two retries, then accepted");
1909
19101×
        let (base, seen) = fake_hub(vec![500, 500, 500, 500]);
19111×
        let e = hub_at(base).post_with("/flow/claim", &serde_json::json!({}), &quick).unwrap_err().to_string();
19121×
        assert!(e.contains("HTTP 500"), "{e}");
19131×
        assert_eq!(seen.load(std::sync::atomic::Ordering::SeqCst), 4, "gives up after the last delay");
1914
19151×
        let (base, seen) = fake_hub(vec![401]);
19161×
        assert!(hub_at(base).post_with("/flow/claim", &serde_json::json!({}), &quick).is_err());
19171×
        assert_eq!(seen.load(std::sync::atomic::Ordering::SeqCst), 1, "a refusal is final");
19181×
    }
1919
1920
    static NOT_LEAVING: std::sync::Mutex<Option<Leave>> = std::sync::Mutex::new(None);
1921
1922
    /// oxygenflow#76: once the runner leaves, a job's sink says it is
1923
    /// cancelled, having sent what the job said so far, and the job is
1924
    /// handed back to the hub.
1925
    #[test]
19261×
    fn a_leaving_runner_stops_its_job_and_hands_it_back() {
1927
        use microvm::Sink;
19281×
        let leaving = std::sync::Mutex::new(None);
19291×
        let (base, seen) = fake_hub(vec![204, 204]);
19301×
        let hub = hub_at(base);
19311×
        let mut sink = LogSink {
19321×
            hub: &hub,
19331×
            job: 7,
19341×
            buf: Vec::new(),
19351×
            last: Instant::now(),
19361×
            gone: false,
19371×
            leaving: &leaving,
19381×
            started: Instant::now(),
19391×
            expected: None,
19401×
        };
19411×
        sink.buf.push(Record { t: 1, stream: "out".into(), text: "step 1".into() });
19421×
        assert!(!sink.cancelled());
19431×
        *leaving.lock().unwrap() = Some(Leave { reason: "off Wi-Fi".into(), by: Instant::now() });
19441×
        assert!(sink.cancelled());
19451×
        assert!(sink.buf.is_empty(), "flushed before the job stops");
19461×
        assert_eq!(seen.load(std::sync::atomic::Ordering::SeqCst), 1);
19471×
        hub.release(7, "off Wi-Fi").unwrap();
19481×
        assert_eq!(seen.load(std::sync::atomic::Ordering::SeqCst), 2);
19491×
    }
1950
1951
    /// oxygenflow#76: with notice, a job the hub expects to finish within
1952
    /// it runs on; one that will not, or whose time is unknown, is handed
1953
    /// back at once, and any job still running when the notice is up.
1954
    #[test]
19551×
    fn a_job_that_fits_the_notice_finishes_and_the_others_go_back() {
1956
        use microvm::Sink;
19571×
        let (base, _) = fake_hub(vec![204; 8]);
19581×
        let hub = hub_at(base);
19591×
        let leaving = std::sync::Mutex::new(Some(Leave { reason: "off charge".into(), by: Instant::now() + Duration::from_secs(60) }));
19601×
        let sink = |expected: Option<u64>, ran: u64| LogSink {
19614×
            hub: &hub,
1962
            job: 1,
19634×
            buf: Vec::new(),
19644×
            last: Instant::now(),
1965
            gone: false,
19664×
            leaving: &leaving,
19674×
            started: Instant::now() - Duration::from_secs(ran),
19684×
            expected: expected.map(Duration::from_secs),
19694×
        };
19701×
        assert!(!sink(Some(70), 30).cancelled(), "40 s left of it, within a minute: it finishes");
19711×
        assert!(sink(Some(600), 30).cancelled(), "nearly ten minutes left: handed back");
19721×
        assert!(sink(None, 0).cancelled(), "no idea how long: handed back");
19731×
        *leaving.lock().unwrap() = Some(Leave { reason: "off charge".into(), by: Instant::now() - Duration::from_secs(1) });
19741×
        assert!(sink(Some(70), 30).cancelled(), "the notice is up: handed back whatever was expected");
19751×
    }
1976
1977
    /// oxygenflow#32: a quiet job asks the hub every few seconds whether
1978
    /// it still runs; a 409 marks it cancelled, and nothing more is sent.
1979
    #[test]
19801×
    fn a_quiet_job_learns_that_its_run_was_cancelled() {
1981
        use microvm::Sink;
19822×
        let n = |seen: &std::sync::Arc<std::sync::atomic::AtomicUsize>| seen.load(std::sync::atomic::Ordering::SeqCst);
19831×
        let quiet = Instant::now() - HEARTBEAT - Duration::from_secs(1);
19841×
        let (base, seen) = fake_hub(vec![204]);
19851×
        let hub = hub_at(base);
19861×
        let mut sink = LogSink {
19871×
            hub: &hub,
19881×
            job: 1,
19891×
            buf: Vec::new(),
19901×
            last: quiet,
19911×
            gone: false,
19921×
            leaving: &NOT_LEAVING,
19931×
            started: Instant::now(),
19941×
            expected: None,
19951×
        };
19961×
        assert!(!sink.cancelled());
19971×
        assert!(!sink.cancelled(), "asked again only after the heartbeat");
19981×
        assert_eq!(n(&seen), 1);
1999
20001×
        let (base, seen) = fake_hub(vec![409]);
20011×
        let hub = hub_at(base);
20021×
        let mut sink = LogSink {
20031×
            hub: &hub,
20041×
            job: 1,
20051×
            buf: Vec::new(),
20061×
            last: quiet,
20071×
            gone: false,
20081×
            leaving: &NOT_LEAVING,
20091×
            started: Instant::now(),
20101×
            expected: None,
20111×
        };
20121×
        assert!(sink.cancelled());
20131×
        sink.record(Record { t: 0, stream: "out".into(), text: "late".into() });
20141×
        sink.flush();
20151×
        assert!(sink.cancelled());
20161×
        assert_eq!(n(&seen), 1, "nothing is sent for a cancelled job");
20171×
    }
2018
2019
    /// oxygenflow#49: a hub that is away for a while (a deploy restarting
2020
    /// it) costs a job's uploads a wait, not the upload, and costs its log
2021
    /// no lines.
2022
    #[test]
20231×
    fn a_job_outlasts_a_hub_restart() {
20242×
        let n = |seen: &std::sync::Arc<std::sync::atomic::AtomicUsize>| seen.load(std::sync::atomic::Ordering::SeqCst);
2025
        // A port nobody listens on yet: the hub is restarting.
20261×
        let port = std::net::TcpListener::bind("127.0.0.1:0").unwrap().local_addr().unwrap().port();
20271×
        let base = format!("http://127.0.0.1:{port}");
20281×
        let hub = hub_at(base.clone());
2029
2030
        // Log lines sent while it is away are kept, and go when it is back.
20311×
        let mut sink = LogSink {
20321×
            hub: &hub,
20331×
            job: 1,
20341×
            buf: Vec::new(),
20351×
            last: Instant::now(),
20361×
            gone: false,
20371×
            leaving: &NOT_LEAVING,
20381×
            started: Instant::now(),
20391×
            expected: None,
20401×
        };
2041450×
        for i in 0..450 {
2042450×
            sink.buf.push(Record { t: i, stream: "out".into(), text: format!("line {i}") });
2043450×
        }
20441×
        sink.send();
20451×
        assert_eq!(sink.buf.len(), 450, "nothing lost while the hub is away");
20461×
        let (_, seen) = fake_hub_on(std::net::TcpListener::bind(("127.0.0.1", port)).unwrap(), vec![204, 204, 204]);
20471×
        sink.send();
20481×
        assert!(sink.buf.is_empty() && !sink.gone);
20491×
        assert_eq!(n(&seen), 3, "in batches of 200: 200, 200 and 50");
2050
2051
        // An upload waits for the hub to come back, through refused
2052
        // connections and server errors alike.
20531×
        let port = std::net::TcpListener::bind("127.0.0.1:0").unwrap().local_addr().unwrap().port();
20541×
        let url = format!("http://127.0.0.1:{port}/x");
20551×
        let agent = ureq::AgentBuilder::new().timeout(Duration::from_secs(5)).build();
20561×
        let later = std::thread::spawn(move || {
20571×
            std::thread::sleep(Duration::from_millis(150));
20581×
            fake_hub_on(std::net::TcpListener::bind(("127.0.0.1", port)).unwrap(), vec![502, 204])
20591×
        });
20601×
        let quick = [Duration::from_millis(50); 20];
20615×
        let r = retrying(&url, &quick, true, || agent.post(&url).send_string("{}").map_err(Box::new)).unwrap();
20621×
        assert_eq!(r.status(), 204);
20631×
        assert_eq!(n(&later.join().unwrap().1), 2, "a 502 from the proxy, then the hub");
2064
        // Without `connection`, a hub that cannot be reached ends it at once.
20651×
        let port = std::net::TcpListener::bind("127.0.0.1:0").unwrap().local_addr().unwrap().port();
20661×
        let url = format!("http://127.0.0.1:{port}/x");
20671×
        assert!(retrying(&url, &quick, false, || agent.post(&url).send_string("{}").map_err(Box::new)).is_err());
20681×
        assert!(PATIENT_DELAYS.iter().sum::<Duration>() >= Duration::from_secs(180), "longer than a hub takes to restart");
20691×
    }
2070
2071
    /// oxygenflow#50: the first stop drains (the second, not called here,
2072
    /// exits at once).
2073
    #[test]
20741×
    fn a_stop_drains_the_runner() {
20751×
        assert!(!stopping());
20761×
        on_stop(libc::SIGTERM);
20771×
        assert!(stopping(), "told to stop, it claims nothing more");
2078
        // An embedded runner starts afresh, and stop() drains it the same way.
20791×
        STOPS.store(0, std::sync::atomic::Ordering::SeqCst);
20801×
        stop();
20811×
        assert!(stopping());
20821×
        STOPS.store(0, std::sync::atomic::Ordering::SeqCst);
20831×
    }
2084
2085
    /// Lines kept for a hub that stays away are bounded, saying how many went.
2086
    #[test]
20871×
    fn unsent_log_lines_are_bounded() {
20881×
        let port = std::net::TcpListener::bind("127.0.0.1:0").unwrap().local_addr().unwrap().port();
20891×
        let hub = hub_at(format!("http://127.0.0.1:{port}"));
20901×
        let mut sink = LogSink {
20911×
            hub: &hub,
20921×
            job: 1,
20931×
            buf: Vec::new(),
20941×
            last: Instant::now(),
20951×
            gone: false,
20961×
            leaving: &NOT_LEAVING,
20971×
            started: Instant::now(),
20981×
            expected: None,
20991×
        };
210050010×
        sink.buf = (0..MAX_UNSENT as u64 + 10).map(|i| Record { t: i, stream: "out".into(), text: String::new() }).collect();
21011×
        sink.send();
21021×
        assert_eq!(sink.buf.len(), MAX_UNSENT + 1);
21031×
        assert_eq!(sink.buf[0].text, "(10 log lines lost while the hub could not be reached)");
21041×
        assert_eq!(sink.buf[1].t, 10, "the oldest go first");
21051×
    }
2106
2107
    #[test]
21081×
    fn the_budget_admits_jobs_that_fit() {
21091×
        let b = Budget { max_jobs: 3, memory_mib: Some(24_576), cpus: Some(8) };
21107×
        let used = |jobs, memory_mib, cpus| Used { jobs, memory_mib, cpus };
21111×
        assert_eq!(b.room(used(0, 0, 0)), Some((None, None)), "a lone job may take everything");
21121×
        assert_eq!(b.room(used(1, 8192, 4)), Some((Some(16_384), Some(4))));
21131×
        assert_eq!(b.room(used(2, 16_384, 8)), None, "no vCPU left");
21141×
        assert_eq!(b.room(used(3, 1024, 1)), None, "at max_jobs");
21151×
        let one = Budget { max_jobs: 1, memory_mib: None, cpus: None };
21161×
        assert_eq!(one.room(used(0, 0, 0)), Some((None, None)));
21171×
        assert_eq!(one.room(used(1, 0, 0)), None, "the default runs one job at a time");
21181×
        let open = Budget { max_jobs: 2, memory_mib: None, cpus: None };
21191×
        assert_eq!(open.room(used(1, 8192, 4)), Some((None, None)), "no limits configured");
21201×
    }
2121
}