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