OXYGENHUB
# eb8e445f27b6 oxygenflow / crates / flow / src / runner.rs
81.3 KiB · Rust · last changed The WASM tier: WASI modules run by wasmtime on any runner (closes #75) 11 days ago source blame history raw
e0918b88 Andy McCall 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
47c1d64d Andy McCall ↶ 6
use crate::home::{Home, RunnerConfig, RunnerKey};
e0918b88 Andy McCall 7
use crate::{microvm, workspace};
8
use anyhow::{bail, Context, Result};
b11e30f5 Andy McCall ↶ 9
use flow_core::api::{Claim, ClaimRequest, Decline, Finish, LogBatch, Record, Register, Registered, RunnerInfo, MAX_RECORD_TEXT};
e0918b88 Andy McCall 10
use flow_core::{scope_tree_hash, Receipt};
11
use oxy_core::hash::ChangeHash;
12
use oxy_core::repo::Repo;
46fe2c81 Andy McCall ↶ 13
use std::path::{Path, PathBuf};
e0918b88 Andy McCall 14
use std::time::{Duration, Instant};
15
280ef951 Andy McCall ↶ 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 {
25
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
26
        write!(f, "HTTP {}: {}", self.code, self.text)
27
    }
28
}
29
30
impl std::error::Error for Refused {}
31
32
/// Whether `e` is the hub saying the job no longer runs.
33
fn job_gone(e: &anyhow::Error) -> bool {
34
    e.downcast_ref::<Refused>().is_some_and(|r| r.code == 409)
35
}
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
41
fn cancelled() -> Finish {
8f211e20 Andy McCall ↶ 42
    Finish {
43
        exit_code: None,
44
        duration_ms: 0,
45
        receipt: None,
46
        signed_receipt: None,
47
        error: Some(CANCELLED.into()),
48
        peak_disk_mib: None,
49
        peak_memory_mib: None,
50
    }
280ef951 Andy McCall ↶ 51
}
52
e0918b88 Andy McCall 53
pub struct Hub {
54
    base: String,
55
    token: String,
56
    agent: ureq::Agent,
57
}
58
59
impl Hub {
60
    pub fn new(cfg: &RunnerConfig) -> Result<Hub> {
61
        let tls = oxy_core::protocol::tls_client_config(cfg.ca.as_deref()).map_err(|e| anyhow::anyhow!("{e}"))?;
62
        let agent = ureq::AgentBuilder::new().tls_config(tls).timeout(Duration::from_secs(60)).build();
63
        Ok(Hub { base: cfg.hub.trim_end_matches('/').to_string(), token: cfg.token.clone(), agent })
64
    }
65
1b2229da Andy McCall ↶ 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.
e0918b88 Andy McCall 69
    fn post(&self, path: &str, body: &impl serde::Serialize) -> Result<Option<ureq::Response>> {
1b2229da Andy McCall ↶ 70
        self.post_with(path, body, &RETRY_DELAYS)
71
    }
72
73
    fn post_with(&self, path: &str, body: &impl serde::Serialize, delays: &[Duration]) -> Result<Option<ureq::Response>> {
e0918b88 Andy McCall 74
        let url = format!("{}/api/v1{path}", self.base);
89171fca Andy McCall ↶ 75
        let r = retrying(&url, delays, false, || {
76
            self.agent.post(&url).set("Authorization", &format!("Bearer {}", self.token)).send_json(body).map_err(Box::new)
77
        })?;
78
        Ok(if r.status() == 204 { None } else { Some(r) })
79
    }
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.
84
    fn post_patiently(&self, path: &str, body: &impl serde::Serialize) -> Result<Option<ureq::Response>> {
85
        let url = format!("{}/api/v1{path}", self.base);
86
        let r = retrying(&url, &PATIENT_DELAYS, true, || {
87
            self.agent.post(&url).set("Authorization", &format!("Bearer {}", self.token)).send_json(body).map_err(Box::new)
88
        })?;
89
        Ok(if r.status() == 204 { None } else { Some(r) })
e0918b88 Andy McCall 90
    }
91
92
    pub fn claim(&self, req: &ClaimRequest) -> Result<Option<Claim>> {
93
        match self.post("/flow/claim", req)? {
94
            Some(r) => Ok(Some(r.into_json()?)),
95
            None => Ok(None),
96
        }
97
    }
98
b11e30f5 Andy McCall ↶ 99
    /// Hand job `job` back, saying why this runner will not run it.
100
    pub fn decline(&self, job: i64, reason: &str) -> Result<()> {
89171fca Andy McCall ↶ 101
        self.post_patiently(&format!("/flow/jobs/{job}/decline"), &Decline { reason: reason.into() })?;
b11e30f5 Andy McCall ↶ 102
        Ok(())
103
    }
104
a4b3f8cb Andy McCall ↶ 105
    /// Say this runner is there while it claims nothing: its slots are full,
106
    /// or it is draining (oxygenhub#243). Once, no retries: the next comes
107
    /// soon. A hub without the endpoint (404) is not an error.
35f7a849 Andy McCall ↶ 108
    /// A ten-minute certificate for `identity`, asked with a job's token
109
    /// (keyless, oxygenhub#241), and the identity of the hub's key that
110
    /// issued it, from `/.well-known/oxyhub-key`.
111
    pub fn certify(
112
        &self,
113
        job_token: &str,
114
        identity: &oxy_core::identity::Identity,
115
        proof: &oxy_core::identity::Signature,
116
    ) -> Result<(oxy_core::cert::SignedCertificate, oxy_core::identity::Identity)> {
117
        use oxy_core::dsse::{base64, base64_decode};
118
        let body = serde_json::json!({
119
            "identity": base64(&identity.encode()),
120
            "proof": base64(&oxy_core::cbor::encode(&proof.to_value())),
121
            "scope": "seal",
122
        });
123
        let url = format!("{}/api/v1/keyless/certify", self.base);
124
        let r = self
125
            .agent
126
            .post(&url)
127
            .set("Authorization", &format!("Bearer {job_token}"))
128
            .send_json(body)
129
            .map_err(|e| anyhow::anyhow!("asking the hub to certify the key: {e}"))?;
130
        let v: serde_json::Value = r.into_json()?;
131
        let cert = base64_decode(v["certificate"].as_str().unwrap_or(""))
132
            .context("the hub's answer has no certificate")
133
            .and_then(|b| oxy_core::cert::SignedCertificate::decode(&b).map_err(|e| anyhow::anyhow!("{e}")))?;
134
        let mut bytes = Vec::new();
135
        std::io::Read::read_to_end(
136
            &mut self.agent.get(&format!("{}/.well-known/oxyhub-key", self.base)).call()?.into_reader(),
137
            &mut bytes,
138
        )?;
139
        let issuer = oxy_core::identity::Identity::decode(&bytes)?;
140
        if issuer.hash() != cert.cert.issuer || cert.verify(&issuer).is_err() {
141
            bail!("the certificate is not signed by the hub's published key");
142
        }
143
        if cert.cert.key_id() != identity.hash() {
144
            bail!("the hub certified another key");
145
        }
146
        Ok((cert, issuer))
147
    }
148
a4b3f8cb Andy McCall ↶ 149
    pub fn heartbeat(&self) -> Result<()> {
150
        match self.post_with("/flow/runners/heartbeat", &serde_json::json!({}), &[]) {
151
            Ok(_) => Ok(()),
152
            Err(e) if format!("{e:#}").contains("404") => Ok(()),
153
            Err(e) => Err(e),
154
        }
155
    }
156
e0918b88 Andy McCall 157
    pub fn log(&self, job: i64, records: Vec<Record>) -> Result<()> {
158
        self.post(&format!("/flow/jobs/{job}/log"), &LogBatch { records })?;
159
        Ok(())
160
    }
161
a67b97e9 Andy McCall ↶ 162
    /// Upload artifact `name` of job `job` (spec §5.2); the hub keeps it as
163
    /// a blob of the job's repository and answers with its ObjectRef.
164
    pub fn artifact(&self, job: i64, name: &str, bytes: &[u8]) -> Result<String> {
165
        let url = format!("{}/api/v1/flow/jobs/{job}/artifacts/{name}", self.base);
89171fca Andy McCall ↶ 166
        let r = retrying(&url, &PATIENT_DELAYS, true, || {
167
            self.agent
a67b97e9 Andy McCall ↶ 168
                .post(&url)
169
                .timeout(Duration::from_secs(600))
170
                .set("Authorization", &format!("Bearer {}", self.token))
89171fca Andy McCall ↶ 171
                .set("Content-Type", "application/octet-stream")
172
                .send_bytes(bytes)
173
                .map_err(Box::new)
174
        })?;
175
        let v: serde_json::Value = r.into_json()?;
176
        v["blob"].as_str().map(String::from).context("the hub named no blob")
a67b97e9 Andy McCall ↶ 177
    }
178
46fe2c81 Andy McCall ↶ 179
    /// Input `index` of job `job` (oxygenflow#58): the bytes of the
180
    /// producing job's artifact, which the caller checks against the blob the
181
    /// claim names.
182
    pub fn input(&self, job: i64, index: usize) -> Result<Vec<u8>> {
183
        let url = format!("{}/api/v1/flow/jobs/{job}/inputs/{index}", self.base);
184
        let r = retrying(&url, &PATIENT_DELAYS, false, || {
185
            self.agent
186
                .get(&url)
187
                .timeout(Duration::from_secs(600))
188
                .set("Authorization", &format!("Bearer {}", self.token))
189
                .call()
190
                .map_err(Box::new)
191
        })?;
192
        let mut bytes = Vec::new();
193
        let mut reader = r.into_reader();
194
        std::io::Read::read_to_end(&mut std::io::Read::take(&mut reader, MAX_INPUT_BYTES as u64 + 1), &mut bytes)?;
195
        if bytes.len() > MAX_INPUT_BYTES {
196
            bail!("larger than {} MiB", MAX_INPUT_BYTES >> 20);
197
        }
198
        Ok(bytes)
199
    }
200
6d53fb7d Andy McCall ↶ 201
    /// Upload file `path` of report `name` of job `job` (oxygenhub#127);
202
    /// the hub keeps it as a blob and answers with its ObjectRef. The
203
    /// report's manifest follows through [`Hub::artifact`].
204
    pub fn report_file(&self, job: i64, name: &str, path: &str, bytes: &[u8]) -> Result<String> {
205
        let url = format!("{}/api/v1/flow/jobs/{job}/reports/{name}/files", self.base);
89171fca Andy McCall ↶ 206
        let r = retrying(&url, &PATIENT_DELAYS, true, || {
207
            self.agent
6d53fb7d Andy McCall ↶ 208
                .post(&url)
209
                .timeout(Duration::from_secs(600))
210
                .set("Authorization", &format!("Bearer {}", self.token))
211
                .set("Content-Type", "application/octet-stream")
89171fca Andy McCall ↶ 212
                .set("X-Flow-Report-Path", path)
213
                .send_bytes(bytes)
214
                .map_err(Box::new)
215
        })?;
216
        let v: serde_json::Value = r.into_json()?;
217
        v["blob"].as_str().map(String::from).context("the hub named no blob")
6d53fb7d Andy McCall ↶ 218
    }
219
3007d8f0 Andy McCall ↶ 220
    /// Report a job's end until the hub has it (oxygenhub#71): while the hub
221
    /// cannot be reached or fails (5xx), try again after `first_wait`,
222
    /// doubling to a minute, for up to `patience`. A refusal (4xx: the job was ended
223
    /// already, say) is final. A result lost here leaves the job running
224
    /// on the hub until its time limit.
225
    pub fn finish_until_accepted(&self, job: i64, f: &Finish, patience: Duration, first_wait: Duration) -> Result<()> {
226
        let url = format!("{}/api/v1/flow/jobs/{job}/finish", self.base);
227
        let deadline = std::time::Instant::now() + patience;
228
        let mut wait = first_wait;
229
        loop {
230
            let why = match self.agent.post(&url).set("Authorization", &format!("Bearer {}", self.token)).send_json(f) {
231
                Ok(_) => return Ok(()),
232
                Err(ureq::Error::Status(code, r)) if code < 500 => {
233
                    bail!("{url}: HTTP {code}: {}", r.into_string().unwrap_or_default())
234
                }
235
                Err(ureq::Error::Status(code, _)) => format!("HTTP {code}"),
236
                Err(e) => e.to_string(),
237
            };
238
            if std::time::Instant::now() + wait > deadline {
239
                bail!("{url}: gave up after {} minutes: {why}", patience.as_secs() / 60);
240
            }
241
            eprintln!("job {job}: the hub did not take the result ({why}); trying again in {} s", wait.as_secs());
242
            std::thread::sleep(wait);
243
            wait = (wait * 2).min(Duration::from_secs(60));
244
        }
245
    }
246
}
247
248
/// How long a runner keeps trying to report a job's end.
249
const FINISH_PATIENCE: Duration = Duration::from_secs(2 * 3600);
250
251
/// Where a job's result waits until the hub has it, so a runner that
252
/// restarts still reports it.
253
fn pending_path(home: &Home, job: i64) -> PathBuf {
254
    home.root.join("pending").join(format!("{job}.json"))
255
}
256
257
/// Report `f`, keeping it on disk until the hub has it.
258
fn report_finish(home: &Home, hub: &Hub, job: i64, f: &Finish) {
259
    let path = pending_path(home, job);
260
    let kept = std::fs::create_dir_all(path.parent().unwrap())
261
        .and_then(|_| std::fs::write(&path, serde_json::to_vec(f).unwrap_or_default()))
262
        .is_ok();
263
    match hub.finish_until_accepted(job, f, FINISH_PATIENCE, Duration::from_secs(5)) {
264
        Ok(()) => {}
265
        Err(e) => eprintln!("job {job}: reporting failed: {e:#}"),
266
    }
267
    if kept {
268
        let _ = std::fs::remove_file(&path);
f98a8f78 Andy McCall ↶ 269
    }
3007d8f0 Andy McCall ↶ 270
}
271
272
/// Results a previous run of the runner could not report, to send again.
273
fn report_pending(home: &Home) -> Vec<(i64, Finish)> {
274
    let Ok(dir) = std::fs::read_dir(home.root.join("pending")) else {
275
        return Vec::new();
276
    };
277
    dir.filter_map(|e| {
278
        let p = e.ok()?.path();
279
        let job: i64 = p.file_stem()?.to_str()?.parse().ok()?;
280
        let f: Finish = serde_json::from_slice(&std::fs::read(&p).ok()?).ok()?;
281
        Some((job, f))
282
    })
283
    .collect()
f98a8f78 Andy McCall ↶ 284
}
285
286
/// `flow runner register`: exchange a one-time registration token from
287
/// the hub for this runner's credential, binding the runner's signing key,
288
/// and keep hub, credential and name in runner.toml.
289
pub fn register(home: &Home, hub: &str, token: &str, name: &str, ca: Option<PathBuf>, labels: Vec<String>) -> Result<Registered> {
290
    if home.config.runner.is_some() && !home.root.join(crate::home::RUNNER_TOML).is_file() {
291
        bail!("flow.toml already has a [runner] section; remove it to register this runner instead");
292
    }
293
    let key = home.runner_key(name)?;
294
    let hub = hub.trim_end_matches('/').to_string();
295
    let tls = oxy_core::protocol::tls_client_config(ca.as_deref()).map_err(|e| anyhow::anyhow!("{e}"))?;
296
    let agent = ureq::AgentBuilder::new().tls_config(tls).timeout(Duration::from_secs(60)).build();
297
    let req = Register {
298
        token: token.trim().to_string(),
299
        name: name.to_string(),
300
        identity: hex::encode(key.identity.encode()),
2d025bbf Andy McCall ↶ 301
        info: RunnerInfo { version: env!("OXY_VERSION_LONG").into(), ..RunnerInfo::here(labels.clone(), 1, None, None) },
f98a8f78 Andy McCall ↶ 302
    };
303
    let url = format!("{hub}/api/v1/flow/runners/register");
304
    let got: Registered = match agent.post(&url).send_json(&req) {
305
        Ok(r) => r.into_json()?,
306
        Err(ureq::Error::Status(code, r)) => bail!("{url}: HTTP {code}: {}", r.into_string().unwrap_or_default()),
307
        Err(e) => bail!("{url}: {e}"),
308
    };
309
    let mut text = format!(
310
        "# Written by `flow runner register`; the credential is secret.\nhub = {hub:?}\ntoken = {:?}\nname = {:?}\n",
311
        got.credential, got.name
312
    );
313
    if let Some(ca) = &ca {
314
        text.push_str(&format!("ca = {:?}\n", ca.display().to_string()));
315
    }
316
    if !labels.is_empty() {
317
        text.push_str(&format!("labels = {labels:?}\n"));
318
    }
319
    let path = home.root.join(crate::home::RUNNER_TOML);
320
    {
321
        use std::io::Write;
322
        use std::os::unix::fs::OpenOptionsExt;
323
        let tmp = path.with_extension("toml.tmp");
324
        let mut f = std::fs::OpenOptions::new().write(true).create(true).truncate(true).mode(0o600).open(&tmp)?;
325
        f.write_all(text.as_bytes())?;
326
        f.sync_all()?;
327
        std::fs::rename(&tmp, &path)?;
e0918b88 Andy McCall 328
    }
f98a8f78 Andy McCall ↶ 329
    Ok(got)
e0918b88 Andy McCall 330
}
1b2229da Andy McCall ↶ 331
332
/// Waits before trying a hub request again after a server error.
333
const RETRY_DELAYS: [Duration; 3] = [Duration::from_secs(1), Duration::from_secs(2), Duration::from_secs(4)];
89171fca Andy McCall ↶ 334
335
/// Waits for what a job leaves behind (oxygenflow#49): three minutes in
336
/// all, longer than a hub takes to restart.
46fe2c81 Andy McCall ↶ 337
/// Check an input's bytes against the blob the producing job's receipt
338
/// names, then write them at its path under `tree` (the workspace's `/src`).
339
fn place_input(tree: &Path, i: &flow_core::api::ArtifactInput, bytes: &[u8]) -> Result<[u8; 32]> {
340
    let Some(rel) = i.path.strip_prefix("/src/").filter(|r| r.split('/').all(|p| !p.is_empty() && p != "." && p != ".." && p != ".oxy"))
341
    else {
342
        bail!("path {:?} is not a clean path under /src", i.path);
343
    };
344
    let blob = Repo::blob_ref(bytes);
345
    if blob.to_hex() != i.blob {
346
        bail!("it is not what {}'s receipt names (blob {}, not {})", i.from, &blob.to_hex()[..12], &i.blob[..i.blob.len().min(12)]);
347
    }
348
    let dest = tree.join(rel);
349
    if let Some(dir) = dest.parent() {
350
        std::fs::create_dir_all(dir)?;
351
    }
352
    std::fs::write(&dest, bytes)?;
353
    Ok(blob.0)
354
}
355
356
/// The largest input a job takes: the hub's artifact limit.
357
pub const MAX_INPUT_BYTES: usize = 512 << 20;
358
89171fca Andy McCall ↶ 359
const PATIENT_DELAYS: [Duration; 15] = {
360
    let mut d = [Duration::from_secs(15); 15];
361
    d[0] = Duration::from_secs(1);
362
    d[1] = Duration::from_secs(2);
363
    d[2] = Duration::from_secs(4);
364
    d[3] = Duration::from_secs(8);
365
    d
366
};
367
368
/// Send a request until the hub answers, waiting `delays` in turn after a
369
/// server error (5xx: nothing was committed) and, when `connection`, after
370
/// the hub could not be reached at all. A refusal (4xx) is final, as a
371
/// [`Refused`] the caller can look at.
372
fn retrying(
373
    url: &str,
374
    delays: &[Duration],
375
    connection: bool,
376
    mut send: impl FnMut() -> Result<ureq::Response, Box<ureq::Error>>,
377
) -> Result<ureq::Response> {
378
    let mut delays = delays.iter();
379
    loop {
380
        let why = match send().map_err(|e| *e) {
381
            Ok(r) => return Ok(r),
382
            Err(ureq::Error::Status(code, r)) if code < 500 => {
383
                let text = r.into_string().unwrap_or_default();
384
                return Err(anyhow::Error::new(Refused { code, text }).context(url.to_string()));
385
            }
386
            Err(ureq::Error::Status(code, r)) => format!("HTTP {code}: {}", r.into_string().unwrap_or_default()),
387
            Err(e) if connection => e.to_string(),
388
            Err(e) => bail!("{url}: {e}"),
389
        };
390
        match delays.next() {
391
            Some(d) => std::thread::sleep(*d),
392
            None => bail!("{url}: {why}"),
393
        }
394
    }
395
}
e0918b88 Andy McCall 396
bb643c25 Andy McCall ↶ 397
/// What the runner may run at once (flow.toml `[runner]`): at most
398
/// `max_jobs` jobs, whose sandboxes together fit `memory_mib` and `cpus`.
399
#[derive(Debug, Default, PartialEq, Eq)]
400
pub struct Budget {
401
    pub max_jobs: usize,
402
    pub memory_mib: Option<u32>,
403
    pub cpus: Option<u32>,
404
}
405
406
/// What is in use now.
407
#[derive(Debug, Default, Clone, Copy, PartialEq, Eq)]
408
pub struct Used {
409
    pub jobs: usize,
410
    pub memory_mib: u32,
411
    pub cpus: u32,
412
}
413
414
impl Budget {
415
    pub fn of(cfg: &RunnerConfig) -> Budget {
416
        Budget { max_jobs: cfg.max_jobs.unwrap_or(1).max(1), memory_mib: cfg.memory_mib, cpus: cfg.cpus }
417
    }
418
419
    /// The room to ask the hub for, or `None` when no job more can start.
420
    /// A lone job may use the whole budget even if it asks for more, so a
421
    /// large sandbox is never starved.
422
    pub fn room(&self, used: Used) -> Option<(Option<u32>, Option<u32>)> {
423
        if used.jobs >= self.max_jobs {
424
            return None;
425
        }
426
        if used.jobs == 0 {
427
            return Some((None, None));
428
        }
429
        let mem = self.memory_mib.map(|m| m.saturating_sub(used.memory_mib));
430
        let cpus = self.cpus.map(|c| c.saturating_sub(used.cpus));
431
        if mem == Some(0) || cpus == Some(0) {
432
            return None;
433
        }
434
        Some((mem, cpus))
435
    }
436
}
437
c5b702e5 Andy McCall ↶ 438
/// The isolation tiers this machine can honour now (spec §11.1): the
ea56c56e Andy McCall ↶ 439
/// MicroVM tier when `/dev/kvm` opens for reading and writing and
440
/// flow.toml pins Firecracker; the syscall tier when this binary may use
441
/// user namespaces, Landlock and seccomp and manage a delegated cgroup.
442
/// `Err` says why there are none; the reasons for missing tiers come back
443
/// with the ones there are.
444
pub fn tiers(home: &Home) -> std::result::Result<(Vec<String>, Vec<String>), String> {
445
    let mut have = Vec::new();
446
    let mut missing = Vec::new();
c5b702e5 Andy McCall ↶ 447
    let kvm = std::fs::OpenOptions::new().read(true).write(true).open("/dev/kvm");
448
    match (kvm, home.config.microvm.is_some()) {
ea56c56e Andy McCall ↶ 449
        (Ok(_), true) => have.push("microvm".to_string()),
450
        (Ok(_), false) => missing.push("microvm: flow.toml has no [microvm] section".to_string()),
451
        (Err(e), _) => missing.push(format!(
452
            "microvm: /dev/kvm cannot be opened ({e}); the tier needs hardware virtualisation and this user in the kvm group"
c5b702e5 Andy McCall ↶ 453
        )),
454
    }
ea56c56e Andy McCall ↶ 455
    match crate::syscall::available() {
456
        Ok(()) => have.push("syscall".to_string()),
457
        Err(e) => missing.push(format!("syscall: {e}")),
458
    }
28cc603f Andy McCall ↶ 459
    // wasmtime runs on every machine this binary does (oxygenflow#75).
460
    have.push("wasm".to_string());
ea56c56e Andy McCall ↶ 461
    if have.is_empty() {
462
        return Err(format!("no isolation tier can run here: {}", missing.join("; ")));
463
    }
464
    Ok((have, missing))
b11e30f5 Andy McCall ↶ 465
}
466
4cf0c99a Andy McCall ↶ 467
/// Fetch `claim`'s image from the hub when this home lacks it
468
/// (oxygenflow#39), saying so in the job's log. A hub that does not hold it
469
/// leaves it missing, and the preflight declines the job as before.
b14aeaae Andy McCall ↶ 470
fn fetch_image(home: &Home, hub: &Hub, cfg: &RunnerConfig, swarm: Option<&crate::swarm::Swarm>, claim: &Claim) {
4cf0c99a Andy McCall ↶ 471
    let hash = &claim.sandbox.rootfs;
472
    if hash.is_empty() || home.rootfs(hash).is_file() || !jet::images::is_hash(hash) {
473
        return;
474
    }
475
    let note = |text: String| {
476
        eprintln!("job {}: {text}", claim.job_id);
477
        hub.log(claim.job_id, vec![Record { t: 0, stream: "flow".into(), text }]).ok();
478
    };
479
    // One fetch of an image at a time: two jobs wanting it wait for one.
480
    static FETCHING: std::sync::Mutex<()> = std::sync::Mutex::new(());
481
    let _one = FETCHING.lock().unwrap_or_else(|p| p.into_inner());
482
    if home.rootfs(hash).is_file() {
483
        return;
484
    }
485
    let client = match crate::images::Client::new(&cfg.hub, &cfg.token, cfg.ca.as_deref()) {
486
        Ok(c) => c,
487
        Err(e) => return note(format!("image {}: cannot reach the hub: {e:#}", &hash[..12])),
488
    };
b14aeaae Andy McCall ↶ 489
    let fetched = match swarm {
490
        Some(sw) => {
491
            note(format!("image {} is not on this runner: fetching it from its peers and the hub", &hash[..12]));
492
            sw.fetch(home, hash)
493
        }
494
        None => {
495
            note(format!("image {} is not on this runner: fetching it from the hub", &hash[..12]));
496
            client.fetch(home, hash)
497
        }
498
    };
499
    match fetched {
4cf0c99a Andy McCall ↶ 500
        Ok(Some(m)) => note(format!(
b14aeaae Andy McCall ↶ 501
            "image {}: fetched {} chunks, {}{} in {:.1} s",
4cf0c99a Andy McCall ↶ 502
            &hash[..12],
503
            m.chunks,
504
            crate::images::human(m.bytes),
b14aeaae Andy McCall ↶ 505
            if swarm.is_some() { format!(" ({} from peers)", crate::images::human(m.peer_bytes)) } else { String::new() },
4cf0c99a Andy McCall ↶ 506
            m.elapsed.as_secs_f64()
507
        )),
508
        Ok(None) => note(format!("image {}: the hub does not hold it either", &hash[..12])),
509
        Err(e) => note(format!("image {}: fetch failed: {e:#}", &hash[..12])),
510
    }
511
}
512
b11e30f5 Andy McCall ↶ 513
/// Why this runner cannot run `claim` now (spec §11.5), checked before
514
/// anything is fetched: the tier, the architecture, the image and the
515
/// memory. The hub chose it from what the runner last said, which may be
516
/// out of date.
517
fn preflight(home: &Home, claim: &Claim) -> Option<String> {
518
    let sb = &claim.sandbox;
519
    match sb.runtime {
520
        flow_core::Runtime::Microvm => {
521
            if let Err(e) = std::fs::OpenOptions::new().read(true).write(true).open("/dev/kvm") {
522
                return Some(format!("the MicroVM tier needs /dev/kvm, which cannot be opened here ({e})"));
523
            }
524
            if home.config.microvm.is_none() {
525
                return Some("the MicroVM tier is not set up here (flow.toml has no [microvm] section)".into());
526
            }
527
        }
528
        flow_core::Runtime::Syscall => {
529
            if let Err(e) = crate::syscall::available() {
530
                return Some(format!("the syscall tier cannot run here: {e}"));
531
            }
532
        }
28cc603f Andy McCall ↶ 533
        // No image and no architecture: only the memory matters.
534
        flow_core::Runtime::Wasm => {
535
            return available_memory_mib()
536
                .filter(|free| *free < u64::from(sb.memory_mib))
537
                .map(|free| format!("only {free} MiB of memory is free here; the sandbox needs {} MiB", sb.memory_mib));
538
        }
b11e30f5 Andy McCall ↶ 539
    }
540
    sandbox_problem(home, sb, std::env::consts::ARCH, available_memory_mib())
541
}
542
543
/// What stops `sb` running on this home's images, on a machine of
544
/// architecture `here` with `free_mib` of memory free.
545
fn sandbox_problem(home: &Home, sb: &flow_core::Sandbox, here: &str, free_mib: Option<u64>) -> Option<String> {
546
    if let Some(want) = sb.arch.as_deref().filter(|a| *a != here) {
547
        return Some(format!("the sandbox needs {want}; this runner is {here}"));
548
    }
549
    let short = &sb.rootfs[..12.min(sb.rootfs.len())];
550
    let image = home.rootfs(&sb.rootfs);
551
    if !image.is_file() {
552
        return Some(format!("rootfs {short} is not on this runner"));
553
    }
554
    if let Some(arch) = home.image_arch(&sb.rootfs).filter(|a| a != here) {
555
        return Some(format!("rootfs {short} is for {arch}; this runner is {here}"));
556
    }
557
    if let Err(e) = home.verified(&image, &sb.rootfs) {
558
        return Some(format!("rootfs {short} does not verify here: {e:#}"));
559
    }
560
    if let Some(free) = free_mib.filter(|free| *free < u64::from(sb.memory_mib)) {
561
        return Some(format!("only {free} MiB of memory is free here; the sandbox needs {} MiB", sb.memory_mib));
562
    }
563
    None
564
}
565
566
/// `MemAvailable` from /proc/meminfo, in MiB.
567
fn available_memory_mib() -> Option<u64> {
568
    let info = std::fs::read_to_string("/proc/meminfo").ok()?;
569
    let kib: u64 = info.lines().find_map(|l| l.strip_prefix("MemAvailable:"))?.trim().trim_end_matches("kB").trim().parse().ok()?;
570
    Some(kib / 1024)
c5b702e5 Andy McCall ↶ 571
}
572
e0918b88 Andy McCall 573
pub fn serve(home: &Home) -> Result<()> {
574
    let cfg = home.config.runner.clone().context("flow.toml has no [runner] section")?;
c5b702e5 Andy McCall ↶ 575
    // A runner offers only what it can run: a machine without KVM claims
576
    // nothing rather than taking MicroVM jobs and failing them (#36).
ea56c56e Andy McCall ↶ 577
    let (runtimes, missing) = tiers(home).map_err(|why| anyhow::anyhow!("flow runner: {why}"))?;
578
    for why in &missing {
579
        eprintln!("flow runner: not offering {why}");
580
    }
e0918b88 Andy McCall 581
    let hub = Hub::new(&cfg)?;
582
    let name = cfg.name.clone().unwrap_or_else(|| "flow".into());
bb643c25 Andy McCall ↶ 583
    let budget = Budget::of(&cfg);
89171fca Andy McCall ↶ 584
    drain_on_stop();
47c1d64d Andy McCall ↶ 585
    let key = home.runner_key(&name)?;
b14aeaae Andy McCall ↶ 586
    // The swarm (docs/jetstream.md §8.1): a runner that cannot serve its
587
    // peers still runs jobs, fetching images from the hub alone.
588
    let swarm = crate::swarm::Swarm::start(home, &cfg).unwrap_or_else(|e| {
589
        eprintln!("flow runner: not joining the swarm: {e:#}");
590
        None
591
    });
47c1d64d Andy McCall ↶ 592
    eprintln!(
c5b702e5 Andy McCall ↶ 593
        "flow runner {name}: polling {} (up to {} jobs at once, tiers {}), signing receipts as {}",
47c1d64d Andy McCall ↶ 594
        cfg.hub,
595
        budget.max_jobs,
c5b702e5 Andy McCall ↶ 596
        runtimes.join(", "),
47c1d64d Andy McCall ↶ 597
        key.identity.hash().to_hex()
598
    );
4be5e4cd Andy McCall ↶ 599
    if let Some(addr) = &cfg.metrics {
600
        crate::metrics::serve(addr, cfg.metrics_token.clone(), name.clone());
601
    }
bb643c25 Andy McCall ↶ 602
    let used = std::sync::Mutex::new(Used::default());
e0918b88 Andy McCall 603
    let mut idle = Duration::from_secs(2);
3007d8f0 Andy McCall ↶ 604
    let pending = report_pending(home);
1daca0b6 Andy McCall ↶ 605
    // The jobs held now, told to the hub at each claim so it can end the
606
    // ones this runner lost: a job is held from its claim until its result
607
    // is reported.
608
    let held = std::sync::Mutex::new(std::collections::BTreeSet::<i64>::new());
609
    held.lock().unwrap().extend(pending.iter().map(|(job, _)| *job));
3007d8f0 Andy McCall ↶ 610
    std::thread::scope(|scope| {
611
        for (job, f) in pending {
1daca0b6 Andy McCall ↶ 612
            let (hub, held) = (&hub, &held);
3007d8f0 Andy McCall ↶ 613
            scope.spawn(move || {
614
                eprintln!("job {job}: reporting the result kept from before the restart");
615
                report_finish(home, hub, job, &f);
1daca0b6 Andy McCall ↶ 616
                held.lock().unwrap().remove(&job);
3007d8f0 Andy McCall ↶ 617
            });
618
        }
62829d15 Andy McCall ↶ 619
        // The speed (spec §11.1): measured now, and again every 15 minutes
620
        // while no job runs, so a job never shares the CPU with it.
621
        let measure = || {
622
            let (speed, ms) = crate::facts::bench();
623
            eprintln!("flow runner {name}: speed {speed} (class {}), benchmark {ms} ms", flow_core::api::Facts::class_of(speed));
624
            speed
625
        };
626
        let mut speed = measure();
627
        let mut benched = Instant::now();
89171fca Andy McCall ↶ 628
        let mut said_draining = false;
a4b3f8cb Andy McCall ↶ 629
        // When the hub last heard from us (oxygenhub#243): a claim, or a
630
        // heartbeat while there is no room to claim.
631
        let mut heard = Instant::now();
632
        let beat = |heard: &mut Instant| {
633
            if heard.elapsed() >= HUB_HEARTBEAT {
634
                if let Err(e) = hub.heartbeat() {
635
                    eprintln!("flow runner {name}: heartbeat: {e:#}");
636
                }
637
                *heard = Instant::now();
638
            }
639
        };
3007d8f0 Andy McCall ↶ 640
        loop {
89171fca Andy McCall ↶ 641
            // Draining (oxygenflow#50): told to stop, claim nothing more and
642
            // stop once every job held is done and reported.
643
            if stopping() {
644
                let (jobs, holding) = (used.lock().unwrap().jobs, held.lock().unwrap().len());
645
                if jobs == 0 && holding == 0 {
646
                    eprintln!("flow runner {name}: drained, stopping");
647
                    break;
648
                }
649
                if !said_draining {
650
                    eprintln!("flow runner {name}: draining: claiming nothing more, stopping when the {jobs} job(s) held are done (stop again to stop now)");
651
                    said_draining = true;
652
                }
a4b3f8cb Andy McCall ↶ 653
                beat(&mut heard);
89171fca Andy McCall ↶ 654
                std::thread::sleep(Duration::from_millis(500));
655
                continue;
656
            }
62829d15 Andy McCall ↶ 657
            if used.lock().unwrap().jobs == 0 && benched.elapsed() >= Duration::from_secs(15 * 60) {
658
                speed = measure();
659
                benched = Instant::now();
660
            }
3007d8f0 Andy McCall ↶ 661
            let room = budget.room(*used.lock().unwrap());
662
            let Some((free_memory_mib, free_cpus)) = room else {
a4b3f8cb Andy McCall ↶ 663
                beat(&mut heard);
3007d8f0 Andy McCall ↶ 664
                std::thread::sleep(Duration::from_millis(500));
665
                continue;
666
            };
a4b3f8cb Andy McCall ↶ 667
            heard = Instant::now();
1e6b9fb1 Andy McCall ↶ 668
            let cache_times = crate::cache::Pool::new(&home.root, cfg.cache_gb).slot_times();
3007d8f0 Andy McCall ↶ 669
            let req = ClaimRequest {
670
                runner: name.clone(),
c5b702e5 Andy McCall ↶ 671
                runtimes: runtimes.clone(),
3007d8f0 Andy McCall ↶ 672
                free_memory_mib,
673
                free_cpus,
674
                info: Some(RunnerInfo {
675
                    version: env!("OXY_VERSION_LONG").into(),
ea81796b Andy McCall ↶ 676
                    ..RunnerInfo::here(cfg.offered_labels(), budget.max_jobs as u32, cfg.memory_mib, cfg.cpus)
3007d8f0 Andy McCall ↶ 677
                }),
8c0a4e3a Andy McCall ↶ 678
                // Read each time: an image imported while the runner runs counts.
679
                images: Some(home.images()),
1abadd4a Andy McCall ↶ 680
                image_archs: Some(home.image_archs()),
1daca0b6 Andy McCall ↶ 681
                holding: Some(held.lock().unwrap().iter().copied().collect()),
4cf0c99a Andy McCall ↶ 682
                fetches_images: true,
62829d15 Andy McCall ↶ 683
                facts: Some(crate::facts::now(home, Some(speed))),
b14aeaae Andy McCall ↶ 684
                swarm: swarm.as_ref().map(|s| s.addr.clone()),
1e6b9fb1 Andy McCall ↶ 685
                caches: Some(cache_times.keys().cloned().collect()),
686
                cache_times: Some(cache_times),
3007d8f0 Andy McCall ↶ 687
            };
688
            match hub.claim(&req) {
689
                Ok(Some(claim)) => {
690
                    idle = Duration::from_secs(2);
4be5e4cd Andy McCall ↶ 691
                    crate::metrics::CLAIMS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
3007d8f0 Andy McCall ↶ 692
                    let (mem, cpus) = (claim.sandbox.memory_mib, claim.sandbox.cpus);
693
                    {
694
                        let mut u = used.lock().unwrap();
695
                        u.jobs += 1;
696
                        u.memory_mib += mem;
697
                        u.cpus += cpus;
bb643c25 Andy McCall ↶ 698
                    }
1daca0b6 Andy McCall ↶ 699
                    held.lock().unwrap().insert(claim.job_id);
b14aeaae Andy McCall ↶ 700
                    let (home, hub, cfg, used, key, held, swarm) = (home, &hub, &cfg, &used, &key, &held, swarm.as_ref());
3007d8f0 Andy McCall ↶ 701
                    scope.spawn(move || {
702
                        let id = claim.job_id;
b14aeaae Andy McCall ↶ 703
                        fetch_image(home, hub, cfg, swarm, &claim);
b11e30f5 Andy McCall ↶ 704
                        if let Some(why) = preflight(home, &claim) {
705
                            eprintln!("job {id}: declined: {why}");
4be5e4cd Andy McCall ↶ 706
                            crate::metrics::DECLINED.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
b11e30f5 Andy McCall ↶ 707
                            if let Err(e) = hub.decline(id, &why) {
708
                                eprintln!("job {id}: decline: {e:#}");
709
                            }
710
                            held.lock().unwrap().remove(&id);
711
                            let mut u = used.lock().unwrap();
712
                            u.jobs -= 1;
713
                            u.memory_mib -= mem;
714
                            u.cpus -= cpus;
715
                            return;
716
                        }
3007d8f0 Andy McCall ↶ 717
                        eprintln!(
718
                            "job {id}: {} {} on {}",
719
                            claim.repo,
720
                            claim.job.name,
721
                            claim.heads.first().map(|h| &h[..12]).unwrap_or("-")
722
                        );
4be5e4cd Andy McCall ↶ 723
                        crate::metrics::RUNNING.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
3007d8f0 Andy McCall ↶ 724
                        let finish = run_claim(home, hub, cfg, key, &claim).unwrap_or_else(|e| Finish {
725
                            exit_code: None,
726
                            duration_ms: 0,
727
                            receipt: None,
728
                            signed_receipt: None,
729
                            error: Some(format!("{e:#}")),
8f211e20 Andy McCall ↶ 730
                            peak_disk_mib: None,
731
                            peak_memory_mib: None,
3007d8f0 Andy McCall ↶ 732
                        });
733
                        eprintln!(
734
                            "job {id}: exit {:?}{}",
735
                            finish.exit_code,
736
                            finish.error.as_deref().map(|e| format!(" ({e})")).unwrap_or_default()
737
                        );
4be5e4cd Andy McCall ↶ 738
                        crate::metrics::RUNNING.fetch_sub(1, std::sync::atomic::Ordering::Relaxed);
739
                        let cancelled = finish.error.as_deref() == Some(CANCELLED);
740
                        crate::metrics::finished(finish.exit_code, finish.error.as_deref(), finish.duration_ms, cancelled);
741
                        if !cancelled {
280ef951 Andy McCall ↶ 742
                            report_finish(home, hub, id, &finish);
743
                        }
1daca0b6 Andy McCall ↶ 744
                        held.lock().unwrap().remove(&id);
3007d8f0 Andy McCall ↶ 745
                        let mut u = used.lock().unwrap();
746
                        u.jobs -= 1;
747
                        u.memory_mib -= mem;
748
                        u.cpus -= cpus;
749
                    });
750
                }
751
                Ok(None) => std::thread::sleep(idle),
752
                Err(e) => {
753
                    eprintln!("claim: {e:#}");
754
                    std::thread::sleep(idle);
755
                    idle = (idle * 2).min(Duration::from_secs(60));
756
                }
e0918b88 Andy McCall 757
            }
758
        }
89171fca Andy McCall ↶ 759
        Ok(())
bb643c25 Andy McCall ↶ 760
    })
89171fca Andy McCall ↶ 761
}
762
763
/// How many times the runner was told to stop (SIGTERM or SIGINT).
764
static STOPS: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
765
766
extern "C" fn on_stop(_: libc::c_int) {
767
    // A second stop means now: only async-signal-safe calls here.
768
    if STOPS.fetch_add(1, std::sync::atomic::Ordering::SeqCst) >= 1 {
769
        unsafe { libc::_exit(143) };
770
    }
771
}
772
773
/// Drain instead of dying on the first SIGTERM or SIGINT (oxygenflow#50),
774
/// so restarting a runner never kills the job it runs: the unit's
775
/// `KillMode=mixed` sends the signal to the runner alone, not its microVMs.
776
fn drain_on_stop() {
777
    let handler = on_stop as extern "C" fn(libc::c_int) as libc::sighandler_t;
778
    unsafe {
779
        libc::signal(libc::SIGTERM, handler);
780
        libc::signal(libc::SIGINT, handler);
781
    }
e0918b88 Andy McCall 782
}
783
89171fca Andy McCall ↶ 784
fn stopping() -> bool {
785
    STOPS.load(std::sync::atomic::Ordering::SeqCst) > 0
786
}
787
280ef951 Andy McCall ↶ 788
/// Batches records to the hub every second (or every 200 lines). A quiet
789
/// job's sink still asks the hub every few seconds whether the job runs,
790
/// with an empty batch; once the hub answers 409 the job is not wanted.
e0918b88 Andy McCall 791
struct LogSink<'a> {
792
    hub: &'a Hub,
793
    job: i64,
794
    buf: Vec<Record>,
795
    last: Instant,
280ef951 Andy McCall ↶ 796
    gone: bool,
797
}
89171fca Andy McCall ↶ 798
799
/// The most log lines sent at once, as a busy job's sink flushes them.
800
const BATCH: usize = 200;
280ef951 Andy McCall ↶ 801
89171fca Andy McCall ↶ 802
/// The most log lines kept while the hub cannot be reached.
803
const MAX_UNSENT: usize = 50_000;
804
280ef951 Andy McCall ↶ 805
/// How often a quiet job asks whether it was cancelled.
806
const HEARTBEAT: Duration = Duration::from_secs(5);
807
808
impl microvm::Sink for LogSink<'_> {
809
    fn record(&mut self, r: Record) {
810
        self.push(r)
811
    }
812
813
    fn cancelled(&mut self) -> bool {
814
        if !self.gone && self.last.elapsed() >= HEARTBEAT {
815
            self.send();
816
        }
817
        self.gone
818
    }
e0918b88 Andy McCall 819
}
820
821
impl LogSink<'_> {
822
    fn push(&mut self, mut r: Record) {
280ef951 Andy McCall ↶ 823
        if self.gone {
824
            return;
825
        }
e0918b88 Andy McCall 826
        if r.text.len() > MAX_RECORD_TEXT {
827
            let mut cut = MAX_RECORD_TEXT;
828
            while !r.text.is_char_boundary(cut) {
829
                cut -= 1;
830
            }
831
            r.text.truncate(cut);
832
        }
833
        self.buf.push(r);
89171fca Andy McCall ↶ 834
        if self.buf.len() >= BATCH || self.last.elapsed() >= Duration::from_secs(1) {
e0918b88 Andy McCall 835
            self.flush();
836
        }
837
    }
838
839
    fn flush(&mut self) {
840
        if !self.buf.is_empty() {
280ef951 Andy McCall ↶ 841
            self.send();
842
        }
843
        self.last = Instant::now();
844
    }
845
89171fca Andy McCall ↶ 846
    /// Send what is buffered, even nothing, in batches of at most
847
    /// `BATCH` lines.
280ef951 Andy McCall ↶ 848
    fn send(&mut self) {
89171fca Andy McCall ↶ 849
        loop {
850
            if self.gone {
851
                return;
852
            }
853
            let n = self.buf.len().min(BATCH);
854
            let batch: Vec<Record> = self.buf.drain(..n).collect();
855
            match self.hub.log(self.job, batch.clone()) {
856
                Ok(()) => {}
857
                Err(e) if job_gone(&e) => self.gone = true,
858
                Err(e) => {
859
                    // The hub is away (a restart, say): keep the lines for
860
                    // the next batch, up to a bound, so the log loses none
861
                    // (oxygenflow#49).
862
                    eprintln!("job {}: log: {e:#}; kept for the next batch", self.job);
863
                    let mut kept = batch;
864
                    kept.append(&mut self.buf);
865
                    let over = kept.len().saturating_sub(MAX_UNSENT);
866
                    if over > 0 {
867
                        kept.drain(..over);
868
                        kept.insert(
869
                            0,
870
                            Record {
871
                                t: 0,
872
                                stream: "flow".into(),
873
                                text: format!("({over} log lines lost while the hub could not be reached)"),
874
                            },
875
                        );
876
                    }
877
                    self.buf = kept;
878
                    break;
879
                }
880
            }
881
            if self.buf.is_empty() {
882
                break;
883
            }
e0918b88 Andy McCall 884
        }
885
        self.last = Instant::now();
886
    }
887
}
a4b3f8cb Andy McCall ↶ 888
889
/// How often a runner with no room to claim tells the hub it is there:
890
/// well inside the hub's 90 s before it shows a runner offline.
891
const HUB_HEARTBEAT: Duration = Duration::from_secs(30);
bb643c25 Andy McCall ↶ 892
ed4aef8b Andy McCall ↶ 893
/// Held while a job takes its cache disks and images its workspace (see
894
/// `run_claim`): one job at a time on the runner's disk and cache pool.
bb643c25 Andy McCall ↶ 895
static PREPARE: std::sync::Mutex<()> = std::sync::Mutex::new(());
e0918b88 Andy McCall 896
ed4aef8b Andy McCall ↶ 897
/// Held while the first clone of any repository passes its token through
898
/// the process environment.
899
static CLONE: std::sync::Mutex<()> = std::sync::Mutex::new(());
900
901
/// One lock per cached repository: fetches into it, and exports from it,
902
/// never overlap, while jobs of other repositories go on. A slow repository
903
/// (one kept in a bucket, say) once held every job on the runner waiting
904
/// behind a single global lock.
905
fn repo_lock(name: &str) -> std::sync::Arc<std::sync::Mutex<()>> {
906
    static LOCKS: std::sync::OnceLock<std::sync::Mutex<std::collections::HashMap<String, std::sync::Arc<std::sync::Mutex<()>>>>> =
907
        std::sync::OnceLock::new();
908
    let mut locks = LOCKS.get_or_init(Default::default).lock().unwrap_or_else(|p| p.into_inner());
909
    locks.entry(name.to_string()).or_default().clone()
910
}
911
912
/// Seconds, to one decimal place, for the job's log.
913
fn secs(d: std::time::Duration) -> String {
914
    format!("{:.1} s", d.as_secs_f64())
915
}
916
47c1d64d Andy McCall ↶ 917
fn run_claim(home: &Home, hub: &Hub, cfg: &RunnerConfig, key: &RunnerKey, claim: &Claim) -> Result<Finish> {
e0918b88 Andy McCall 918
    let started = Instant::now();
280ef951 Andy McCall ↶ 919
    let mut sink = LogSink { hub, job: claim.job_id, buf: Vec::new(), last: Instant::now(), gone: false };
e0918b88 Andy McCall 920
    let note =
921
        |sink: &mut LogSink, text: String| sink.push(Record { t: started.elapsed().as_millis() as u64, stream: "flow".into(), text });
922
    let heads: Vec<ChangeHash> = claim.heads.iter().map(|h| ChangeHash::from_hex(h).context("bad head")).collect::<Result<_>>()?;
923
    note(&mut sink, format!("fetching {} for state {}", claim.repo, claim.heads.iter().map(|h| &h[..12]).collect::<Vec<_>>().join("+")));
ed4aef8b Andy McCall ↶ 924
    // Preparing a workspace: fetches into a cached repository, and exports
925
    // from it, are one job at a time per repository (`repo_lock`); taking
926
    // cache disks and imaging the workspace are one job at a time on the
927
    // runner (`PREPARE`); a first clone, whose token goes through the process
928
    // environment, one at a time (`CLONE`).
929
    let main_lock = repo_lock(&claim.repo);
930
    let asked = Instant::now();
931
    let mut main_guard = Some(main_lock.lock().unwrap_or_else(|p| p.into_inner()));
932
    if asked.elapsed().as_secs() >= 2 {
933
        note(&mut sink, format!("waited {} for another job fetching {}", secs(asked.elapsed()), claim.repo));
934
    }
935
    let fetching = Instant::now();
e0918b88 Andy McCall 936
    let repo = cached_repo(home, cfg, claim)?;
ed4aef8b Andy McCall ↶ 937
    let fetched = fetching.elapsed();
938
    let mut preparing = None;
e0918b88 Andy McCall 939
    let scratch = home.root.join("work").join(format!("job-{}", claim.job_id));
940
    let _ = std::fs::remove_dir_all(&scratch);
941
    std::fs::create_dir_all(scratch.join("tree"))?;
942
    let result = (|| -> Result<Finish> {
ed4aef8b Andy McCall ↶ 943
        let exporting = Instant::now();
c23d5191 Andy McCall ↶ 944
        let mut files = workspace::export_state(&repo, &heads, &scratch.join("tree"))?;
ed4aef8b Andy McCall ↶ 945
        main_guard.take();
946
        note(&mut sink, format!("fetched in {}, {} files exported in {}", secs(fetched), files.len(), secs(exporting.elapsed())));
c23d5191 Andy McCall ↶ 947
        // Pinned subrepos (Oxygen spec §7.8), at their paths, as part of the
948
        // workspace and of the scope hash.
949
        for sub in &claim.subrepos {
950
            if sub.path.split('/').any(|p| p.is_empty() || p == "." || p == ".." || p == ".oxy") {
951
                bail!("subrepo path {:?} is not a clean relative path", sub.path);
952
            }
953
            note(
954
                &mut sink,
955
                format!(
956
                    "fetching subrepo {} at {} for {}",
957
                    sub.repo,
958
                    sub.heads.iter().map(|h| &h[..12]).collect::<Vec<_>>().join("+"),
959
                    sub.path
960
                ),
961
            );
ed4aef8b Andy McCall ↶ 962
            let sub_lock = repo_lock(&sub.repo);
963
            let asked = Instant::now();
964
            let sub_guard = sub_lock.lock().unwrap_or_else(|p| p.into_inner());
965
            if asked.elapsed().as_secs() >= 2 {
966
                note(&mut sink, format!("waited {} for another job fetching {}", secs(asked.elapsed()), sub.repo));
967
            }
c23d5191 Andy McCall ↶ 968
            let sub_repo = cached_repo_at(home, cfg, &sub.repo, &sub.clone_url, &claim.token)?;
969
            let sub_heads: Vec<ChangeHash> =
970
                sub.heads.iter().map(|h| ChangeHash::from_hex(h).context("bad subrepo head")).collect::<Result<_>>()?;
971
            let dir = scratch.join("tree").join(&sub.path);
972
            std::fs::create_dir_all(&dir)?;
973
            let sub_files = workspace::export_state(&sub_repo, &sub_heads, &dir)?;
ed4aef8b Andy McCall ↶ 974
            drop(sub_guard);
c23d5191 Andy McCall ↶ 975
            files.extend(sub_files.into_iter().map(|(p, h)| (format!("{}/{p}", sub.path), h)));
976
        }
e0918b88 Andy McCall 977
        let scope_hash = scope_tree_hash(&claim.job.scope, files.iter().map(|(p, h)| (p.as_str(), *h)));
46fe2c81 Andy McCall ↶ 978
        // Inputs (oxygenflow#58): each producing job's artifact, checked
979
        // against the blob its receipt names, then put at its path. Not part
980
        // of the scope: they are the run's, not the repository's.
981
        let mut input_blobs = Vec::new();
982
        for (index, i) in claim.inputs.iter().enumerate() {
983
            let what = format!("input {} from {}", i.artifact, i.from);
984
            let bytes = hub.input(claim.job_id, index).with_context(|| format!("{what}: fetching it"))?;
985
            let blob = place_input(&scratch.join("tree"), i, &bytes).with_context(|| what.clone())?;
986
            note(&mut sink, format!("{what}: {} bytes at {}, blob {} as its receipt names", bytes.len(), i.path, &i.blob[..12]));
987
            input_blobs.push(blob);
988
        }
ea56c56e Andy McCall ↶ 989
        // The syscall tier runs on the tree itself; a microVM gets an image.
990
        let syscall_tier = claim.sandbox.runtime == flow_core::Runtime::Syscall;
28cc603f Andy McCall ↶ 991
        let wasm_tier = claim.sandbox.runtime == flow_core::Runtime::Wasm;
992
        // The syscall and WASM tiers see the job's files as a directory;
993
        // the MicroVM tier as an ext4 image.
994
        let dir_tier = syscall_tier || wasm_tier;
82cf6e91 Andy McCall ↶ 995
        let job = claim.job.in_sandbox(&claim.sandbox).with_flow_env(&claim.flow_env());
2594278f Andy McCall ↶ 996
        // Disk mounts that name a cache start from a kept disk (#28): a
997
        // microVM takes an image already in place as it is, the syscall tier
998
        // a directory (#70). Taken before the workspace is imaged: the
999
        // sources the disk was built from give unchanged files their old
1000
        // times back (#52).
ed4aef8b Andy McCall ↶ 1001
        let asked = Instant::now();
1002
        preparing = Some(PREPARE.lock().unwrap_or_else(|p| p.into_inner()));
1003
        if asked.elapsed().as_secs() >= 2 {
1004
            note(&mut sink, format!("waited {} for another job imaging its workspace", secs(asked.elapsed())));
1005
        }
82cf6e91 Andy McCall ↶ 1006
        let pool = crate::cache::Pool::new(&home.root, cfg.cache_gb);
28cc603f Andy McCall ↶ 1007
        let form = if dir_tier { crate::cache::Form::Dir } else { crate::cache::Form::Image };
82cf6e91 Andy McCall ↶ 1008
        let cache_ctx =
2594278f Andy McCall ↶ 1009
            crate::cache::Ctx { repo: &claim.repo, bookmark: &claim.bookmark, job: &claim.job.name, image: &claim.sandbox.rootfs, form };
82cf6e91 Andy McCall ↶ 1010
        let mut cached: Vec<(usize, String, String)> = Vec::new();
1011
        let mut built_from: Option<crate::cache::Sources> = None;
2594278f Andy McCall ↶ 1012
        for (i, m) in job.mounts.iter().filter(|m| m.source == flow_core::pipeline::MountSource::Disk).enumerate() {
1013
            let Some(name) = &m.cache else { continue };
1014
            let key = crate::cache::Pool::key(&cache_ctx, m, |p| files.iter().find(|(f, _)| f == p).map(|(_, h)| hex::encode(h)));
1015
            let how = match pool.take(&cache_ctx, m, &key, &crate::cache::disk_path(form, &scratch, i)) {
1016
                Some(t) => {
1017
                    if built_from.is_none() {
1018
                        built_from = t.sources;
82cf6e91 Andy McCall ↶ 1019
                    }
2594278f Andy McCall ↶ 1020
                    t.how
1021
                }
1022
                None => format!("cache {name}: none kept yet, an empty disk"),
1023
            };
1024
            note(&mut sink, format!("{} ({})", how, m.target));
077a6524 Andy McCall ↶ 1025
            // What the job reads is seen when the disk is pruned (#72).
1026
            if let Err(e) = crate::cache::forget_reads(form, &crate::cache::disk_path(form, &scratch, i)) {
1027
                note(&mut sink, format!("cache {name}: {e:#}"));
1028
            }
2594278f Andy McCall ↶ 1029
            cached.push((i, key, how));
82cf6e91 Andy McCall ↶ 1030
        }
077a6524 Andy McCall ↶ 1031
        // What the job reads or writes on its cache from now on is what it
1032
        // used; the rest may be pruned before the cache is kept (#72).
1033
        let cache_started = if cached.is_empty() { std::time::SystemTime::now() } else { flow_init::prune::start_clock() };
82cf6e91 Andy McCall ↶ 1034
        let sources = if cached.is_empty() {
1035
            crate::cache::Sources::new()
1036
        } else {
1037
            let (sources, restored) = workspace::restore_times(&scratch.join("tree"), &files, built_from.as_ref());
1038
            if built_from.is_some() {
1039
                note(&mut sink, format!("cache: {restored} of {} files unchanged since the cached build, their times kept", sources.len()));
1040
            }
1041
            sources
1042
        };
28cc603f Andy McCall ↶ 1043
        if !dir_tier {
ea56c56e Andy McCall ↶ 1044
            workspace::image(&scratch.join("tree"), &scratch.join("workspace.ext4"))?;
1045
            std::fs::remove_dir_all(scratch.join("tree"))?;
1046
        }
bb643c25 Andy McCall ↶ 1047
        preparing.take();
ea56c56e Andy McCall ↶ 1048
        // Cancelled while it was being prepared: no sandbox.
280ef951 Andy McCall ↶ 1049
        if microvm::Sink::cancelled(&mut sink) {
1050
            return Ok(cancelled());
1051
        }
28cc603f Andy McCall ↶ 1052
        if wasm_tier {
1053
            note(&mut sink, format!("starting WASM (wasmtime {}): {} MiB", crate::wasm::WASMTIME, claim.sandbox.memory_mib));
1054
        } else {
1055
            note(
1056
                &mut sink,
1057
                format!(
1058
                    "{}: {} {}, {} MiB, rootfs {}",
1059
                    if syscall_tier { "starting a syscall sandbox" } else { "booting a microVM" },
1060
                    claim.sandbox.cpus,
1061
                    if syscall_tier { "CPU" } else { "vCPU" },
1062
                    claim.sandbox.memory_mib,
1063
                    &claim.sandbox.rootfs[..12]
1064
                ),
1065
            );
1066
        }
ea56c56e Andy McCall ↶ 1067
        let timeout = Duration::from_secs(claim.timeout_s);
28cc603f Andy McCall ↶ 1068
        let mut outcome = if wasm_tier {
1069
            crate::wasm::run(&claim.sandbox, &job, &scratch.join("tree"), &scratch, timeout, &mut sink)?
1070
        } else if syscall_tier {
ea56c56e Andy McCall ↶ 1071
            let group = format!("job-{}", claim.job_id);
1072
            crate::syscall::run(home, &claim.sandbox, &job, &claim.secrets, &scratch.join("tree"), &scratch, timeout, &mut sink, &group)?
1073
        } else {
1074
            microvm::run(home, &claim.sandbox, &job, &claim.secrets, &scratch.join("workspace.ext4"), &scratch, timeout, &mut sink)?
1075
        };
280ef951 Andy McCall ↶ 1076
        if outcome.cancelled {
1077
            return Ok(cancelled());
d60aac6c Andy McCall ↶ 1078
        }
1079
        // The receipt says what a cached disk started from.
1080
        let disk_mounts: Vec<&flow_core::pipeline::Mount> =
1081
            job.mounts.iter().filter(|m| m.source == flow_core::pipeline::MountSource::Disk).collect();
1082
        for (i, key, how) in &cached {
1083
            outcome.environment.parts.push((format!("cache {}", disk_mounts[*i].target), format!("{key}: {how}")));
280ef951 Andy McCall ↶ 1084
        }
a67b97e9 Andy McCall ↶ 1085
        // A passing job's artifacts, read from its disks and uploaded; a
9a6fac2b Andy McCall ↶ 1086
        // declared artifact that cannot be kept fails the job. A failing
1087
        // job keeps only its `when "always"` ones (oxygenflow#37), outside
1088
        // its receipt, and one it cannot keep is only noted.
a67b97e9 Andy McCall ↶ 1089
        let mut outputs = vec![];
1090
        let mut output_error = None;
9a6fac2b Andy McCall ↶ 1091
        let passed = outcome.exit_code == Some(0);
1092
        let wanted = claim.job.outputs.iter().filter(|o| passed || o.always);
1093
        for o in wanted {
6d53fb7d Andy McCall ↶ 1094
            if o.kind == flow_core::OutputKind::Report {
28cc603f Andy McCall ↶ 1095
                let read = if dir_tier {
6d53fb7d Andy McCall ↶ 1096
                    let (dir, inner) = crate::outputs::locate_dir(&claim.job, &scratch.join("tree"), &scratch, &o.path);
1097
                    crate::outputs::read_report_dir(&dir, &inner)
1098
                } else {
1099
                    let (image, inner) = crate::outputs::locate(&claim.job, &scratch.join("workspace.ext4"), &scratch, &o.path);
1100
                    crate::outputs::read_report(&image, &inner, &scratch)
1101
                };
1102
                let kept = read.and_then(|files| upload_report(hub, claim.job_id, &o.name, &files));
1103
                match kept {
1104
                    Ok((blob, files, bytes)) => {
1105
                        let unattested = if passed { "" } else { " (the job failed: not in its receipt)" };
1106
                        let hex = blob.to_hex();
1107
                        note(&mut sink, format!("report {}: {files} files, {bytes} bytes, manifest {}{unattested}", o.name, &hex[..12]));
1108
                        if passed {
1109
                            outputs.push(blob.0);
1110
                        }
1111
                    }
1112
                    Err(e) if passed => {
1113
                        output_error = Some(format!("report {}: {e:#}", o.name));
1114
                        break;
1115
                    }
1116
                    Err(e) => note(&mut sink, format!("report {}: not kept: {e:#}", o.name)),
1117
                }
1118
                continue;
1119
            }
28cc603f Andy McCall ↶ 1120
            let read = if dir_tier {
9a6fac2b Andy McCall ↶ 1121
                let (dir, inner) = crate::outputs::locate_dir(&claim.job, &scratch.join("tree"), &scratch, &o.path);
1122
                crate::outputs::read_dir_file(&dir, &inner)
1123
            } else {
1124
                let (image, inner) = crate::outputs::locate(&claim.job, &scratch.join("workspace.ext4"), &scratch, &o.path);
1125
                crate::outputs::read(&image, &inner, &scratch)
1126
            };
1127
            let kept = read.and_then(|bytes| {
1128
                let blob = Repo::blob_ref(&bytes);
1129
                let named = hub.artifact(claim.job_id, &o.name, &bytes)?;
1130
                if named != blob.to_hex() {
1131
                    bail!("the hub kept it as {named}, not {}", blob.to_hex());
1132
                }
1133
                let unattested = if passed { "" } else { " (the job failed: not in its receipt)" };
1134
                note(&mut sink, format!("artifact {}: {} bytes, blob {}{unattested}", o.name, bytes.len(), &named[..12]));
1135
                Ok(blob.0)
1136
            });
1137
            match kept {
1138
                Ok(b) if passed => outputs.push(b),
1139
                Ok(_) => {}
1140
                Err(e) if passed => {
1141
                    output_error = Some(format!("artifact {}: {e:#}", o.name));
1142
                    break;
a67b97e9 Andy McCall ↶ 1143
                }
9a6fac2b Andy McCall ↶ 1144
                Err(e) => note(&mut sink, format!("artifact {}: not kept: {e:#}", o.name)),
a67b97e9 Andy McCall ↶ 1145
            }
1146
        }
1147
        if let Some(e) = &output_error {
1148
            note(&mut sink, e.clone());
1149
        }
1150
        let receipt = outcome.exit_code.filter(|_| output_error.is_none()).map(|code| Receipt {
e0918b88 Andy McCall 1151
            job_name: claim.job.name.clone(),
1152
            pipeline_hash: hex32(&claim.pipeline_hash),
1153
            scope_tree_hash: scope_hash,
46fe2c81 Andy McCall ↶ 1154
            inputs: input_blobs.clone(),
e0918b88 Andy McCall 1155
            environment: outcome.environment.hash(),
a67b97e9 Andy McCall ↶ 1156
            outputs,
e0918b88 Andy McCall 1157
            exit_code: code as u32,
1158
            duration_ms: outcome.duration_ms,
1159
        });
47c1d64d Andy McCall ↶ 1160
        let signed_receipt = match &receipt {
35f7a849 Andy McCall ↶ 1161
            Some(r) => {
1162
                let mut signed = sign_receipt(&repo, &heads, cfg, key, claim, r)?;
1163
                if cfg.keyless {
1164
                    match sign_keyless(&repo, &heads, cfg, hub, claim, r) {
1165
                        Ok(k) => signed = k,
1166
                        Err(e) => {
1167
                            note(&mut sink, format!("receipt: signed with the runner's key; a short-lived key was not certified: {e:#}"))
1168
                        }
1169
                    }
1170
                }
1171
                Some(hex::encode(signed.encode()))
1172
            }
47c1d64d Andy McCall ↶ 1173
            None => None,
1174
        };
d60aac6c Andy McCall ↶ 1175
        // Measured before a cached disk leaves the scratch directory.
1176
        let peak_disk_mib = crate::facts::allocated_mib(&scratch);
077a6524 Andy McCall ↶ 1177
        // A passing job's cached disks are pruned and kept (#72); a
1178
        // failing job's are thrown away, so nothing it wrote reaches a
1179
        // later job.
2594278f Andy McCall ↶ 1180
        let kept = passed && output_error.is_none();
1181
        for (i, key, _) in &cached {
1182
            let disk = crate::cache::disk_path(form, &scratch, *i);
077a6524 Andy McCall ↶ 1183
            let m = disk_mounts[*i];
1184
            let prune = crate::cache::Prune {
1185
                started: cache_started,
1186
                percent: cfg.cache_prune_percent.unwrap_or(flow_init::prune::DEFAULT_PERCENT),
1187
                guest: outcome.pruned.iter().find(|(t, _)| *t == m.target).map(|(_, p)| p),
1188
            };
1189
            match pool.settle(&cache_ctx, m, key, &disk, &sources, kept, &prune) {
1190
                Ok(Some(line)) => note(&mut sink, line),
1191
                Ok(None) => {}
1192
                Err(e) => note(&mut sink, format!("cache: not {}: {e:#}", if kept { "kept" } else { "discarded" })),
d60aac6c Andy McCall ↶ 1193
            }
1194
        }
e0918b88 Andy McCall 1195
        Ok(Finish {
1196
            exit_code: outcome.exit_code,
1197
            duration_ms: started.elapsed().as_millis() as u64,
1198
            receipt,
47c1d64d Andy McCall ↶ 1199
            signed_receipt,
a67b97e9 Andy McCall ↶ 1200
            error: output_error.or_else(|| outcome.timed_out.then(|| "stopped at the time limit".to_string())),
8f211e20 Andy McCall ↶ 1201
            // What the job took (oxygenflow#41): its disks are sparse files
1202
            // in the scratch directory, so their blocks now are their peak.
d60aac6c Andy McCall ↶ 1203
            peak_disk_mib,
8f211e20 Andy McCall ↶ 1204
            peak_memory_mib: outcome.peak_memory_mib,
e0918b88 Andy McCall 1205
        })
1206
    })();
ea56c56e Andy McCall ↶ 1207
    let _ = workspace::remove_tree(&scratch);
e0918b88 Andy McCall 1208
    sink.flush();
1209
    result
47c1d64d Andy McCall ↶ 1210
}
1211
1212
/// Bind `receipt` to the state of `heads` in `repo` and sign it as the
1213
/// runner (Oxygen spec §14.6). The state is computed here, not taken from
1214
/// the claim, so the runner vouches only for what it fetched.
6d53fb7d Andy McCall ↶ 1215
/// Upload a report's files, then its manifest under the report's name, and
1216
/// check the hub kept each as the blob it should (oxygenhub#127). Answers
1217
/// the manifest's blob, the file count and their total size.
1218
fn upload_report(hub: &Hub, job: i64, name: &str, files: &[(String, Vec<u8>)]) -> Result<(oxy_core::hash::ObjectRef, usize, u64)> {
1219
    let mut listed = Vec::with_capacity(files.len());
1220
    let mut total = 0u64;
1221
    for (path, bytes) in files {
1222
        let blob = Repo::blob_ref(bytes).to_hex();
1223
        let named = hub.report_file(job, name, path, bytes).with_context(|| format!("uploading {path}"))?;
1224
        if named != blob {
1225
            bail!("the hub kept {path} as {named}, not {blob}");
1226
        }
1227
        total += bytes.len() as u64;
1228
        listed.push(serde_json::json!({ "path": path, "blob": blob, "size": bytes.len() }));
1229
    }
1230
    let manifest = serde_json::to_vec(&serde_json::json!({ "version": 1, "files": listed }))?;
1231
    let blob = Repo::blob_ref(&manifest);
1232
    let named = hub.artifact(job, name, &manifest)?;
1233
    if named != blob.to_hex() {
1234
        bail!("the hub kept the manifest as {named}, not {}", blob.to_hex());
1235
    }
1236
    Ok((blob, files.len(), total))
1237
}
1238
47c1d64d Andy McCall ↶ 1239
fn sign_receipt(
1240
    repo: &Repo,
1241
    heads: &[ChangeHash],
1242
    cfg: &RunnerConfig,
1243
    key: &RunnerKey,
1244
    claim: &Claim,
1245
    receipt: &Receipt,
1246
) -> Result<oxy_core::receipt::SignedReceipt> {
1247
    let state = state_of(heads);
1248
    let run = format!("{}/{}/flow/{}", cfg.hub.trim_end_matches('/'), claim.repo, claim.run_number);
1249
    Ok(oxy_core::receipt::SignedReceipt::sign(receipt.to_oxy(), repo.id()?, state, &run, &key.identity, &key.secret))
1250
}
1251
35f7a849 Andy McCall ↶ 1252
/// Sign `receipt` with a fresh key the hub certifies for this job now,
1253
/// just before signing, so the certificate covers the moment the hub
1254
/// accepts it (keyless, oxygenhub#241). The key is dropped with the
1255
/// receipt signed: nothing long-lived signs.
1256
fn sign_keyless(
1257
    repo: &Repo,
1258
    heads: &[ChangeHash],
1259
    cfg: &RunnerConfig,
1260
    hub: &Hub,
1261
    claim: &Claim,
1262
    receipt: &Receipt,
1263
) -> Result<oxy_core::receipt::SignedReceipt> {
1264
    let sk = oxy_core::identity::SecretKey::generate();
1265
    let now = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map(|d| d.as_millis() as u64).unwrap_or(0);
1266
    let name = format!("{} job {}", cfg.name.as_deref().unwrap_or("runner"), claim.job_id);
1267
    let id = sk.identity(&name, "", now);
1268
    let proof = sk.sign_challenge(&id.hash(), &oxy_core::cert::certify_challenge(&claim.token)).map_err(|e| anyhow::anyhow!("{e}"))?;
1269
    let (cert, issuer) = hub.certify(&claim.token, &id, &proof)?;
1270
    let state = state_of(heads);
1271
    let run = format!("{}/{}/flow/{}", cfg.hub.trim_end_matches('/'), claim.repo, claim.run_number);
1272
    Ok(oxy_core::receipt::SignedReceipt::sign(receipt.to_oxy(), repo.id()?, state, &run, &id, &sk).with_certificate(cert, issuer))
1273
}
1274
47c1d64d Andy McCall ↶ 1275
/// The ObjectRef of the state whose heads are `heads` (Oxygen spec §10.1).
1276
pub fn state_of(heads: &[ChangeHash]) -> oxy_core::hash::ObjectRef {
1277
    use oxy_core::hash::{hash_object, ObjectType};
1278
    hash_object(ObjectType::State, &oxy_core::objects::StateObject::new(heads.to_vec()).encode())
e0918b88 Andy McCall 1279
}
1280
1281
fn hex32(s: &str) -> [u8; 32] {
1282
    let mut out = [0; 32];
1283
    if let Ok(v) = hex::decode(s) {
1284
        if v.len() == 32 {
1285
            out.copy_from_slice(&v);
1286
        }
1287
    }
1288
    out
1289
}
1290
f53e6d47 Andy McCall ↶ 1291
/// Whether a network error is worth another try: DNS, a refused or reset
1292
/// connection, a timeout, or a gateway answering 502, 503 or 504 while the
1293
/// hub restarts (oxygenhub#111).
1294
fn transient(msg: &str) -> bool {
1295
    let m = msg.to_lowercase();
1296
    [
1297
        "dns failed",
1298
        "name resolution",
1299
        "connection refused",
1300
        "connection reset",
1301
        "timed out",
1302
        "timeout",
1303
        "http 502",
1304
        "http 503",
1305
        "http 504",
1306
        "broken pipe",
1307
        "unexpected eof",
1308
    ]
1309
    .iter()
1310
    .any(|k| m.contains(k))
1311
}
1312
1313
/// Run `f` again after a transient network error, waiting `waits` between
1314
/// tries (about a minute in all), and give up on any other error at once.
1315
fn with_retries<T>(waits: &[Duration], mut f: impl FnMut() -> Result<T>) -> Result<T> {
1316
    let mut tries = waits.iter();
1317
    loop {
1318
        match f() {
1319
            Ok(v) => return Ok(v),
1320
            Err(e) => match tries.next() {
1321
                Some(w) if transient(&format!("{e:#}")) => std::thread::sleep(*w),
1322
                _ => return Err(e),
1323
            },
1324
        }
1325
    }
1326
}
1327
1328
/// The waits between tries of a fetch: 2, 4, 8, 16 and 30 seconds.
1329
const FETCH_WAITS: [Duration; 5] =
1330
    [Duration::from_secs(2), Duration::from_secs(4), Duration::from_secs(8), Duration::from_secs(16), Duration::from_secs(30)];
1331
e0918b88 Andy McCall 1332
/// The runner's copy of a repository, fetched up to date with the job's token.
1333
fn cached_repo(home: &Home, cfg: &RunnerConfig, claim: &Claim) -> Result<Repo> {
c23d5191 Andy McCall ↶ 1334
    cached_repo_at(home, cfg, &claim.repo, &claim.clone_url, &claim.token)
1335
}
1336
1337
/// The runner's copy of `repo`, cloned or fetched with `token`.
1338
fn cached_repo_at(home: &Home, cfg: &RunnerConfig, repo_name: &str, clone_url: &str, token: &str) -> Result<Repo> {
1339
    let dir: PathBuf = home.root.join("repos").join(repo_name.replace('/', "__"));
e0918b88 Andy McCall 1340
    let set_remote = |repo: &mut Repo| -> Result<()> {
c23d5191 Andy McCall ↶ 1341
        repo.config.set("remote.origin.url", clone_url).map_err(|e| anyhow::anyhow!("{e}"))?;
1342
        repo.config.set("remote.origin.token", token).map_err(|e| anyhow::anyhow!("{e}"))?;
e0918b88 Andy McCall 1343
        if let Some(ca) = &cfg.ca {
1344
            repo.config.set("remote.origin.ca", &ca.to_string_lossy()).map_err(|e| anyhow::anyhow!("{e}"))?;
1345
        }
1346
        repo.save_config().map_err(|e| anyhow::anyhow!("{e}"))
1347
    };
1348
    if dir.join(".oxy").is_dir() {
1349
        let mut repo = Repo::open(&dir).map_err(|e| anyhow::anyhow!("{e}"))?;
1350
        set_remote(&mut repo)?;
f53e6d47 Andy McCall ↶ 1351
        with_retries(&FETCH_WAITS, || repo.fetch("origin").map(|_| ()).map_err(|e| anyhow::anyhow!("fetch {clone_url}: {e}")))?;
e0918b88 Andy McCall 1352
        return Ok(repo);
1353
    }
ed4aef8b Andy McCall ↶ 1354
    // First job for this repository: clone with the job's token, which goes
1355
    // through the process environment, so one clone at a time.
1356
    let _clone = CLONE.lock().unwrap_or_else(|p| p.into_inner());
c23d5191 Andy McCall ↶ 1357
    std::env::set_var("OXY_TOKEN", token);
e0918b88 Andy McCall 1358
    if let Some(ca) = &cfg.ca {
1359
        std::env::set_var("OXY_CA", ca);
1360
    }
f53e6d47 Andy McCall ↶ 1361
    let cloned = with_retries(&FETCH_WAITS, || {
1362
        let _ = std::fs::remove_dir_all(&dir);
1363
        Repo::clone(clone_url, &dir).map_err(|e| anyhow::anyhow!("{e}"))
1364
    });
e0918b88 Andy McCall 1365
    std::env::remove_var("OXY_TOKEN");
1366
    std::env::remove_var("OXY_CA");
1367
    let mut repo = cloned.map_err(|e| {
1368
        let _ = std::fs::remove_dir_all(&dir);
c23d5191 Andy McCall ↶ 1369
        anyhow::anyhow!("clone {}: {e}", clone_url)
e0918b88 Andy McCall 1370
    })?;
1371
    set_remote(&mut repo)?;
1372
    Ok(repo)
bb643c25 Andy McCall ↶ 1373
}
1374
1375
#[cfg(test)]
1376
mod tests {
46fe2c81 Andy McCall ↶ 1377
1378
    #[test]
1379
    fn an_input_is_placed_only_when_it_is_what_the_receipt_names() {
1380
        let dir = tempfile::tempdir().unwrap();
1381
        let bytes = b"the reviewed plan";
1382
        let blob = Repo::blob_ref(bytes).to_hex();
1383
        let input = |path: &str, blob: &str| flow_core::api::ArtifactInput {
1384
            artifact: "tfplan".into(),
1385
            from: "plan".into(),
1386
            path: path.into(),
1387
            blob: blob.into(),
1388
        };
1389
        let got = super::place_input(dir.path(), &input("/src/plans/tfplan", &blob), bytes).unwrap();
1390
        assert_eq!(hex::encode(got), blob);
1391
        assert_eq!(std::fs::read(dir.path().join("plans/tfplan")).unwrap(), bytes);
1392
        let wrong = super::place_input(dir.path(), &input("/src/other", &"0".repeat(64)), bytes).unwrap_err();
1393
        assert!(format!("{wrong:#}").contains("not what plan's receipt names"), "{wrong:#}");
1394
        assert!(!dir.path().join("other").exists(), "nothing written when it does not match");
1395
        for bad in ["/etc/passwd", "/src/../x", "/src/.oxy/x", "/src/"] {
1396
            assert!(super::place_input(dir.path(), &input(bad, &blob), bytes).is_err(), "{bad}");
1397
        }
1398
    }
1399
bb643c25 Andy McCall ↶ 1400
    use super::*;
b11e30f5 Andy McCall ↶ 1401
1402
    #[test]
1403
    fn a_runner_names_what_stops_a_sandbox() {
1404
        let dir = tempfile::tempdir().unwrap();
1405
        let home = Home::locate(Some(dir.path())).unwrap();
1406
        let bytes = b"not really ext4";
1407
        let hash = blake3::hash(bytes).to_hex().to_string();
1408
        let mut sb: flow_core::Sandbox = serde_json::from_value(serde_json::json!({
1409
            "name": "s", "runtime": "syscall", "rootfs": "ab".repeat(32), "memory_mib": 1024, "cpus": 1, "network": "isolated"
1410
        }))
1411
        .unwrap();
1412
        let problem = |sb: &flow_core::Sandbox, free| sandbox_problem(&home, sb, "x86_64", free);
1413
        assert_eq!(problem(&sb, None).unwrap(), "rootfs abababababab is not on this runner");
1414
        std::fs::write(home.rootfs(&hash), bytes).unwrap();
1415
        sb.rootfs = hash.clone();
1416
        assert_eq!(problem(&sb, Some(4096)), None);
1417
        assert_eq!(problem(&sb, Some(512)).unwrap(), "only 512 MiB of memory is free here; the sandbox needs 1024 MiB");
1418
        std::fs::write(home.image_manifest(&hash), r#"{"arch":"riscv64"}"#).unwrap();
1419
        assert_eq!(problem(&sb, None).unwrap(), format!("rootfs {} is for riscv64; this runner is x86_64", &hash[..12]));
1420
        sb.arch = Some("aarch64".into());
1421
        assert_eq!(problem(&sb, None).unwrap(), "the sandbox needs aarch64; this runner is x86_64");
1422
        sb.arch = None;
1423
        std::fs::remove_file(home.image_manifest(&hash)).unwrap();
1424
        std::fs::write(home.rootfs(&hash), b"changed").unwrap();
1425
        assert!(problem(&sb, None).unwrap().contains("does not verify"));
1426
    }
f53e6d47 Andy McCall ↶ 1427
1428
    #[test]
1429
    fn transient_network_errors_are_tried_again_and_others_are_not() {
1430
        assert!(transient("fetch x: Dns Failed: resolve dns name 'oxygenhub.io:443': Temporary failure in name resolution"));
1431
        assert!(transient("HTTP 503: the hub is restarting"));
1432
        assert!(!transient("HTTP 404: no such repository"));
1433
        let mut n = 0;
1434
        let got: Result<u32> = with_retries(&[Duration::ZERO, Duration::ZERO], || {
1435
            n += 1;
1436
            if n < 3 {
1437
                Err(anyhow::anyhow!("connection refused"))
1438
            } else {
1439
                Ok(7)
1440
            }
1441
        });
1442
        assert_eq!((got.unwrap(), n), (7, 3), "two retries, then success");
1443
        let mut m = 0;
1444
        let got: Result<u32> = with_retries(&[Duration::ZERO; 4], || {
1445
            m += 1;
1446
            Err(anyhow::anyhow!("HTTP 403: forbidden"))
1447
        });
1448
        assert!(got.is_err());
1449
        assert_eq!(m, 1, "a refusal is not tried again");
1450
        let mut k = 0;
1451
        let got: Result<u32> = with_retries(&[Duration::ZERO; 2], || {
1452
            k += 1;
1453
            Err(anyhow::anyhow!("timed out"))
1454
        });
1455
        assert!(got.is_err());
1456
        assert_eq!(k, 3, "gives up after the last wait");
1457
    }
1b2229da Andy McCall ↶ 1458
1459
    /// A hub that answers each request with the next of `codes`, counting them.
1460
    fn fake_hub(codes: Vec<u16>) -> (String, std::sync::Arc<std::sync::atomic::AtomicUsize>) {
89171fca Andy McCall ↶ 1461
        fake_hub_on(std::net::TcpListener::bind("127.0.0.1:0").unwrap(), codes)
1462
    }
1463
1464
    /// A hub at `listener` answering each request with the next of `codes`.
1465
    fn fake_hub_on(listener: std::net::TcpListener, codes: Vec<u16>) -> (String, std::sync::Arc<std::sync::atomic::AtomicUsize>) {
1b2229da Andy McCall ↶ 1466
        use std::io::{Read, Write};
1467
        let addr = listener.local_addr().unwrap();
1468
        let seen = std::sync::Arc::new(std::sync::atomic::AtomicUsize::new(0));
1469
        let count = seen.clone();
1470
        std::thread::spawn(move || {
1471
            for code in codes {
1472
                let (mut s, _) = listener.accept().unwrap();
1473
                let mut buf = [0u8; 8192];
1474
                let _ = s.read(&mut buf);
1475
                count.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
1476
                let reason = if code == 204 { "No Content" } else { "Error" };
1477
                let _ = write!(s, "HTTP/1.1 {code} {reason}\r\nContent-Length: 0\r\nConnection: close\r\n\r\n");
1478
            }
1479
        });
1480
        (format!("http://{addr}"), seen)
f98a8f78 Andy McCall ↶ 1481
    }
1482
1483
    /// A hub that answers one request with `body` (status 200) and hands
1484
    /// back what it was sent.
1485
    fn fake_json_hub(body: &'static str) -> (String, std::sync::mpsc::Receiver<String>) {
1486
        use std::io::{Read, Write};
1487
        let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
1488
        let addr = listener.local_addr().unwrap();
1489
        let (tx, rx) = std::sync::mpsc::channel();
1490
        std::thread::spawn(move || {
1491
            let (mut s, _) = listener.accept().unwrap();
1492
            let mut req = Vec::new();
1493
            let mut buf = [0u8; 65536];
1494
            loop {
1495
                let n = s.read(&mut buf).unwrap_or(0);
1496
                if n == 0 {
1497
                    break;
1498
                }
1499
                req.extend_from_slice(&buf[..n]);
1500
                let text = String::from_utf8_lossy(&req);
1501
                if let Some(end) = text.find("\r\n\r\n") {
1502
                    let len = text[..end]
1503
                        .lines()
1504
                        .find_map(|l| {
1505
                            l.to_ascii_lowercase().strip_prefix("content-length:").map(|v| v.trim().parse::<usize>().unwrap_or(0))
1506
                        })
1507
                        .unwrap_or(0);
1508
                    if req.len() >= end + 4 + len {
1509
                        break;
1510
                    }
1511
                }
1512
            }
1513
            tx.send(String::from_utf8_lossy(&req).into_owned()).unwrap();
1514
            let _ = write!(
1515
                s,
1516
                "HTTP/1.1 200 OK\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{body}",
1517
                body.len()
1518
            );
1519
        });
1520
        (format!("http://{addr}"), rx)
1521
    }
1522
1523
    #[test]
1524
    fn registering_binds_the_key_and_keeps_the_credential_private() {
1525
        use std::os::unix::fs::PermissionsExt;
1526
        let dir = tempfile::tempdir().unwrap();
1527
        let home = Home::locate(Some(dir.path())).unwrap();
1528
        let (hub, sent) = fake_json_hub(r#"{"id":7,"name":"plex","credential":"flowrunner_secret"}"#);
1529
        let got = register(&home, &hub, " reg-token ", "plex", None, vec!["gpu".into()]).unwrap();
1530
        assert_eq!((got.id, got.name.as_str()), (7, "plex"));
1531
        let req = sent.recv().unwrap();
1532
        assert!(req.starts_with("POST /api/v1/flow/runners/register"), "{req}");
1533
        let body: Register = serde_json::from_str(&req[req.find("\r\n\r\n").unwrap() + 4..]).unwrap();
1534
        assert_eq!((body.token.as_str(), body.info.labels.clone()), ("reg-token", vec!["gpu".to_string()]));
1535
        let key = home.runner_key("plex").unwrap();
1536
        assert_eq!(body.identity, hex::encode(key.identity.encode()), "the runner's signing identity");
1537
        let path = dir.path().join(crate::home::RUNNER_TOML);
1538
        assert_eq!(std::fs::metadata(&path).unwrap().permissions().mode() & 0o777, 0o600);
1539
        // The runner then starts from runner.toml.
1540
        let again = Home::locate(Some(dir.path())).unwrap();
1541
        let cfg = again.config.runner.unwrap();
1542
        assert_eq!((cfg.hub.as_str(), cfg.token.as_str(), cfg.name.as_deref()), (hub.as_str(), "flowrunner_secret", Some("plex")));
1543
        assert_eq!(cfg.labels, ["gpu"]);
35f7a849 Andy McCall ↶ 1544
    }
1545
1546
    /// A hub that answers certify with a certificate `sign_as` signs for
1547
    /// `cert_key`, and publishes `published` as its key: two requests.
1548
    fn fake_certify_hub(
1549
        sign_as: (oxy_core::identity::Identity, oxy_core::identity::SecretKey),
1550
        cert_key: oxy_core::identity::Identity,
1551
        published: oxy_core::identity::Identity,
1552
    ) -> String {
1553
        use std::io::{Read, Write};
1554
        let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
1555
        let addr = listener.local_addr().unwrap();
1556
        std::thread::spawn(move || {
1557
            for _ in 0..2 {
1558
                let Ok((mut s, _)) = listener.accept() else { return };
1559
                let mut req = Vec::new();
1560
                let mut buf = [0u8; 65536];
1561
                loop {
1562
                    let n = s.read(&mut buf).unwrap_or(0);
1563
                    if n == 0 {
1564
                        break;
1565
                    }
1566
                    req.extend_from_slice(&buf[..n]);
1567
                    let text = String::from_utf8_lossy(&req);
1568
                    if let Some(end) = text.find("\r\n\r\n") {
1569
                        let len = text[..end]
1570
                            .lines()
1571
                            .find_map(|l| {
1572
                                l.to_ascii_lowercase().strip_prefix("content-length:").map(|v| v.trim().parse::<usize>().unwrap_or(0))
1573
                            })
1574
                            .unwrap_or(0);
1575
                        if req.len() >= end + 4 + len {
1576
                            break;
1577
                        }
1578
                    }
1579
                }
1580
                let line = String::from_utf8_lossy(&req).lines().next().unwrap_or("").to_string();
1581
                let body: Vec<u8> = if line.contains("/keyless/certify") {
1582
                    let cert = oxy_core::cert::SignedCertificate::sign(
1583
                        oxy_core::cert::Certificate {
1584
                            key: cert_key.clone(),
1585
                            issuer: sign_as.0.hash(),
1586
                            subject: "repo:andy/demo:bookmark:main".into(),
1587
                            claims: vec![],
1588
                            scope: oxy_core::identity::Scope::SEAL,
1589
                            not_before: 1,
1590
                            expires: 600_001,
fc2a6d18 Andy McCall ↶ 1591
                            grant: None,
35f7a849 Andy McCall ↶ 1592
                        },
1593
                        &sign_as.0,
1594
                        &sign_as.1,
1595
                    );
1596
                    serde_json::json!({ "certificate": oxy_core::dsse::base64(&cert.encode()) }).to_string().into_bytes()
1597
                } else {
1598
                    published.encode()
1599
                };
1600
                let _ = write!(s, "HTTP/1.1 200 OK\r\nContent-Length: {}\r\nConnection: close\r\n\r\n", body.len());
1601
                let _ = s.write_all(&body);
1602
            }
1603
        });
1604
        format!("http://{addr}")
1605
    }
1606
1607
    /// keyless (oxygenhub#241): the runner takes a certificate only when it
1608
    /// is for its fresh key and signed by the key the hub publishes.
1609
    #[test]
1610
    fn a_certificate_is_taken_only_for_this_key_from_the_hubs_key() {
1611
        use oxy_core::identity::SecretKey;
1612
        let hub_sk = SecretKey::generate();
1613
        let hub_id = hub_sk.identity("hub", "", 1);
1614
        let sk = SecretKey::generate();
1615
        let id = sk.identity("earth-1 job 7", "", 1);
1616
        let proof = sk.sign_challenge(&id.hash(), &oxy_core::cert::certify_challenge("flowjob_x")).unwrap();
1617
1618
        let base = fake_certify_hub((hub_id.clone(), hub_sk.clone()), id.clone(), hub_id.clone());
1619
        let (cert, issuer) = hub_at(base).certify("flowjob_x", &id, &proof).unwrap();
1620
        assert_eq!((cert.cert.key_id(), issuer.hash()), (id.hash(), hub_id.hash()));
1621
1622
        let mallory_sk = SecretKey::generate();
1623
        let mallory = mallory_sk.identity("mallory", "", 1);
1624
        let base = fake_certify_hub((mallory.clone(), mallory_sk), id.clone(), hub_id.clone());
1625
        let e = hub_at(base).certify("flowjob_x", &id, &proof).unwrap_err().to_string();
1626
        assert!(e.contains("not signed by the hub's published key"), "{e}");
1627
1628
        let other = SecretKey::generate().identity("other", "", 1);
1629
        let base = fake_certify_hub((hub_id.clone(), hub_sk), other, hub_id);
1630
        let e = hub_at(base).certify("flowjob_x", &id, &proof).unwrap_err().to_string();
1631
        assert!(e.contains("another key"), "{e}");
1b2229da Andy McCall ↶ 1632
    }
1633
1634
    fn hub_at(base: String) -> Hub {
1635
        Hub { base, token: "t".into(), agent: ureq::AgentBuilder::new().timeout(Duration::from_secs(5)).build() }
3007d8f0 Andy McCall ↶ 1636
    }
1637
1638
    /// oxygenhub#71: a job's result is offered until the hub takes it,
1639
    /// through server errors, and a refusal ends the trying at once.
1640
    #[test]
1641
    fn a_result_is_reported_until_the_hub_takes_it() {
8f211e20 Andy McCall ↶ 1642
        let f = Finish {
1643
            exit_code: Some(0),
1644
            duration_ms: 1,
1645
            receipt: None,
1646
            signed_receipt: None,
1647
            error: None,
1648
            peak_disk_mib: None,
1649
            peak_memory_mib: None,
1650
        };
3007d8f0 Andy McCall ↶ 1651
        let quick = Duration::from_millis(10);
1652
        let (base, seen) = fake_hub(vec![502, 503, 500, 500, 204]);
1653
        hub_at(base).finish_until_accepted(7, &f, Duration::from_secs(30), quick).unwrap();
1654
        assert_eq!(seen.load(std::sync::atomic::Ordering::SeqCst), 5, "kept trying through four server errors");
1655
        let (base, seen) = fake_hub(vec![409]);
1656
        assert!(hub_at(base).finish_until_accepted(7, &f, Duration::from_secs(30), quick).is_err());
1657
        assert_eq!(seen.load(std::sync::atomic::Ordering::SeqCst), 1, "a refusal is final");
1b2229da Andy McCall ↶ 1658
    }
1659
1660
    #[test]
1661
    fn server_errors_are_tried_again_and_client_errors_are_not() {
1662
        let quick = [Duration::from_millis(10); 3];
1663
        let (base, seen) = fake_hub(vec![500, 503, 204]);
1664
        let r = hub_at(base).post_with("/flow/jobs/1/log", &serde_json::json!({}), &quick).unwrap();
1665
        assert!(r.is_none());
1666
        assert_eq!(seen.load(std::sync::atomic::Ordering::SeqCst), 3, "two retries, then accepted");
1667
1668
        let (base, seen) = fake_hub(vec![500, 500, 500, 500]);
1669
        let e = hub_at(base).post_with("/flow/claim", &serde_json::json!({}), &quick).unwrap_err().to_string();
1670
        assert!(e.contains("HTTP 500"), "{e}");
1671
        assert_eq!(seen.load(std::sync::atomic::Ordering::SeqCst), 4, "gives up after the last delay");
1672
1673
        let (base, seen) = fake_hub(vec![401]);
1674
        assert!(hub_at(base).post_with("/flow/claim", &serde_json::json!({}), &quick).is_err());
1675
        assert_eq!(seen.load(std::sync::atomic::Ordering::SeqCst), 1, "a refusal is final");
280ef951 Andy McCall ↶ 1676
    }
1677
1678
    /// oxygenflow#32: a quiet job asks the hub every few seconds whether
1679
    /// it still runs; a 409 marks it cancelled, and nothing more is sent.
1680
    #[test]
1681
    fn a_quiet_job_learns_that_its_run_was_cancelled() {
1682
        use microvm::Sink;
1683
        let n = |seen: &std::sync::Arc<std::sync::atomic::AtomicUsize>| seen.load(std::sync::atomic::Ordering::SeqCst);
1684
        let quiet = Instant::now() - HEARTBEAT - Duration::from_secs(1);
1685
        let (base, seen) = fake_hub(vec![204]);
1686
        let hub = hub_at(base);
1687
        let mut sink = LogSink { hub: &hub, job: 1, buf: Vec::new(), last: quiet, gone: false };
1688
        assert!(!sink.cancelled());
1689
        assert!(!sink.cancelled(), "asked again only after the heartbeat");
1690
        assert_eq!(n(&seen), 1);
1691
1692
        let (base, seen) = fake_hub(vec![409]);
1693
        let hub = hub_at(base);
1694
        let mut sink = LogSink { hub: &hub, job: 1, buf: Vec::new(), last: quiet, gone: false };
1695
        assert!(sink.cancelled());
1696
        sink.record(Record { t: 0, stream: "out".into(), text: "late".into() });
1697
        sink.flush();
1698
        assert!(sink.cancelled());
1699
        assert_eq!(n(&seen), 1, "nothing is sent for a cancelled job");
89171fca Andy McCall ↶ 1700
    }
1701
1702
    /// oxygenflow#49: a hub that is away for a while (a deploy restarting
1703
    /// it) costs a job's uploads a wait, not the upload, and costs its log
1704
    /// no lines.
1705
    #[test]
1706
    fn a_job_outlasts_a_hub_restart() {
1707
        let n = |seen: &std::sync::Arc<std::sync::atomic::AtomicUsize>| seen.load(std::sync::atomic::Ordering::SeqCst);
1708
        // A port nobody listens on yet: the hub is restarting.
1709
        let port = std::net::TcpListener::bind("127.0.0.1:0").unwrap().local_addr().unwrap().port();
1710
        let base = format!("http://127.0.0.1:{port}");
1711
        let hub = hub_at(base.clone());
1712
1713
        // Log lines sent while it is away are kept, and go when it is back.
1714
        let mut sink = LogSink { hub: &hub, job: 1, buf: Vec::new(), last: Instant::now(), gone: false };
1715
        for i in 0..450 {
1716
            sink.buf.push(Record { t: i, stream: "out".into(), text: format!("line {i}") });
1717
        }
1718
        sink.send();
1719
        assert_eq!(sink.buf.len(), 450, "nothing lost while the hub is away");
1720
        let (_, seen) = fake_hub_on(std::net::TcpListener::bind(("127.0.0.1", port)).unwrap(), vec![204, 204, 204]);
1721
        sink.send();
1722
        assert!(sink.buf.is_empty() && !sink.gone);
1723
        assert_eq!(n(&seen), 3, "in batches of 200: 200, 200 and 50");
1724
1725
        // An upload waits for the hub to come back, through refused
1726
        // connections and server errors alike.
1727
        let port = std::net::TcpListener::bind("127.0.0.1:0").unwrap().local_addr().unwrap().port();
1728
        let url = format!("http://127.0.0.1:{port}/x");
1729
        let agent = ureq::AgentBuilder::new().timeout(Duration::from_secs(5)).build();
1730
        let later = std::thread::spawn(move || {
1731
            std::thread::sleep(Duration::from_millis(150));
1732
            fake_hub_on(std::net::TcpListener::bind(("127.0.0.1", port)).unwrap(), vec![502, 204])
1733
        });
1734
        let quick = [Duration::from_millis(50); 20];
1735
        let r = retrying(&url, &quick, true, || agent.post(&url).send_string("{}").map_err(Box::new)).unwrap();
1736
        assert_eq!(r.status(), 204);
1737
        assert_eq!(n(&later.join().unwrap().1), 2, "a 502 from the proxy, then the hub");
1738
        // Without `connection`, a hub that cannot be reached ends it at once.
1739
        let port = std::net::TcpListener::bind("127.0.0.1:0").unwrap().local_addr().unwrap().port();
1740
        let url = format!("http://127.0.0.1:{port}/x");
1741
        assert!(retrying(&url, &quick, false, || agent.post(&url).send_string("{}").map_err(Box::new)).is_err());
1742
        assert!(PATIENT_DELAYS.iter().sum::<Duration>() >= Duration::from_secs(180), "longer than a hub takes to restart");
1743
    }
1744
1745
    /// oxygenflow#50: the first stop drains (the second, not called here,
1746
    /// exits at once).
1747
    #[test]
1748
    fn a_stop_drains_the_runner() {
1749
        assert!(!stopping());
1750
        on_stop(libc::SIGTERM);
1751
        assert!(stopping(), "told to stop, it claims nothing more");
1752
    }
1753
1754
    /// Lines kept for a hub that stays away are bounded, saying how many went.
1755
    #[test]
1756
    fn unsent_log_lines_are_bounded() {
1757
        let port = std::net::TcpListener::bind("127.0.0.1:0").unwrap().local_addr().unwrap().port();
1758
        let hub = hub_at(format!("http://127.0.0.1:{port}"));
1759
        let mut sink = LogSink { hub: &hub, job: 1, buf: Vec::new(), last: Instant::now(), gone: false };
1760
        sink.buf = (0..MAX_UNSENT as u64 + 10).map(|i| Record { t: i, stream: "out".into(), text: String::new() }).collect();
1761
        sink.send();
1762
        assert_eq!(sink.buf.len(), MAX_UNSENT + 1);
1763
        assert_eq!(sink.buf[0].text, "(10 log lines lost while the hub could not be reached)");
1764
        assert_eq!(sink.buf[1].t, 10, "the oldest go first");
1b2229da Andy McCall ↶ 1765
    }
bb643c25 Andy McCall ↶ 1766
1767
    #[test]
1768
    fn the_budget_admits_jobs_that_fit() {
1769
        let b = Budget { max_jobs: 3, memory_mib: Some(24_576), cpus: Some(8) };
1770
        let used = |jobs, memory_mib, cpus| Used { jobs, memory_mib, cpus };
1771
        assert_eq!(b.room(used(0, 0, 0)), Some((None, None)), "a lone job may take everything");
1772
        assert_eq!(b.room(used(1, 8192, 4)), Some((Some(16_384), Some(4))));
1773
        assert_eq!(b.room(used(2, 16_384, 8)), None, "no vCPU left");
1774
        assert_eq!(b.room(used(3, 1024, 1)), None, "at max_jobs");
1775
        let one = Budget { max_jobs: 1, memory_mib: None, cpus: None };
1776
        assert_eq!(one.room(used(0, 0, 0)), Some((None, None)));
1777
        assert_eq!(one.room(used(1, 0, 0)), None, "the default runs one job at a time");
1778
        let open = Budget { max_jobs: 2, memory_mib: None, cpus: None };
1779
        assert_eq!(open.room(used(1, 8192, 4)), Some((None, None)), "no limits configured");
1780
    }
e0918b88 Andy McCall 1781
}