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