OXYGENHUB
# 3007d8f011fa oxygenflow / crates / flow / src / runner.rs
30.6 KiB · Rust · last changed A job's result is kept until the hub has it (refs andymccall/oxygenhub#71) 1 month ago source blame history raw
1
//! `flow runner` (docs/m0.md §5): claim a job from OxygenHub, fetch the
2
//! repository into a cache with the job's token, write the state into a
3
//! workspace, run it in its tier, stream the log, report the receipt.
4
//! One job at a time.
5
6
use crate::home::{Home, RunnerConfig, RunnerKey};
7
use crate::{microvm, workspace};
8
use anyhow::{bail, Context, Result};
9
use flow_core::api::{Claim, ClaimRequest, Finish, LogBatch, Record, Register, Registered, RunnerInfo, MAX_RECORD_TEXT};
10
use flow_core::{scope_tree_hash, Receipt};
11
use oxy_core::hash::ChangeHash;
12
use oxy_core::repo::Repo;
13
use std::path::PathBuf;
14
use std::time::{Duration, Instant};
15
16
pub struct Hub {
17
    base: String,
18
    token: String,
19
    agent: ureq::Agent,
20
}
21
22
impl Hub {
23
    pub fn new(cfg: &RunnerConfig) -> Result<Hub> {
24
        let tls = oxy_core::protocol::tls_client_config(cfg.ca.as_deref()).map_err(|e| anyhow::anyhow!("{e}"))?;
25
        let agent = ureq::AgentBuilder::new().tls_config(tls).timeout(Duration::from_secs(60)).build();
26
        Ok(Hub { base: cfg.hub.trim_end_matches('/').to_string(), token: cfg.token.clone(), agent })
27
    }
28
29
    /// POST to the hub. A server error (5xx) means nothing was committed,
30
    /// so it is tried again after 1, 2 and 4 seconds before giving up: a
31
    /// busy hub costs a job a few seconds, not its log lines or its claim.
32
    fn post(&self, path: &str, body: &impl serde::Serialize) -> Result<Option<ureq::Response>> {
33
        self.post_with(path, body, &RETRY_DELAYS)
34
    }
35
36
    fn post_with(&self, path: &str, body: &impl serde::Serialize, delays: &[Duration]) -> Result<Option<ureq::Response>> {
37
        let url = format!("{}/api/v1{path}", self.base);
38
        let mut delays = delays.iter();
39
        loop {
40
            match self.agent.post(&url).set("Authorization", &format!("Bearer {}", self.token)).send_json(body) {
41
                Ok(r) if r.status() == 204 => return Ok(None),
42
                Ok(r) => return Ok(Some(r)),
43
                Err(ureq::Error::Status(code, r)) => {
44
                    let text = r.into_string().unwrap_or_default();
45
                    match delays.next() {
46
                        Some(d) if code >= 500 => std::thread::sleep(*d),
47
                        _ => bail!("{url}: HTTP {code}: {text}"),
48
                    }
49
                }
50
                Err(e) => bail!("{url}: {e}"),
51
            }
52
        }
53
    }
54
55
    pub fn claim(&self, req: &ClaimRequest) -> Result<Option<Claim>> {
56
        match self.post("/flow/claim", req)? {
57
            Some(r) => Ok(Some(r.into_json()?)),
58
            None => Ok(None),
59
        }
60
    }
61
62
    pub fn log(&self, job: i64, records: Vec<Record>) -> Result<()> {
63
        self.post(&format!("/flow/jobs/{job}/log"), &LogBatch { records })?;
64
        Ok(())
65
    }
66
67
    /// Upload artifact `name` of job `job` (spec §5.2); the hub keeps it as
68
    /// a blob of the job's repository and answers with its ObjectRef.
69
    pub fn artifact(&self, job: i64, name: &str, bytes: &[u8]) -> Result<String> {
70
        let url = format!("{}/api/v1/flow/jobs/{job}/artifacts/{name}", self.base);
71
        let mut delays = RETRY_DELAYS.iter();
72
        loop {
73
            let req = self
74
                .agent
75
                .post(&url)
76
                .timeout(Duration::from_secs(600))
77
                .set("Authorization", &format!("Bearer {}", self.token))
78
                .set("Content-Type", "application/octet-stream");
79
            match req.send_bytes(bytes) {
80
                Ok(r) => {
81
                    let v: serde_json::Value = r.into_json()?;
82
                    return v["blob"].as_str().map(String::from).context("the hub named no blob");
83
                }
84
                Err(ureq::Error::Status(code, r)) => {
85
                    let text = r.into_string().unwrap_or_default();
86
                    match delays.next() {
87
                        Some(d) if code >= 500 => std::thread::sleep(*d),
88
                        _ => bail!("{url}: HTTP {code}: {text}"),
89
                    }
90
                }
91
                Err(e) => bail!("{url}: {e}"),
92
            }
93
        }
94
    }
95
96
    /// Report a job's end until the hub has it (oxygenhub#71): while the hub
97
    /// cannot be reached or fails (5xx), try again after `first_wait`,
98
    /// doubling to a minute, for up to `patience`. A refusal (4xx: the job was ended
99
    /// already, say) is final. A result lost here leaves the job running
100
    /// on the hub until its time limit.
101
    pub fn finish_until_accepted(&self, job: i64, f: &Finish, patience: Duration, first_wait: Duration) -> Result<()> {
102
        let url = format!("{}/api/v1/flow/jobs/{job}/finish", self.base);
103
        let deadline = std::time::Instant::now() + patience;
104
        let mut wait = first_wait;
105
        loop {
106
            let why = match self.agent.post(&url).set("Authorization", &format!("Bearer {}", self.token)).send_json(f) {
107
                Ok(_) => return Ok(()),
108
                Err(ureq::Error::Status(code, r)) if code < 500 => {
109
                    bail!("{url}: HTTP {code}: {}", r.into_string().unwrap_or_default())
110
                }
111
                Err(ureq::Error::Status(code, _)) => format!("HTTP {code}"),
112
                Err(e) => e.to_string(),
113
            };
114
            if std::time::Instant::now() + wait > deadline {
115
                bail!("{url}: gave up after {} minutes: {why}", patience.as_secs() / 60);
116
            }
117
            eprintln!("job {job}: the hub did not take the result ({why}); trying again in {} s", wait.as_secs());
118
            std::thread::sleep(wait);
119
            wait = (wait * 2).min(Duration::from_secs(60));
120
        }
121
    }
122
}
123
124
/// How long a runner keeps trying to report a job's end.
125
const FINISH_PATIENCE: Duration = Duration::from_secs(2 * 3600);
126
127
/// Where a job's result waits until the hub has it, so a runner that
128
/// restarts still reports it.
129
fn pending_path(home: &Home, job: i64) -> PathBuf {
130
    home.root.join("pending").join(format!("{job}.json"))
131
}
132
133
/// Report `f`, keeping it on disk until the hub has it.
134
fn report_finish(home: &Home, hub: &Hub, job: i64, f: &Finish) {
135
    let path = pending_path(home, job);
136
    let kept = std::fs::create_dir_all(path.parent().unwrap())
137
        .and_then(|_| std::fs::write(&path, serde_json::to_vec(f).unwrap_or_default()))
138
        .is_ok();
139
    match hub.finish_until_accepted(job, f, FINISH_PATIENCE, Duration::from_secs(5)) {
140
        Ok(()) => {}
141
        Err(e) => eprintln!("job {job}: reporting failed: {e:#}"),
142
    }
143
    if kept {
144
        let _ = std::fs::remove_file(&path);
145
    }
146
}
147
148
/// Results a previous run of the runner could not report, to send again.
149
fn report_pending(home: &Home) -> Vec<(i64, Finish)> {
150
    let Ok(dir) = std::fs::read_dir(home.root.join("pending")) else {
151
        return Vec::new();
152
    };
153
    dir.filter_map(|e| {
154
        let p = e.ok()?.path();
155
        let job: i64 = p.file_stem()?.to_str()?.parse().ok()?;
156
        let f: Finish = serde_json::from_slice(&std::fs::read(&p).ok()?).ok()?;
157
        Some((job, f))
158
    })
159
    .collect()
160
}
161
162
/// `flow runner register`: exchange a one-time registration token from
163
/// the hub for this runner's credential, binding the runner's signing key,
164
/// and keep hub, credential and name in runner.toml.
165
pub fn register(home: &Home, hub: &str, token: &str, name: &str, ca: Option<PathBuf>, labels: Vec<String>) -> Result<Registered> {
166
    if home.config.runner.is_some() && !home.root.join(crate::home::RUNNER_TOML).is_file() {
167
        bail!("flow.toml already has a [runner] section; remove it to register this runner instead");
168
    }
169
    let key = home.runner_key(name)?;
170
    let hub = hub.trim_end_matches('/').to_string();
171
    let tls = oxy_core::protocol::tls_client_config(ca.as_deref()).map_err(|e| anyhow::anyhow!("{e}"))?;
172
    let agent = ureq::AgentBuilder::new().tls_config(tls).timeout(Duration::from_secs(60)).build();
173
    let req = Register {
174
        token: token.trim().to_string(),
175
        name: name.to_string(),
176
        identity: hex::encode(key.identity.encode()),
177
        info: RunnerInfo { version: env!("OXY_VERSION_LONG").into(), ..RunnerInfo::here(labels.clone(), 1, None, None) },
178
    };
179
    let url = format!("{hub}/api/v1/flow/runners/register");
180
    let got: Registered = match agent.post(&url).send_json(&req) {
181
        Ok(r) => r.into_json()?,
182
        Err(ureq::Error::Status(code, r)) => bail!("{url}: HTTP {code}: {}", r.into_string().unwrap_or_default()),
183
        Err(e) => bail!("{url}: {e}"),
184
    };
185
    let mut text = format!(
186
        "# Written by `flow runner register`; the credential is secret.\nhub = {hub:?}\ntoken = {:?}\nname = {:?}\n",
187
        got.credential, got.name
188
    );
189
    if let Some(ca) = &ca {
190
        text.push_str(&format!("ca = {:?}\n", ca.display().to_string()));
191
    }
192
    if !labels.is_empty() {
193
        text.push_str(&format!("labels = {labels:?}\n"));
194
    }
195
    let path = home.root.join(crate::home::RUNNER_TOML);
196
    {
197
        use std::io::Write;
198
        use std::os::unix::fs::OpenOptionsExt;
199
        let tmp = path.with_extension("toml.tmp");
200
        let mut f = std::fs::OpenOptions::new().write(true).create(true).truncate(true).mode(0o600).open(&tmp)?;
201
        f.write_all(text.as_bytes())?;
202
        f.sync_all()?;
203
        std::fs::rename(&tmp, &path)?;
204
    }
205
    Ok(got)
206
}
207
208
/// Waits before trying a hub request again after a server error.
209
const RETRY_DELAYS: [Duration; 3] = [Duration::from_secs(1), Duration::from_secs(2), Duration::from_secs(4)];
210
211
/// What the runner may run at once (flow.toml `[runner]`): at most
212
/// `max_jobs` jobs, whose sandboxes together fit `memory_mib` and `cpus`.
213
#[derive(Debug, Default, PartialEq, Eq)]
214
pub struct Budget {
215
    pub max_jobs: usize,
216
    pub memory_mib: Option<u32>,
217
    pub cpus: Option<u32>,
218
}
219
220
/// What is in use now.
221
#[derive(Debug, Default, Clone, Copy, PartialEq, Eq)]
222
pub struct Used {
223
    pub jobs: usize,
224
    pub memory_mib: u32,
225
    pub cpus: u32,
226
}
227
228
impl Budget {
229
    pub fn of(cfg: &RunnerConfig) -> Budget {
230
        Budget { max_jobs: cfg.max_jobs.unwrap_or(1).max(1), memory_mib: cfg.memory_mib, cpus: cfg.cpus }
231
    }
232
233
    /// The room to ask the hub for, or `None` when no job more can start.
234
    /// A lone job may use the whole budget even if it asks for more, so a
235
    /// large sandbox is never starved.
236
    pub fn room(&self, used: Used) -> Option<(Option<u32>, Option<u32>)> {
237
        if used.jobs >= self.max_jobs {
238
            return None;
239
        }
240
        if used.jobs == 0 {
241
            return Some((None, None));
242
        }
243
        let mem = self.memory_mib.map(|m| m.saturating_sub(used.memory_mib));
244
        let cpus = self.cpus.map(|c| c.saturating_sub(used.cpus));
245
        if mem == Some(0) || cpus == Some(0) {
246
            return None;
247
        }
248
        Some((mem, cpus))
249
    }
250
}
251
252
pub fn serve(home: &Home) -> Result<()> {
253
    let cfg = home.config.runner.clone().context("flow.toml has no [runner] section")?;
254
    let hub = Hub::new(&cfg)?;
255
    let name = cfg.name.clone().unwrap_or_else(|| "flow".into());
256
    let budget = Budget::of(&cfg);
257
    let key = home.runner_key(&name)?;
258
    eprintln!(
259
        "flow runner {name}: polling {} (up to {} jobs at once), signing receipts as {}",
260
        cfg.hub,
261
        budget.max_jobs,
262
        key.identity.hash().to_hex()
263
    );
264
    let used = std::sync::Mutex::new(Used::default());
265
    let mut idle = Duration::from_secs(2);
266
    let pending = report_pending(home);
267
    std::thread::scope(|scope| {
268
        for (job, f) in pending {
269
            let hub = &hub;
270
            scope.spawn(move || {
271
                eprintln!("job {job}: reporting the result kept from before the restart");
272
                report_finish(home, hub, job, &f);
273
            });
274
        }
275
        loop {
276
            let room = budget.room(*used.lock().unwrap());
277
            let Some((free_memory_mib, free_cpus)) = room else {
278
                std::thread::sleep(Duration::from_millis(500));
279
                continue;
280
            };
281
            let req = ClaimRequest {
282
                runner: name.clone(),
283
                runtimes: vec!["microvm".into()],
284
                free_memory_mib,
285
                free_cpus,
286
                info: Some(RunnerInfo {
287
                    version: env!("OXY_VERSION_LONG").into(),
288
                    ..RunnerInfo::here(cfg.labels.clone(), budget.max_jobs as u32, cfg.memory_mib, cfg.cpus)
289
                }),
290
            };
291
            match hub.claim(&req) {
292
                Ok(Some(claim)) => {
293
                    idle = Duration::from_secs(2);
294
                    let (mem, cpus) = (claim.sandbox.memory_mib, claim.sandbox.cpus);
295
                    {
296
                        let mut u = used.lock().unwrap();
297
                        u.jobs += 1;
298
                        u.memory_mib += mem;
299
                        u.cpus += cpus;
300
                    }
301
                    let (home, hub, cfg, used, key) = (home, &hub, &cfg, &used, &key);
302
                    scope.spawn(move || {
303
                        let id = claim.job_id;
304
                        eprintln!(
305
                            "job {id}: {} {} on {}",
306
                            claim.repo,
307
                            claim.job.name,
308
                            claim.heads.first().map(|h| &h[..12]).unwrap_or("-")
309
                        );
310
                        let finish = run_claim(home, hub, cfg, key, &claim).unwrap_or_else(|e| Finish {
311
                            exit_code: None,
312
                            duration_ms: 0,
313
                            receipt: None,
314
                            signed_receipt: None,
315
                            error: Some(format!("{e:#}")),
316
                        });
317
                        eprintln!(
318
                            "job {id}: exit {:?}{}",
319
                            finish.exit_code,
320
                            finish.error.as_deref().map(|e| format!(" ({e})")).unwrap_or_default()
321
                        );
322
                        report_finish(home, hub, id, &finish);
323
                        let mut u = used.lock().unwrap();
324
                        u.jobs -= 1;
325
                        u.memory_mib -= mem;
326
                        u.cpus -= cpus;
327
                    });
328
                }
329
                Ok(None) => std::thread::sleep(idle),
330
                Err(e) => {
331
                    eprintln!("claim: {e:#}");
332
                    std::thread::sleep(idle);
333
                    idle = (idle * 2).min(Duration::from_secs(60));
334
                }
335
            }
336
        }
337
    })
338
}
339
340
/// Batches records to the hub every second (or every 200 lines).
341
struct LogSink<'a> {
342
    hub: &'a Hub,
343
    job: i64,
344
    buf: Vec<Record>,
345
    last: Instant,
346
}
347
348
impl LogSink<'_> {
349
    fn push(&mut self, mut r: Record) {
350
        if r.text.len() > MAX_RECORD_TEXT {
351
            let mut cut = MAX_RECORD_TEXT;
352
            while !r.text.is_char_boundary(cut) {
353
                cut -= 1;
354
            }
355
            r.text.truncate(cut);
356
        }
357
        self.buf.push(r);
358
        if self.buf.len() >= 200 || self.last.elapsed() >= Duration::from_secs(1) {
359
            self.flush();
360
        }
361
    }
362
363
    fn flush(&mut self) {
364
        if !self.buf.is_empty() {
365
            if let Err(e) = self.hub.log(self.job, std::mem::take(&mut self.buf)) {
366
                eprintln!("job {}: log: {e:#}", self.job);
367
            }
368
        }
369
        self.last = Instant::now();
370
    }
371
}
372
373
/// Held while a job's workspace is prepared (see `run_claim`).
374
static PREPARE: std::sync::Mutex<()> = std::sync::Mutex::new(());
375
376
fn run_claim(home: &Home, hub: &Hub, cfg: &RunnerConfig, key: &RunnerKey, claim: &Claim) -> Result<Finish> {
377
    let started = Instant::now();
378
    let mut sink = LogSink { hub, job: claim.job_id, buf: Vec::new(), last: Instant::now() };
379
    let note =
380
        |sink: &mut LogSink, text: String| sink.push(Record { t: started.elapsed().as_millis() as u64, stream: "flow".into(), text });
381
    let heads: Vec<ChangeHash> = claim.heads.iter().map(|h| ChangeHash::from_hex(h).context("bad head")).collect::<Result<_>>()?;
382
    note(&mut sink, format!("fetching {} for state {}", claim.repo, claim.heads.iter().map(|h| &h[..12]).collect::<Vec<_>>().join("+")));
383
    // Preparing a workspace (the cached repositories, the export, the
384
    // image) is one job at a time: fetches into a cached repository must not
385
    // overlap, and the first clone passes its token through the process
386
    // environment. Only the microVMs run side by side.
387
    let mut preparing = Some(PREPARE.lock().unwrap_or_else(|p| p.into_inner()));
388
    let repo = cached_repo(home, cfg, claim)?;
389
    let scratch = home.root.join("work").join(format!("job-{}", claim.job_id));
390
    let _ = std::fs::remove_dir_all(&scratch);
391
    std::fs::create_dir_all(scratch.join("tree"))?;
392
    let result = (|| -> Result<Finish> {
393
        let mut files = workspace::export_state(&repo, &heads, &scratch.join("tree"))?;
394
        // Pinned subrepos (Oxygen spec §7.8), at their paths, as part of the
395
        // workspace and of the scope hash.
396
        for sub in &claim.subrepos {
397
            if sub.path.split('/').any(|p| p.is_empty() || p == "." || p == ".." || p == ".oxy") {
398
                bail!("subrepo path {:?} is not a clean relative path", sub.path);
399
            }
400
            note(
401
                &mut sink,
402
                format!(
403
                    "fetching subrepo {} at {} for {}",
404
                    sub.repo,
405
                    sub.heads.iter().map(|h| &h[..12]).collect::<Vec<_>>().join("+"),
406
                    sub.path
407
                ),
408
            );
409
            let sub_repo = cached_repo_at(home, cfg, &sub.repo, &sub.clone_url, &claim.token)?;
410
            let sub_heads: Vec<ChangeHash> =
411
                sub.heads.iter().map(|h| ChangeHash::from_hex(h).context("bad subrepo head")).collect::<Result<_>>()?;
412
            let dir = scratch.join("tree").join(&sub.path);
413
            std::fs::create_dir_all(&dir)?;
414
            let sub_files = workspace::export_state(&sub_repo, &sub_heads, &dir)?;
415
            files.extend(sub_files.into_iter().map(|(p, h)| (format!("{}/{p}", sub.path), h)));
416
        }
417
        let scope_hash = scope_tree_hash(&claim.job.scope, files.iter().map(|(p, h)| (p.as_str(), *h)));
418
        workspace::image(&scratch.join("tree"), &scratch.join("workspace.ext4"))?;
419
        std::fs::remove_dir_all(scratch.join("tree"))?;
420
        preparing.take();
421
        note(
422
            &mut sink,
423
            format!(
424
                "booting a microVM: {} vCPU, {} MiB, rootfs {}",
425
                claim.sandbox.cpus,
426
                claim.sandbox.memory_mib,
427
                &claim.sandbox.rootfs[..12]
428
            ),
429
        );
430
        let job = claim.job.in_sandbox(&claim.sandbox).with_flow_env(&claim.flow_env());
431
        let outcome = microvm::run(
432
            home,
433
            &claim.sandbox,
434
            &job,
435
            &scratch.join("workspace.ext4"),
436
            &scratch,
437
            Duration::from_secs(claim.timeout_s),
438
            &mut |r| sink.push(r),
439
        )?;
440
        // A passing job's artifacts, read from its disks and uploaded; a
441
        // declared artifact that cannot be kept fails the job.
442
        let mut outputs = vec![];
443
        let mut output_error = None;
444
        if outcome.exit_code == Some(0) {
445
            for o in &claim.job.outputs {
446
                let (image, inner) = crate::outputs::locate(&claim.job, &scratch.join("workspace.ext4"), &scratch, &o.path);
447
                let kept = crate::outputs::read(&image, &inner, &scratch).and_then(|bytes| {
448
                    let blob = Repo::blob_ref(&bytes);
449
                    let named = hub.artifact(claim.job_id, &o.name, &bytes)?;
450
                    if named != blob.to_hex() {
451
                        bail!("the hub kept it as {named}, not {}", blob.to_hex());
452
                    }
453
                    note(&mut sink, format!("artifact {}: {} bytes, blob {}", o.name, bytes.len(), &named[..12]));
454
                    Ok(blob.0)
455
                });
456
                match kept {
457
                    Ok(b) => outputs.push(b),
458
                    Err(e) => {
459
                        output_error = Some(format!("artifact {}: {e:#}", o.name));
460
                        break;
461
                    }
462
                }
463
            }
464
        }
465
        if let Some(e) = &output_error {
466
            note(&mut sink, e.clone());
467
        }
468
        let receipt = outcome.exit_code.filter(|_| output_error.is_none()).map(|code| Receipt {
469
            job_name: claim.job.name.clone(),
470
            pipeline_hash: hex32(&claim.pipeline_hash),
471
            scope_tree_hash: scope_hash,
472
            inputs: vec![],
473
            environment: outcome.environment.hash(),
474
            outputs,
475
            exit_code: code as u32,
476
            duration_ms: outcome.duration_ms,
477
        });
478
        let signed_receipt = match &receipt {
479
            Some(r) => Some(hex::encode(sign_receipt(&repo, &heads, cfg, key, claim, r)?.encode())),
480
            None => None,
481
        };
482
        Ok(Finish {
483
            exit_code: outcome.exit_code,
484
            duration_ms: started.elapsed().as_millis() as u64,
485
            receipt,
486
            signed_receipt,
487
            error: output_error.or_else(|| outcome.timed_out.then(|| "stopped at the time limit".to_string())),
488
        })
489
    })();
490
    let _ = std::fs::remove_dir_all(&scratch);
491
    sink.flush();
492
    result
493
}
494
495
/// Bind `receipt` to the state of `heads` in `repo` and sign it as the
496
/// runner (Oxygen spec §14.6). The state is computed here, not taken from
497
/// the claim, so the runner vouches only for what it fetched.
498
fn sign_receipt(
499
    repo: &Repo,
500
    heads: &[ChangeHash],
501
    cfg: &RunnerConfig,
502
    key: &RunnerKey,
503
    claim: &Claim,
504
    receipt: &Receipt,
505
) -> Result<oxy_core::receipt::SignedReceipt> {
506
    let state = state_of(heads);
507
    let run = format!("{}/{}/flow/{}", cfg.hub.trim_end_matches('/'), claim.repo, claim.run_number);
508
    Ok(oxy_core::receipt::SignedReceipt::sign(receipt.to_oxy(), repo.id()?, state, &run, &key.identity, &key.secret))
509
}
510
511
/// The ObjectRef of the state whose heads are `heads` (Oxygen spec §10.1).
512
pub fn state_of(heads: &[ChangeHash]) -> oxy_core::hash::ObjectRef {
513
    use oxy_core::hash::{hash_object, ObjectType};
514
    hash_object(ObjectType::State, &oxy_core::objects::StateObject::new(heads.to_vec()).encode())
515
}
516
517
fn hex32(s: &str) -> [u8; 32] {
518
    let mut out = [0; 32];
519
    if let Ok(v) = hex::decode(s) {
520
        if v.len() == 32 {
521
            out.copy_from_slice(&v);
522
        }
523
    }
524
    out
525
}
526
527
/// The runner's copy of a repository, fetched up to date with the job's token.
528
fn cached_repo(home: &Home, cfg: &RunnerConfig, claim: &Claim) -> Result<Repo> {
529
    cached_repo_at(home, cfg, &claim.repo, &claim.clone_url, &claim.token)
530
}
531
532
/// The runner's copy of `repo`, cloned or fetched with `token`.
533
fn cached_repo_at(home: &Home, cfg: &RunnerConfig, repo_name: &str, clone_url: &str, token: &str) -> Result<Repo> {
534
    let dir: PathBuf = home.root.join("repos").join(repo_name.replace('/', "__"));
535
    let set_remote = |repo: &mut Repo| -> Result<()> {
536
        repo.config.set("remote.origin.url", clone_url).map_err(|e| anyhow::anyhow!("{e}"))?;
537
        repo.config.set("remote.origin.token", token).map_err(|e| anyhow::anyhow!("{e}"))?;
538
        if let Some(ca) = &cfg.ca {
539
            repo.config.set("remote.origin.ca", &ca.to_string_lossy()).map_err(|e| anyhow::anyhow!("{e}"))?;
540
        }
541
        repo.save_config().map_err(|e| anyhow::anyhow!("{e}"))
542
    };
543
    if dir.join(".oxy").is_dir() {
544
        let mut repo = Repo::open(&dir).map_err(|e| anyhow::anyhow!("{e}"))?;
545
        set_remote(&mut repo)?;
546
        repo.fetch("origin").map_err(|e| anyhow::anyhow!("fetch {clone_url}: {e}"))?;
547
        return Ok(repo);
548
    }
549
    // First job for this repository: clone with the job's token.
550
    std::env::set_var("OXY_TOKEN", token);
551
    if let Some(ca) = &cfg.ca {
552
        std::env::set_var("OXY_CA", ca);
553
    }
554
    let cloned = Repo::clone(clone_url, &dir);
555
    std::env::remove_var("OXY_TOKEN");
556
    std::env::remove_var("OXY_CA");
557
    let mut repo = cloned.map_err(|e| {
558
        let _ = std::fs::remove_dir_all(&dir);
559
        anyhow::anyhow!("clone {}: {e}", clone_url)
560
    })?;
561
    set_remote(&mut repo)?;
562
    Ok(repo)
563
}
564
565
#[cfg(test)]
566
mod tests {
567
    use super::*;
568
569
    /// A hub that answers each request with the next of `codes`, counting them.
570
    fn fake_hub(codes: Vec<u16>) -> (String, std::sync::Arc<std::sync::atomic::AtomicUsize>) {
571
        use std::io::{Read, Write};
572
        let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
573
        let addr = listener.local_addr().unwrap();
574
        let seen = std::sync::Arc::new(std::sync::atomic::AtomicUsize::new(0));
575
        let count = seen.clone();
576
        std::thread::spawn(move || {
577
            for code in codes {
578
                let (mut s, _) = listener.accept().unwrap();
579
                let mut buf = [0u8; 8192];
580
                let _ = s.read(&mut buf);
581
                count.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
582
                let reason = if code == 204 { "No Content" } else { "Error" };
583
                let _ = write!(s, "HTTP/1.1 {code} {reason}\r\nContent-Length: 0\r\nConnection: close\r\n\r\n");
584
            }
585
        });
586
        (format!("http://{addr}"), seen)
587
    }
588
589
    /// A hub that answers one request with `body` (status 200) and hands
590
    /// back what it was sent.
591
    fn fake_json_hub(body: &'static str) -> (String, std::sync::mpsc::Receiver<String>) {
592
        use std::io::{Read, Write};
593
        let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
594
        let addr = listener.local_addr().unwrap();
595
        let (tx, rx) = std::sync::mpsc::channel();
596
        std::thread::spawn(move || {
597
            let (mut s, _) = listener.accept().unwrap();
598
            let mut req = Vec::new();
599
            let mut buf = [0u8; 65536];
600
            loop {
601
                let n = s.read(&mut buf).unwrap_or(0);
602
                if n == 0 {
603
                    break;
604
                }
605
                req.extend_from_slice(&buf[..n]);
606
                let text = String::from_utf8_lossy(&req);
607
                if let Some(end) = text.find("\r\n\r\n") {
608
                    let len = text[..end]
609
                        .lines()
610
                        .find_map(|l| {
611
                            l.to_ascii_lowercase().strip_prefix("content-length:").map(|v| v.trim().parse::<usize>().unwrap_or(0))
612
                        })
613
                        .unwrap_or(0);
614
                    if req.len() >= end + 4 + len {
615
                        break;
616
                    }
617
                }
618
            }
619
            tx.send(String::from_utf8_lossy(&req).into_owned()).unwrap();
620
            let _ = write!(
621
                s,
622
                "HTTP/1.1 200 OK\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{body}",
623
                body.len()
624
            );
625
        });
626
        (format!("http://{addr}"), rx)
627
    }
628
629
    #[test]
630
    fn registering_binds_the_key_and_keeps_the_credential_private() {
631
        use std::os::unix::fs::PermissionsExt;
632
        let dir = tempfile::tempdir().unwrap();
633
        let home = Home::locate(Some(dir.path())).unwrap();
634
        let (hub, sent) = fake_json_hub(r#"{"id":7,"name":"plex","credential":"flowrunner_secret"}"#);
635
        let got = register(&home, &hub, " reg-token ", "plex", None, vec!["gpu".into()]).unwrap();
636
        assert_eq!((got.id, got.name.as_str()), (7, "plex"));
637
        let req = sent.recv().unwrap();
638
        assert!(req.starts_with("POST /api/v1/flow/runners/register"), "{req}");
639
        let body: Register = serde_json::from_str(&req[req.find("\r\n\r\n").unwrap() + 4..]).unwrap();
640
        assert_eq!((body.token.as_str(), body.info.labels.clone()), ("reg-token", vec!["gpu".to_string()]));
641
        let key = home.runner_key("plex").unwrap();
642
        assert_eq!(body.identity, hex::encode(key.identity.encode()), "the runner's signing identity");
643
        let path = dir.path().join(crate::home::RUNNER_TOML);
644
        assert_eq!(std::fs::metadata(&path).unwrap().permissions().mode() & 0o777, 0o600);
645
        // The runner then starts from runner.toml.
646
        let again = Home::locate(Some(dir.path())).unwrap();
647
        let cfg = again.config.runner.unwrap();
648
        assert_eq!((cfg.hub.as_str(), cfg.token.as_str(), cfg.name.as_deref()), (hub.as_str(), "flowrunner_secret", Some("plex")));
649
        assert_eq!(cfg.labels, ["gpu"]);
650
    }
651
652
    fn hub_at(base: String) -> Hub {
653
        Hub { base, token: "t".into(), agent: ureq::AgentBuilder::new().timeout(Duration::from_secs(5)).build() }
654
    }
655
656
    /// oxygenhub#71: a job's result is offered until the hub takes it,
657
    /// through server errors, and a refusal ends the trying at once.
658
    #[test]
659
    fn a_result_is_reported_until_the_hub_takes_it() {
660
        let f = Finish { exit_code: Some(0), duration_ms: 1, receipt: None, signed_receipt: None, error: None };
661
        let quick = Duration::from_millis(10);
662
        let (base, seen) = fake_hub(vec![502, 503, 500, 500, 204]);
663
        hub_at(base).finish_until_accepted(7, &f, Duration::from_secs(30), quick).unwrap();
664
        assert_eq!(seen.load(std::sync::atomic::Ordering::SeqCst), 5, "kept trying through four server errors");
665
        let (base, seen) = fake_hub(vec![409]);
666
        assert!(hub_at(base).finish_until_accepted(7, &f, Duration::from_secs(30), quick).is_err());
667
        assert_eq!(seen.load(std::sync::atomic::Ordering::SeqCst), 1, "a refusal is final");
668
    }
669
670
    #[test]
671
    fn server_errors_are_tried_again_and_client_errors_are_not() {
672
        let quick = [Duration::from_millis(10); 3];
673
        let (base, seen) = fake_hub(vec![500, 503, 204]);
674
        let r = hub_at(base).post_with("/flow/jobs/1/log", &serde_json::json!({}), &quick).unwrap();
675
        assert!(r.is_none());
676
        assert_eq!(seen.load(std::sync::atomic::Ordering::SeqCst), 3, "two retries, then accepted");
677
678
        let (base, seen) = fake_hub(vec![500, 500, 500, 500]);
679
        let e = hub_at(base).post_with("/flow/claim", &serde_json::json!({}), &quick).unwrap_err().to_string();
680
        assert!(e.contains("HTTP 500"), "{e}");
681
        assert_eq!(seen.load(std::sync::atomic::Ordering::SeqCst), 4, "gives up after the last delay");
682
683
        let (base, seen) = fake_hub(vec![401]);
684
        assert!(hub_at(base).post_with("/flow/claim", &serde_json::json!({}), &quick).is_err());
685
        assert_eq!(seen.load(std::sync::atomic::Ordering::SeqCst), 1, "a refusal is final");
686
    }
687
688
    #[test]
689
    fn the_budget_admits_jobs_that_fit() {
690
        let b = Budget { max_jobs: 3, memory_mib: Some(24_576), cpus: Some(8) };
691
        let used = |jobs, memory_mib, cpus| Used { jobs, memory_mib, cpus };
692
        assert_eq!(b.room(used(0, 0, 0)), Some((None, None)), "a lone job may take everything");
693
        assert_eq!(b.room(used(1, 8192, 4)), Some((Some(16_384), Some(4))));
694
        assert_eq!(b.room(used(2, 16_384, 8)), None, "no vCPU left");
695
        assert_eq!(b.room(used(3, 1024, 1)), None, "at max_jobs");
696
        let one = Budget { max_jobs: 1, memory_mib: None, cpus: None };
697
        assert_eq!(one.room(used(0, 0, 0)), Some((None, None)));
698
        assert_eq!(one.room(used(1, 0, 0)), None, "the default runs one job at a time");
699
        let open = Budget { max_jobs: 2, memory_mib: None, cpus: None };
700
        assert_eq!(open.room(used(1, 8192, 4)), Some((None, None)), "no limits configured");
701
    }
702
}