OXYGENHUB
# f2609cf795d8 oxygenflow / crates / flow / src / runner.rs
31.3 KiB · Rust · last changed A runner tells the hub which jobs it holds at each claim (refs 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
    // The jobs held now, told to the hub at each claim so it can end the
268
    // ones this runner lost: a job is held from its claim until its result
269
    // is reported.
270
    let held = std::sync::Mutex::new(std::collections::BTreeSet::<i64>::new());
271
    held.lock().unwrap().extend(pending.iter().map(|(job, _)| *job));
272
    std::thread::scope(|scope| {
273
        for (job, f) in pending {
274
            let (hub, held) = (&hub, &held);
275
            scope.spawn(move || {
276
                eprintln!("job {job}: reporting the result kept from before the restart");
277
                report_finish(home, hub, job, &f);
278
                held.lock().unwrap().remove(&job);
279
            });
280
        }
281
        loop {
282
            let room = budget.room(*used.lock().unwrap());
283
            let Some((free_memory_mib, free_cpus)) = room else {
284
                std::thread::sleep(Duration::from_millis(500));
285
                continue;
286
            };
287
            let req = ClaimRequest {
288
                runner: name.clone(),
289
                runtimes: vec!["microvm".into()],
290
                free_memory_mib,
291
                free_cpus,
292
                info: Some(RunnerInfo {
293
                    version: env!("OXY_VERSION_LONG").into(),
294
                    ..RunnerInfo::here(cfg.labels.clone(), budget.max_jobs as u32, cfg.memory_mib, cfg.cpus)
295
                }),
296
                // Read each time: an image imported while the runner runs counts.
297
                images: Some(home.images()),
298
                holding: Some(held.lock().unwrap().iter().copied().collect()),
299
            };
300
            match hub.claim(&req) {
301
                Ok(Some(claim)) => {
302
                    idle = Duration::from_secs(2);
303
                    let (mem, cpus) = (claim.sandbox.memory_mib, claim.sandbox.cpus);
304
                    {
305
                        let mut u = used.lock().unwrap();
306
                        u.jobs += 1;
307
                        u.memory_mib += mem;
308
                        u.cpus += cpus;
309
                    }
310
                    held.lock().unwrap().insert(claim.job_id);
311
                    let (home, hub, cfg, used, key, held) = (home, &hub, &cfg, &used, &key, &held);
312
                    scope.spawn(move || {
313
                        let id = claim.job_id;
314
                        eprintln!(
315
                            "job {id}: {} {} on {}",
316
                            claim.repo,
317
                            claim.job.name,
318
                            claim.heads.first().map(|h| &h[..12]).unwrap_or("-")
319
                        );
320
                        let finish = run_claim(home, hub, cfg, key, &claim).unwrap_or_else(|e| Finish {
321
                            exit_code: None,
322
                            duration_ms: 0,
323
                            receipt: None,
324
                            signed_receipt: None,
325
                            error: Some(format!("{e:#}")),
326
                        });
327
                        eprintln!(
328
                            "job {id}: exit {:?}{}",
329
                            finish.exit_code,
330
                            finish.error.as_deref().map(|e| format!(" ({e})")).unwrap_or_default()
331
                        );
332
                        report_finish(home, hub, id, &finish);
333
                        held.lock().unwrap().remove(&id);
334
                        let mut u = used.lock().unwrap();
335
                        u.jobs -= 1;
336
                        u.memory_mib -= mem;
337
                        u.cpus -= cpus;
338
                    });
339
                }
340
                Ok(None) => std::thread::sleep(idle),
341
                Err(e) => {
342
                    eprintln!("claim: {e:#}");
343
                    std::thread::sleep(idle);
344
                    idle = (idle * 2).min(Duration::from_secs(60));
345
                }
346
            }
347
        }
348
    })
349
}
350
351
/// Batches records to the hub every second (or every 200 lines).
352
struct LogSink<'a> {
353
    hub: &'a Hub,
354
    job: i64,
355
    buf: Vec<Record>,
356
    last: Instant,
357
}
358
359
impl LogSink<'_> {
360
    fn push(&mut self, mut r: Record) {
361
        if r.text.len() > MAX_RECORD_TEXT {
362
            let mut cut = MAX_RECORD_TEXT;
363
            while !r.text.is_char_boundary(cut) {
364
                cut -= 1;
365
            }
366
            r.text.truncate(cut);
367
        }
368
        self.buf.push(r);
369
        if self.buf.len() >= 200 || self.last.elapsed() >= Duration::from_secs(1) {
370
            self.flush();
371
        }
372
    }
373
374
    fn flush(&mut self) {
375
        if !self.buf.is_empty() {
376
            if let Err(e) = self.hub.log(self.job, std::mem::take(&mut self.buf)) {
377
                eprintln!("job {}: log: {e:#}", self.job);
378
            }
379
        }
380
        self.last = Instant::now();
381
    }
382
}
383
384
/// Held while a job's workspace is prepared (see `run_claim`).
385
static PREPARE: std::sync::Mutex<()> = std::sync::Mutex::new(());
386
387
fn run_claim(home: &Home, hub: &Hub, cfg: &RunnerConfig, key: &RunnerKey, claim: &Claim) -> Result<Finish> {
388
    let started = Instant::now();
389
    let mut sink = LogSink { hub, job: claim.job_id, buf: Vec::new(), last: Instant::now() };
390
    let note =
391
        |sink: &mut LogSink, text: String| sink.push(Record { t: started.elapsed().as_millis() as u64, stream: "flow".into(), text });
392
    let heads: Vec<ChangeHash> = claim.heads.iter().map(|h| ChangeHash::from_hex(h).context("bad head")).collect::<Result<_>>()?;
393
    note(&mut sink, format!("fetching {} for state {}", claim.repo, claim.heads.iter().map(|h| &h[..12]).collect::<Vec<_>>().join("+")));
394
    // Preparing a workspace (the cached repositories, the export, the
395
    // image) is one job at a time: fetches into a cached repository must not
396
    // overlap, and the first clone passes its token through the process
397
    // environment. Only the microVMs run side by side.
398
    let mut preparing = Some(PREPARE.lock().unwrap_or_else(|p| p.into_inner()));
399
    let repo = cached_repo(home, cfg, claim)?;
400
    let scratch = home.root.join("work").join(format!("job-{}", claim.job_id));
401
    let _ = std::fs::remove_dir_all(&scratch);
402
    std::fs::create_dir_all(scratch.join("tree"))?;
403
    let result = (|| -> Result<Finish> {
404
        let mut files = workspace::export_state(&repo, &heads, &scratch.join("tree"))?;
405
        // Pinned subrepos (Oxygen spec §7.8), at their paths, as part of the
406
        // workspace and of the scope hash.
407
        for sub in &claim.subrepos {
408
            if sub.path.split('/').any(|p| p.is_empty() || p == "." || p == ".." || p == ".oxy") {
409
                bail!("subrepo path {:?} is not a clean relative path", sub.path);
410
            }
411
            note(
412
                &mut sink,
413
                format!(
414
                    "fetching subrepo {} at {} for {}",
415
                    sub.repo,
416
                    sub.heads.iter().map(|h| &h[..12]).collect::<Vec<_>>().join("+"),
417
                    sub.path
418
                ),
419
            );
420
            let sub_repo = cached_repo_at(home, cfg, &sub.repo, &sub.clone_url, &claim.token)?;
421
            let sub_heads: Vec<ChangeHash> =
422
                sub.heads.iter().map(|h| ChangeHash::from_hex(h).context("bad subrepo head")).collect::<Result<_>>()?;
423
            let dir = scratch.join("tree").join(&sub.path);
424
            std::fs::create_dir_all(&dir)?;
425
            let sub_files = workspace::export_state(&sub_repo, &sub_heads, &dir)?;
426
            files.extend(sub_files.into_iter().map(|(p, h)| (format!("{}/{p}", sub.path), h)));
427
        }
428
        let scope_hash = scope_tree_hash(&claim.job.scope, files.iter().map(|(p, h)| (p.as_str(), *h)));
429
        workspace::image(&scratch.join("tree"), &scratch.join("workspace.ext4"))?;
430
        std::fs::remove_dir_all(scratch.join("tree"))?;
431
        preparing.take();
432
        note(
433
            &mut sink,
434
            format!(
435
                "booting a microVM: {} vCPU, {} MiB, rootfs {}",
436
                claim.sandbox.cpus,
437
                claim.sandbox.memory_mib,
438
                &claim.sandbox.rootfs[..12]
439
            ),
440
        );
441
        let job = claim.job.in_sandbox(&claim.sandbox).with_flow_env(&claim.flow_env());
442
        let outcome = microvm::run(
443
            home,
444
            &claim.sandbox,
445
            &job,
446
            &scratch.join("workspace.ext4"),
447
            &scratch,
448
            Duration::from_secs(claim.timeout_s),
449
            &mut |r| sink.push(r),
450
        )?;
451
        // A passing job's artifacts, read from its disks and uploaded; a
452
        // declared artifact that cannot be kept fails the job.
453
        let mut outputs = vec![];
454
        let mut output_error = None;
455
        if outcome.exit_code == Some(0) {
456
            for o in &claim.job.outputs {
457
                let (image, inner) = crate::outputs::locate(&claim.job, &scratch.join("workspace.ext4"), &scratch, &o.path);
458
                let kept = crate::outputs::read(&image, &inner, &scratch).and_then(|bytes| {
459
                    let blob = Repo::blob_ref(&bytes);
460
                    let named = hub.artifact(claim.job_id, &o.name, &bytes)?;
461
                    if named != blob.to_hex() {
462
                        bail!("the hub kept it as {named}, not {}", blob.to_hex());
463
                    }
464
                    note(&mut sink, format!("artifact {}: {} bytes, blob {}", o.name, bytes.len(), &named[..12]));
465
                    Ok(blob.0)
466
                });
467
                match kept {
468
                    Ok(b) => outputs.push(b),
469
                    Err(e) => {
470
                        output_error = Some(format!("artifact {}: {e:#}", o.name));
471
                        break;
472
                    }
473
                }
474
            }
475
        }
476
        if let Some(e) = &output_error {
477
            note(&mut sink, e.clone());
478
        }
479
        let receipt = outcome.exit_code.filter(|_| output_error.is_none()).map(|code| Receipt {
480
            job_name: claim.job.name.clone(),
481
            pipeline_hash: hex32(&claim.pipeline_hash),
482
            scope_tree_hash: scope_hash,
483
            inputs: vec![],
484
            environment: outcome.environment.hash(),
485
            outputs,
486
            exit_code: code as u32,
487
            duration_ms: outcome.duration_ms,
488
        });
489
        let signed_receipt = match &receipt {
490
            Some(r) => Some(hex::encode(sign_receipt(&repo, &heads, cfg, key, claim, r)?.encode())),
491
            None => None,
492
        };
493
        Ok(Finish {
494
            exit_code: outcome.exit_code,
495
            duration_ms: started.elapsed().as_millis() as u64,
496
            receipt,
497
            signed_receipt,
498
            error: output_error.or_else(|| outcome.timed_out.then(|| "stopped at the time limit".to_string())),
499
        })
500
    })();
501
    let _ = std::fs::remove_dir_all(&scratch);
502
    sink.flush();
503
    result
504
}
505
506
/// Bind `receipt` to the state of `heads` in `repo` and sign it as the
507
/// runner (Oxygen spec §14.6). The state is computed here, not taken from
508
/// the claim, so the runner vouches only for what it fetched.
509
fn sign_receipt(
510
    repo: &Repo,
511
    heads: &[ChangeHash],
512
    cfg: &RunnerConfig,
513
    key: &RunnerKey,
514
    claim: &Claim,
515
    receipt: &Receipt,
516
) -> Result<oxy_core::receipt::SignedReceipt> {
517
    let state = state_of(heads);
518
    let run = format!("{}/{}/flow/{}", cfg.hub.trim_end_matches('/'), claim.repo, claim.run_number);
519
    Ok(oxy_core::receipt::SignedReceipt::sign(receipt.to_oxy(), repo.id()?, state, &run, &key.identity, &key.secret))
520
}
521
522
/// The ObjectRef of the state whose heads are `heads` (Oxygen spec §10.1).
523
pub fn state_of(heads: &[ChangeHash]) -> oxy_core::hash::ObjectRef {
524
    use oxy_core::hash::{hash_object, ObjectType};
525
    hash_object(ObjectType::State, &oxy_core::objects::StateObject::new(heads.to_vec()).encode())
526
}
527
528
fn hex32(s: &str) -> [u8; 32] {
529
    let mut out = [0; 32];
530
    if let Ok(v) = hex::decode(s) {
531
        if v.len() == 32 {
532
            out.copy_from_slice(&v);
533
        }
534
    }
535
    out
536
}
537
538
/// The runner's copy of a repository, fetched up to date with the job's token.
539
fn cached_repo(home: &Home, cfg: &RunnerConfig, claim: &Claim) -> Result<Repo> {
540
    cached_repo_at(home, cfg, &claim.repo, &claim.clone_url, &claim.token)
541
}
542
543
/// The runner's copy of `repo`, cloned or fetched with `token`.
544
fn cached_repo_at(home: &Home, cfg: &RunnerConfig, repo_name: &str, clone_url: &str, token: &str) -> Result<Repo> {
545
    let dir: PathBuf = home.root.join("repos").join(repo_name.replace('/', "__"));
546
    let set_remote = |repo: &mut Repo| -> Result<()> {
547
        repo.config.set("remote.origin.url", clone_url).map_err(|e| anyhow::anyhow!("{e}"))?;
548
        repo.config.set("remote.origin.token", token).map_err(|e| anyhow::anyhow!("{e}"))?;
549
        if let Some(ca) = &cfg.ca {
550
            repo.config.set("remote.origin.ca", &ca.to_string_lossy()).map_err(|e| anyhow::anyhow!("{e}"))?;
551
        }
552
        repo.save_config().map_err(|e| anyhow::anyhow!("{e}"))
553
    };
554
    if dir.join(".oxy").is_dir() {
555
        let mut repo = Repo::open(&dir).map_err(|e| anyhow::anyhow!("{e}"))?;
556
        set_remote(&mut repo)?;
557
        repo.fetch("origin").map_err(|e| anyhow::anyhow!("fetch {clone_url}: {e}"))?;
558
        return Ok(repo);
559
    }
560
    // First job for this repository: clone with the job's token.
561
    std::env::set_var("OXY_TOKEN", token);
562
    if let Some(ca) = &cfg.ca {
563
        std::env::set_var("OXY_CA", ca);
564
    }
565
    let cloned = Repo::clone(clone_url, &dir);
566
    std::env::remove_var("OXY_TOKEN");
567
    std::env::remove_var("OXY_CA");
568
    let mut repo = cloned.map_err(|e| {
569
        let _ = std::fs::remove_dir_all(&dir);
570
        anyhow::anyhow!("clone {}: {e}", clone_url)
571
    })?;
572
    set_remote(&mut repo)?;
573
    Ok(repo)
574
}
575
576
#[cfg(test)]
577
mod tests {
578
    use super::*;
579
580
    /// A hub that answers each request with the next of `codes`, counting them.
581
    fn fake_hub(codes: Vec<u16>) -> (String, std::sync::Arc<std::sync::atomic::AtomicUsize>) {
582
        use std::io::{Read, Write};
583
        let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
584
        let addr = listener.local_addr().unwrap();
585
        let seen = std::sync::Arc::new(std::sync::atomic::AtomicUsize::new(0));
586
        let count = seen.clone();
587
        std::thread::spawn(move || {
588
            for code in codes {
589
                let (mut s, _) = listener.accept().unwrap();
590
                let mut buf = [0u8; 8192];
591
                let _ = s.read(&mut buf);
592
                count.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
593
                let reason = if code == 204 { "No Content" } else { "Error" };
594
                let _ = write!(s, "HTTP/1.1 {code} {reason}\r\nContent-Length: 0\r\nConnection: close\r\n\r\n");
595
            }
596
        });
597
        (format!("http://{addr}"), seen)
598
    }
599
600
    /// A hub that answers one request with `body` (status 200) and hands
601
    /// back what it was sent.
602
    fn fake_json_hub(body: &'static str) -> (String, std::sync::mpsc::Receiver<String>) {
603
        use std::io::{Read, Write};
604
        let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
605
        let addr = listener.local_addr().unwrap();
606
        let (tx, rx) = std::sync::mpsc::channel();
607
        std::thread::spawn(move || {
608
            let (mut s, _) = listener.accept().unwrap();
609
            let mut req = Vec::new();
610
            let mut buf = [0u8; 65536];
611
            loop {
612
                let n = s.read(&mut buf).unwrap_or(0);
613
                if n == 0 {
614
                    break;
615
                }
616
                req.extend_from_slice(&buf[..n]);
617
                let text = String::from_utf8_lossy(&req);
618
                if let Some(end) = text.find("\r\n\r\n") {
619
                    let len = text[..end]
620
                        .lines()
621
                        .find_map(|l| {
622
                            l.to_ascii_lowercase().strip_prefix("content-length:").map(|v| v.trim().parse::<usize>().unwrap_or(0))
623
                        })
624
                        .unwrap_or(0);
625
                    if req.len() >= end + 4 + len {
626
                        break;
627
                    }
628
                }
629
            }
630
            tx.send(String::from_utf8_lossy(&req).into_owned()).unwrap();
631
            let _ = write!(
632
                s,
633
                "HTTP/1.1 200 OK\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{body}",
634
                body.len()
635
            );
636
        });
637
        (format!("http://{addr}"), rx)
638
    }
639
640
    #[test]
641
    fn registering_binds_the_key_and_keeps_the_credential_private() {
642
        use std::os::unix::fs::PermissionsExt;
643
        let dir = tempfile::tempdir().unwrap();
644
        let home = Home::locate(Some(dir.path())).unwrap();
645
        let (hub, sent) = fake_json_hub(r#"{"id":7,"name":"plex","credential":"flowrunner_secret"}"#);
646
        let got = register(&home, &hub, " reg-token ", "plex", None, vec!["gpu".into()]).unwrap();
647
        assert_eq!((got.id, got.name.as_str()), (7, "plex"));
648
        let req = sent.recv().unwrap();
649
        assert!(req.starts_with("POST /api/v1/flow/runners/register"), "{req}");
650
        let body: Register = serde_json::from_str(&req[req.find("\r\n\r\n").unwrap() + 4..]).unwrap();
651
        assert_eq!((body.token.as_str(), body.info.labels.clone()), ("reg-token", vec!["gpu".to_string()]));
652
        let key = home.runner_key("plex").unwrap();
653
        assert_eq!(body.identity, hex::encode(key.identity.encode()), "the runner's signing identity");
654
        let path = dir.path().join(crate::home::RUNNER_TOML);
655
        assert_eq!(std::fs::metadata(&path).unwrap().permissions().mode() & 0o777, 0o600);
656
        // The runner then starts from runner.toml.
657
        let again = Home::locate(Some(dir.path())).unwrap();
658
        let cfg = again.config.runner.unwrap();
659
        assert_eq!((cfg.hub.as_str(), cfg.token.as_str(), cfg.name.as_deref()), (hub.as_str(), "flowrunner_secret", Some("plex")));
660
        assert_eq!(cfg.labels, ["gpu"]);
661
    }
662
663
    fn hub_at(base: String) -> Hub {
664
        Hub { base, token: "t".into(), agent: ureq::AgentBuilder::new().timeout(Duration::from_secs(5)).build() }
665
    }
666
667
    /// oxygenhub#71: a job's result is offered until the hub takes it,
668
    /// through server errors, and a refusal ends the trying at once.
669
    #[test]
670
    fn a_result_is_reported_until_the_hub_takes_it() {
671
        let f = Finish { exit_code: Some(0), duration_ms: 1, receipt: None, signed_receipt: None, error: None };
672
        let quick = Duration::from_millis(10);
673
        let (base, seen) = fake_hub(vec![502, 503, 500, 500, 204]);
674
        hub_at(base).finish_until_accepted(7, &f, Duration::from_secs(30), quick).unwrap();
675
        assert_eq!(seen.load(std::sync::atomic::Ordering::SeqCst), 5, "kept trying through four server errors");
676
        let (base, seen) = fake_hub(vec![409]);
677
        assert!(hub_at(base).finish_until_accepted(7, &f, Duration::from_secs(30), quick).is_err());
678
        assert_eq!(seen.load(std::sync::atomic::Ordering::SeqCst), 1, "a refusal is final");
679
    }
680
681
    #[test]
682
    fn server_errors_are_tried_again_and_client_errors_are_not() {
683
        let quick = [Duration::from_millis(10); 3];
684
        let (base, seen) = fake_hub(vec![500, 503, 204]);
685
        let r = hub_at(base).post_with("/flow/jobs/1/log", &serde_json::json!({}), &quick).unwrap();
686
        assert!(r.is_none());
687
        assert_eq!(seen.load(std::sync::atomic::Ordering::SeqCst), 3, "two retries, then accepted");
688
689
        let (base, seen) = fake_hub(vec![500, 500, 500, 500]);
690
        let e = hub_at(base).post_with("/flow/claim", &serde_json::json!({}), &quick).unwrap_err().to_string();
691
        assert!(e.contains("HTTP 500"), "{e}");
692
        assert_eq!(seen.load(std::sync::atomic::Ordering::SeqCst), 4, "gives up after the last delay");
693
694
        let (base, seen) = fake_hub(vec![401]);
695
        assert!(hub_at(base).post_with("/flow/claim", &serde_json::json!({}), &quick).is_err());
696
        assert_eq!(seen.load(std::sync::atomic::Ordering::SeqCst), 1, "a refusal is final");
697
    }
698
699
    #[test]
700
    fn the_budget_admits_jobs_that_fit() {
701
        let b = Budget { max_jobs: 3, memory_mib: Some(24_576), cpus: Some(8) };
702
        let used = |jobs, memory_mib, cpus| Used { jobs, memory_mib, cpus };
703
        assert_eq!(b.room(used(0, 0, 0)), Some((None, None)), "a lone job may take everything");
704
        assert_eq!(b.room(used(1, 8192, 4)), Some((Some(16_384), Some(4))));
705
        assert_eq!(b.room(used(2, 16_384, 8)), None, "no vCPU left");
706
        assert_eq!(b.room(used(3, 1024, 1)), None, "at max_jobs");
707
        let one = Budget { max_jobs: 1, memory_mib: None, cpus: None };
708
        assert_eq!(one.room(used(0, 0, 0)), Some((None, None)));
709
        assert_eq!(one.room(used(1, 0, 0)), None, "the default runs one job at a time");
710
        let open = Budget { max_jobs: 2, memory_mib: None, cpus: None };
711
        assert_eq!(open.room(used(1, 8192, 4)), Some((None, None)), "no limits configured");
712
    }
713
}