OXYGENHUB
# 47c1d64dec8a +5 oxygenflow / crates / flow / src / runner.rs
19.2 KiB · Rust · last changed Runners sign their receipts 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, 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
    pub fn finish(&self, job: i64, f: &Finish) -> Result<()> {
68
        self.post(&format!("/flow/jobs/{job}/finish"), f)?;
69
        Ok(())
70
    }
71
}
72
73
/// Waits before trying a hub request again after a server error.
74
const RETRY_DELAYS: [Duration; 3] = [Duration::from_secs(1), Duration::from_secs(2), Duration::from_secs(4)];
75
76
/// What the runner may run at once (flow.toml `[runner]`): at most
77
/// `max_jobs` jobs, whose sandboxes together fit `memory_mib` and `cpus`.
78
#[derive(Debug, Default, PartialEq, Eq)]
79
pub struct Budget {
80
    pub max_jobs: usize,
81
    pub memory_mib: Option<u32>,
82
    pub cpus: Option<u32>,
83
}
84
85
/// What is in use now.
86
#[derive(Debug, Default, Clone, Copy, PartialEq, Eq)]
87
pub struct Used {
88
    pub jobs: usize,
89
    pub memory_mib: u32,
90
    pub cpus: u32,
91
}
92
93
impl Budget {
94
    pub fn of(cfg: &RunnerConfig) -> Budget {
95
        Budget { max_jobs: cfg.max_jobs.unwrap_or(1).max(1), memory_mib: cfg.memory_mib, cpus: cfg.cpus }
96
    }
97
98
    /// The room to ask the hub for, or `None` when no job more can start.
99
    /// A lone job may use the whole budget even if it asks for more, so a
100
    /// large sandbox is never starved.
101
    pub fn room(&self, used: Used) -> Option<(Option<u32>, Option<u32>)> {
102
        if used.jobs >= self.max_jobs {
103
            return None;
104
        }
105
        if used.jobs == 0 {
106
            return Some((None, None));
107
        }
108
        let mem = self.memory_mib.map(|m| m.saturating_sub(used.memory_mib));
109
        let cpus = self.cpus.map(|c| c.saturating_sub(used.cpus));
110
        if mem == Some(0) || cpus == Some(0) {
111
            return None;
112
        }
113
        Some((mem, cpus))
114
    }
115
}
116
117
pub fn serve(home: &Home) -> Result<()> {
118
    let cfg = home.config.runner.clone().context("flow.toml has no [runner] section")?;
119
    let hub = Hub::new(&cfg)?;
120
    let name = cfg.name.clone().unwrap_or_else(|| "flow".into());
121
    let budget = Budget::of(&cfg);
122
    let key = home.runner_key(&name)?;
123
    eprintln!(
124
        "flow runner {name}: polling {} (up to {} jobs at once), signing receipts as {}",
125
        cfg.hub,
126
        budget.max_jobs,
127
        key.identity.hash().to_hex()
128
    );
129
    let used = std::sync::Mutex::new(Used::default());
130
    let mut idle = Duration::from_secs(2);
131
    std::thread::scope(|scope| loop {
132
        let room = budget.room(*used.lock().unwrap());
133
        let Some((free_memory_mib, free_cpus)) = room else {
134
            std::thread::sleep(Duration::from_millis(500));
135
            continue;
136
        };
137
        let req = ClaimRequest { runner: name.clone(), runtimes: vec!["microvm".into()], free_memory_mib, free_cpus };
138
        match hub.claim(&req) {
139
            Ok(Some(claim)) => {
140
                idle = Duration::from_secs(2);
141
                let (mem, cpus) = (claim.sandbox.memory_mib, claim.sandbox.cpus);
142
                {
143
                    let mut u = used.lock().unwrap();
144
                    u.jobs += 1;
145
                    u.memory_mib += mem;
146
                    u.cpus += cpus;
147
                }
148
                let (home, hub, cfg, used, key) = (home, &hub, &cfg, &used, &key);
149
                scope.spawn(move || {
150
                    let id = claim.job_id;
151
                    eprintln!("job {id}: {} {} on {}", claim.repo, claim.job.name, claim.heads.first().map(|h| &h[..12]).unwrap_or("-"));
152
                    let finish = run_claim(home, hub, cfg, key, &claim).unwrap_or_else(|e| Finish {
153
                        exit_code: None,
154
                        duration_ms: 0,
155
                        receipt: None,
156
                        signed_receipt: None,
157
                        error: Some(format!("{e:#}")),
158
                    });
159
                    eprintln!(
160
                        "job {id}: exit {:?}{}",
161
                        finish.exit_code,
162
                        finish.error.as_deref().map(|e| format!(" ({e})")).unwrap_or_default()
163
                    );
164
                    if let Err(e) = hub.finish(id, &finish) {
165
                        eprintln!("job {id}: reporting failed: {e:#}");
166
                    }
167
                    let mut u = used.lock().unwrap();
168
                    u.jobs -= 1;
169
                    u.memory_mib -= mem;
170
                    u.cpus -= cpus;
171
                });
172
            }
173
            Ok(None) => std::thread::sleep(idle),
174
            Err(e) => {
175
                eprintln!("claim: {e:#}");
176
                std::thread::sleep(idle);
177
                idle = (idle * 2).min(Duration::from_secs(60));
178
            }
179
        }
180
    })
181
}
182
183
/// Batches records to the hub every second (or every 200 lines).
184
struct LogSink<'a> {
185
    hub: &'a Hub,
186
    job: i64,
187
    buf: Vec<Record>,
188
    last: Instant,
189
}
190
191
impl LogSink<'_> {
192
    fn push(&mut self, mut r: Record) {
193
        if r.text.len() > MAX_RECORD_TEXT {
194
            let mut cut = MAX_RECORD_TEXT;
195
            while !r.text.is_char_boundary(cut) {
196
                cut -= 1;
197
            }
198
            r.text.truncate(cut);
199
        }
200
        self.buf.push(r);
201
        if self.buf.len() >= 200 || self.last.elapsed() >= Duration::from_secs(1) {
202
            self.flush();
203
        }
204
    }
205
206
    fn flush(&mut self) {
207
        if !self.buf.is_empty() {
208
            if let Err(e) = self.hub.log(self.job, std::mem::take(&mut self.buf)) {
209
                eprintln!("job {}: log: {e:#}", self.job);
210
            }
211
        }
212
        self.last = Instant::now();
213
    }
214
}
215
216
/// Held while a job's workspace is prepared (see `run_claim`).
217
static PREPARE: std::sync::Mutex<()> = std::sync::Mutex::new(());
218
219
fn run_claim(home: &Home, hub: &Hub, cfg: &RunnerConfig, key: &RunnerKey, claim: &Claim) -> Result<Finish> {
220
    let started = Instant::now();
221
    let mut sink = LogSink { hub, job: claim.job_id, buf: Vec::new(), last: Instant::now() };
222
    let note =
223
        |sink: &mut LogSink, text: String| sink.push(Record { t: started.elapsed().as_millis() as u64, stream: "flow".into(), text });
224
    let heads: Vec<ChangeHash> = claim.heads.iter().map(|h| ChangeHash::from_hex(h).context("bad head")).collect::<Result<_>>()?;
225
    note(&mut sink, format!("fetching {} for state {}", claim.repo, claim.heads.iter().map(|h| &h[..12]).collect::<Vec<_>>().join("+")));
226
    // Preparing a workspace (the cached repositories, the export, the
227
    // image) is one job at a time: fetches into a cached repository must not
228
    // overlap, and the first clone passes its token through the process
229
    // environment. Only the microVMs run side by side.
230
    let mut preparing = Some(PREPARE.lock().unwrap_or_else(|p| p.into_inner()));
231
    let repo = cached_repo(home, cfg, claim)?;
232
    let scratch = home.root.join("work").join(format!("job-{}", claim.job_id));
233
    let _ = std::fs::remove_dir_all(&scratch);
234
    std::fs::create_dir_all(scratch.join("tree"))?;
235
    let result = (|| -> Result<Finish> {
236
        let mut files = workspace::export_state(&repo, &heads, &scratch.join("tree"))?;
237
        // Pinned subrepos (Oxygen spec §7.8), at their paths, as part of the
238
        // workspace and of the scope hash.
239
        for sub in &claim.subrepos {
240
            if sub.path.split('/').any(|p| p.is_empty() || p == "." || p == ".." || p == ".oxy") {
241
                bail!("subrepo path {:?} is not a clean relative path", sub.path);
242
            }
243
            note(
244
                &mut sink,
245
                format!(
246
                    "fetching subrepo {} at {} for {}",
247
                    sub.repo,
248
                    sub.heads.iter().map(|h| &h[..12]).collect::<Vec<_>>().join("+"),
249
                    sub.path
250
                ),
251
            );
252
            let sub_repo = cached_repo_at(home, cfg, &sub.repo, &sub.clone_url, &claim.token)?;
253
            let sub_heads: Vec<ChangeHash> =
254
                sub.heads.iter().map(|h| ChangeHash::from_hex(h).context("bad subrepo head")).collect::<Result<_>>()?;
255
            let dir = scratch.join("tree").join(&sub.path);
256
            std::fs::create_dir_all(&dir)?;
257
            let sub_files = workspace::export_state(&sub_repo, &sub_heads, &dir)?;
258
            files.extend(sub_files.into_iter().map(|(p, h)| (format!("{}/{p}", sub.path), h)));
259
        }
260
        let scope_hash = scope_tree_hash(&claim.job.scope, files.iter().map(|(p, h)| (p.as_str(), *h)));
261
        workspace::image(&scratch.join("tree"), &scratch.join("workspace.ext4"))?;
262
        std::fs::remove_dir_all(scratch.join("tree"))?;
263
        preparing.take();
264
        note(
265
            &mut sink,
266
            format!(
267
                "booting a microVM: {} vCPU, {} MiB, rootfs {}",
268
                claim.sandbox.cpus,
269
                claim.sandbox.memory_mib,
270
                &claim.sandbox.rootfs[..12]
271
            ),
272
        );
273
        let job = claim.job.in_sandbox(&claim.sandbox).with_flow_env(&claim.flow_env());
274
        let outcome = microvm::run(
275
            home,
276
            &claim.sandbox,
277
            &job,
278
            &scratch.join("workspace.ext4"),
279
            &scratch,
280
            Duration::from_secs(claim.timeout_s),
281
            &mut |r| sink.push(r),
282
        )?;
283
        let receipt = outcome.exit_code.map(|code| Receipt {
284
            job_name: claim.job.name.clone(),
285
            pipeline_hash: hex32(&claim.pipeline_hash),
286
            scope_tree_hash: scope_hash,
287
            inputs: vec![],
288
            environment: outcome.environment.hash(),
289
            outputs: vec![],
290
            exit_code: code as u32,
291
            duration_ms: outcome.duration_ms,
292
        });
293
        let signed_receipt = match &receipt {
294
            Some(r) => Some(hex::encode(sign_receipt(&repo, &heads, cfg, key, claim, r)?.encode())),
295
            None => None,
296
        };
297
        Ok(Finish {
298
            exit_code: outcome.exit_code,
299
            duration_ms: started.elapsed().as_millis() as u64,
300
            receipt,
301
            signed_receipt,
302
            error: outcome.timed_out.then(|| "stopped at the time limit".to_string()),
303
        })
304
    })();
305
    let _ = std::fs::remove_dir_all(&scratch);
306
    sink.flush();
307
    result
308
}
309
310
/// Bind `receipt` to the state of `heads` in `repo` and sign it as the
311
/// runner (Oxygen spec §14.6). The state is computed here, not taken from
312
/// the claim, so the runner vouches only for what it fetched.
313
fn sign_receipt(
314
    repo: &Repo,
315
    heads: &[ChangeHash],
316
    cfg: &RunnerConfig,
317
    key: &RunnerKey,
318
    claim: &Claim,
319
    receipt: &Receipt,
320
) -> Result<oxy_core::receipt::SignedReceipt> {
321
    let state = state_of(heads);
322
    let run = format!("{}/{}/flow/{}", cfg.hub.trim_end_matches('/'), claim.repo, claim.run_number);
323
    Ok(oxy_core::receipt::SignedReceipt::sign(receipt.to_oxy(), repo.id()?, state, &run, &key.identity, &key.secret))
324
}
325
326
/// The ObjectRef of the state whose heads are `heads` (Oxygen spec §10.1).
327
pub fn state_of(heads: &[ChangeHash]) -> oxy_core::hash::ObjectRef {
328
    use oxy_core::hash::{hash_object, ObjectType};
329
    hash_object(ObjectType::State, &oxy_core::objects::StateObject::new(heads.to_vec()).encode())
330
}
331
332
fn hex32(s: &str) -> [u8; 32] {
333
    let mut out = [0; 32];
334
    if let Ok(v) = hex::decode(s) {
335
        if v.len() == 32 {
336
            out.copy_from_slice(&v);
337
        }
338
    }
339
    out
340
}
341
342
/// The runner's copy of a repository, fetched up to date with the job's token.
343
fn cached_repo(home: &Home, cfg: &RunnerConfig, claim: &Claim) -> Result<Repo> {
344
    cached_repo_at(home, cfg, &claim.repo, &claim.clone_url, &claim.token)
345
}
346
347
/// The runner's copy of `repo`, cloned or fetched with `token`.
348
fn cached_repo_at(home: &Home, cfg: &RunnerConfig, repo_name: &str, clone_url: &str, token: &str) -> Result<Repo> {
349
    let dir: PathBuf = home.root.join("repos").join(repo_name.replace('/', "__"));
350
    let set_remote = |repo: &mut Repo| -> Result<()> {
351
        repo.config.set("remote.origin.url", clone_url).map_err(|e| anyhow::anyhow!("{e}"))?;
352
        repo.config.set("remote.origin.token", token).map_err(|e| anyhow::anyhow!("{e}"))?;
353
        if let Some(ca) = &cfg.ca {
354
            repo.config.set("remote.origin.ca", &ca.to_string_lossy()).map_err(|e| anyhow::anyhow!("{e}"))?;
355
        }
356
        repo.save_config().map_err(|e| anyhow::anyhow!("{e}"))
357
    };
358
    if dir.join(".oxy").is_dir() {
359
        let mut repo = Repo::open(&dir).map_err(|e| anyhow::anyhow!("{e}"))?;
360
        set_remote(&mut repo)?;
361
        repo.fetch("origin").map_err(|e| anyhow::anyhow!("fetch {clone_url}: {e}"))?;
362
        return Ok(repo);
363
    }
364
    // First job for this repository: clone with the job's token.
365
    std::env::set_var("OXY_TOKEN", token);
366
    if let Some(ca) = &cfg.ca {
367
        std::env::set_var("OXY_CA", ca);
368
    }
369
    let cloned = Repo::clone(clone_url, &dir);
370
    std::env::remove_var("OXY_TOKEN");
371
    std::env::remove_var("OXY_CA");
372
    let mut repo = cloned.map_err(|e| {
373
        let _ = std::fs::remove_dir_all(&dir);
374
        anyhow::anyhow!("clone {}: {e}", clone_url)
375
    })?;
376
    set_remote(&mut repo)?;
377
    Ok(repo)
378
}
379
380
#[cfg(test)]
381
mod tests {
382
    use super::*;
383
384
    /// A hub that answers each request with the next of `codes`, counting them.
385
    fn fake_hub(codes: Vec<u16>) -> (String, std::sync::Arc<std::sync::atomic::AtomicUsize>) {
386
        use std::io::{Read, Write};
387
        let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
388
        let addr = listener.local_addr().unwrap();
389
        let seen = std::sync::Arc::new(std::sync::atomic::AtomicUsize::new(0));
390
        let count = seen.clone();
391
        std::thread::spawn(move || {
392
            for code in codes {
393
                let (mut s, _) = listener.accept().unwrap();
394
                // Read the whole request (headers, then Content-Length bytes
395
                // of body) before answering: closing early would reset the
396
                // connection while the client is still sending.
397
                let mut req = Vec::new();
398
                let mut buf = [0u8; 8192];
399
                loop {
400
                    let n = s.read(&mut buf).unwrap_or(0);
401
                    if n == 0 {
402
                        break;
403
                    }
404
                    req.extend_from_slice(&buf[..n]);
405
                    let text = String::from_utf8_lossy(&req);
406
                    if let Some(end) = text.find("\r\n\r\n") {
407
                        let len = text[..end]
408
                            .lines()
409
                            .find_map(|l| {
410
                                l.to_ascii_lowercase().strip_prefix("content-length:").map(|v| v.trim().parse::<usize>().unwrap_or(0))
411
                            })
412
                            .unwrap_or(0);
413
                        if req.len() >= end + 4 + len {
414
                            break;
415
                        }
416
                    }
417
                }
418
                count.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
419
                let reason = if code == 204 { "No Content" } else { "Error" };
420
                let _ = write!(s, "HTTP/1.1 {code} {reason}\r\nContent-Length: 0\r\nConnection: close\r\n\r\n");
421
            }
422
        });
423
        (format!("http://{addr}"), seen)
424
    }
425
426
    fn hub_at(base: String) -> Hub {
427
        Hub { base, token: "t".into(), agent: ureq::AgentBuilder::new().timeout(Duration::from_secs(5)).build() }
428
    }
429
430
    #[test]
431
    fn server_errors_are_tried_again_and_client_errors_are_not() {
432
        let quick = [Duration::from_millis(10); 3];
433
        let (base, seen) = fake_hub(vec![500, 503, 204]);
434
        let r = hub_at(base).post_with("/flow/jobs/1/log", &serde_json::json!({}), &quick).unwrap();
435
        assert!(r.is_none());
436
        assert_eq!(seen.load(std::sync::atomic::Ordering::SeqCst), 3, "two retries, then accepted");
437
438
        let (base, seen) = fake_hub(vec![500, 500, 500, 500]);
439
        let e = hub_at(base).post_with("/flow/claim", &serde_json::json!({}), &quick).unwrap_err().to_string();
440
        assert!(e.contains("HTTP 500"), "{e}");
441
        assert_eq!(seen.load(std::sync::atomic::Ordering::SeqCst), 4, "gives up after the last delay");
442
443
        let (base, seen) = fake_hub(vec![401]);
444
        assert!(hub_at(base).post_with("/flow/claim", &serde_json::json!({}), &quick).is_err());
445
        assert_eq!(seen.load(std::sync::atomic::Ordering::SeqCst), 1, "a refusal is final");
446
    }
447
448
    #[test]
449
    fn the_budget_admits_jobs_that_fit() {
450
        let b = Budget { max_jobs: 3, memory_mib: Some(24_576), cpus: Some(8) };
451
        let used = |jobs, memory_mib, cpus| Used { jobs, memory_mib, cpus };
452
        assert_eq!(b.room(used(0, 0, 0)), Some((None, None)), "a lone job may take everything");
453
        assert_eq!(b.room(used(1, 8192, 4)), Some((Some(16_384), Some(4))));
454
        assert_eq!(b.room(used(2, 16_384, 8)), None, "no vCPU left");
455
        assert_eq!(b.room(used(3, 1024, 1)), None, "at max_jobs");
456
        let one = Budget { max_jobs: 1, memory_mib: None, cpus: None };
457
        assert_eq!(one.room(used(0, 0, 0)), Some((None, None)));
458
        assert_eq!(one.room(used(1, 0, 0)), None, "the default runs one job at a time");
459
        let open = Budget { max_jobs: 2, memory_mib: None, cpus: None };
460
        assert_eq!(open.room(used(1, 8192, 4)), Some((None, None)), "no limits configured");
461
    }
462
}