OXYGENHUB
# f3b4fdeb2bc2 oxygenflow / crates / flow / src / runner.rs
16.4 KiB · Rust · last changed CI without debug info; the retry test reads whole requests 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};
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
    eprintln!("flow runner {name}: polling {} (up to {} jobs at once)", cfg.hub, budget.max_jobs);
123
    let used = std::sync::Mutex::new(Used::default());
124
    let mut idle = Duration::from_secs(2);
125
    std::thread::scope(|scope| loop {
126
        let room = budget.room(*used.lock().unwrap());
127
        let Some((free_memory_mib, free_cpus)) = room else {
128
            std::thread::sleep(Duration::from_millis(500));
129
            continue;
130
        };
131
        let req = ClaimRequest { runner: name.clone(), runtimes: vec!["microvm".into()], free_memory_mib, free_cpus };
132
        match hub.claim(&req) {
133
            Ok(Some(claim)) => {
134
                idle = Duration::from_secs(2);
135
                let (mem, cpus) = (claim.sandbox.memory_mib, claim.sandbox.cpus);
136
                {
137
                    let mut u = used.lock().unwrap();
138
                    u.jobs += 1;
139
                    u.memory_mib += mem;
140
                    u.cpus += cpus;
141
                }
142
                let (home, hub, cfg, used) = (home, &hub, &cfg, &used);
143
                scope.spawn(move || {
144
                    let id = claim.job_id;
145
                    eprintln!("job {id}: {} {} on {}", claim.repo, claim.job.name, claim.heads.first().map(|h| &h[..12]).unwrap_or("-"));
146
                    let finish = run_claim(home, hub, cfg, &claim).unwrap_or_else(|e| Finish {
147
                        exit_code: None,
148
                        duration_ms: 0,
149
                        receipt: None,
150
                        error: Some(format!("{e:#}")),
151
                    });
152
                    eprintln!(
153
                        "job {id}: exit {:?}{}",
154
                        finish.exit_code,
155
                        finish.error.as_deref().map(|e| format!(" ({e})")).unwrap_or_default()
156
                    );
157
                    if let Err(e) = hub.finish(id, &finish) {
158
                        eprintln!("job {id}: reporting failed: {e:#}");
159
                    }
160
                    let mut u = used.lock().unwrap();
161
                    u.jobs -= 1;
162
                    u.memory_mib -= mem;
163
                    u.cpus -= cpus;
164
                });
165
            }
166
            Ok(None) => std::thread::sleep(idle),
167
            Err(e) => {
168
                eprintln!("claim: {e:#}");
169
                std::thread::sleep(idle);
170
                idle = (idle * 2).min(Duration::from_secs(60));
171
            }
172
        }
173
    })
174
}
175
176
/// Batches records to the hub every second (or every 200 lines).
177
struct LogSink<'a> {
178
    hub: &'a Hub,
179
    job: i64,
180
    buf: Vec<Record>,
181
    last: Instant,
182
}
183
184
impl LogSink<'_> {
185
    fn push(&mut self, mut r: Record) {
186
        if r.text.len() > MAX_RECORD_TEXT {
187
            let mut cut = MAX_RECORD_TEXT;
188
            while !r.text.is_char_boundary(cut) {
189
                cut -= 1;
190
            }
191
            r.text.truncate(cut);
192
        }
193
        self.buf.push(r);
194
        if self.buf.len() >= 200 || self.last.elapsed() >= Duration::from_secs(1) {
195
            self.flush();
196
        }
197
    }
198
199
    fn flush(&mut self) {
200
        if !self.buf.is_empty() {
201
            if let Err(e) = self.hub.log(self.job, std::mem::take(&mut self.buf)) {
202
                eprintln!("job {}: log: {e:#}", self.job);
203
            }
204
        }
205
        self.last = Instant::now();
206
    }
207
}
208
209
/// Held while a job's workspace is prepared (see `run_claim`).
210
static PREPARE: std::sync::Mutex<()> = std::sync::Mutex::new(());
211
212
fn run_claim(home: &Home, hub: &Hub, cfg: &RunnerConfig, claim: &Claim) -> Result<Finish> {
213
    let started = Instant::now();
214
    let mut sink = LogSink { hub, job: claim.job_id, buf: Vec::new(), last: Instant::now() };
215
    let note =
216
        |sink: &mut LogSink, text: String| sink.push(Record { t: started.elapsed().as_millis() as u64, stream: "flow".into(), text });
217
    let heads: Vec<ChangeHash> = claim.heads.iter().map(|h| ChangeHash::from_hex(h).context("bad head")).collect::<Result<_>>()?;
218
    note(&mut sink, format!("fetching {} for state {}", claim.repo, claim.heads.iter().map(|h| &h[..12]).collect::<Vec<_>>().join("+")));
219
    // Preparing a workspace (the cached repositories, the export, the
220
    // image) is one job at a time: fetches into a cached repository must not
221
    // overlap, and the first clone passes its token through the process
222
    // environment. Only the microVMs run side by side.
223
    let mut preparing = Some(PREPARE.lock().unwrap_or_else(|p| p.into_inner()));
224
    let repo = cached_repo(home, cfg, claim)?;
225
    let scratch = home.root.join("work").join(format!("job-{}", claim.job_id));
226
    let _ = std::fs::remove_dir_all(&scratch);
227
    std::fs::create_dir_all(scratch.join("tree"))?;
228
    let result = (|| -> Result<Finish> {
229
        let files = workspace::export_state(&repo, &heads, &scratch.join("tree"))?;
230
        let scope_hash = scope_tree_hash(&claim.job.scope, files.iter().map(|(p, h)| (p.as_str(), *h)));
231
        workspace::image(&scratch.join("tree"), &scratch.join("workspace.ext4"))?;
232
        std::fs::remove_dir_all(scratch.join("tree"))?;
233
        preparing.take();
234
        note(
235
            &mut sink,
236
            format!(
237
                "booting a microVM: {} vCPU, {} MiB, rootfs {}",
238
                claim.sandbox.cpus,
239
                claim.sandbox.memory_mib,
240
                &claim.sandbox.rootfs[..12]
241
            ),
242
        );
243
        let outcome = microvm::run(
244
            home,
245
            &claim.sandbox,
246
            &claim.job,
247
            &scratch.join("workspace.ext4"),
248
            &scratch,
249
            Duration::from_secs(claim.timeout_s),
250
            &mut |r| sink.push(r),
251
        )?;
252
        let receipt = outcome.exit_code.map(|code| Receipt {
253
            job_name: claim.job.name.clone(),
254
            pipeline_hash: hex32(&claim.pipeline_hash),
255
            scope_tree_hash: scope_hash,
256
            inputs: vec![],
257
            environment: outcome.environment.hash(),
258
            outputs: vec![],
259
            exit_code: code as u32,
260
            duration_ms: outcome.duration_ms,
261
        });
262
        Ok(Finish {
263
            exit_code: outcome.exit_code,
264
            duration_ms: started.elapsed().as_millis() as u64,
265
            receipt,
266
            error: outcome.timed_out.then(|| "stopped at the time limit".to_string()),
267
        })
268
    })();
269
    let _ = std::fs::remove_dir_all(&scratch);
270
    sink.flush();
271
    result
272
}
273
274
fn hex32(s: &str) -> [u8; 32] {
275
    let mut out = [0; 32];
276
    if let Ok(v) = hex::decode(s) {
277
        if v.len() == 32 {
278
            out.copy_from_slice(&v);
279
        }
280
    }
281
    out
282
}
283
284
/// The runner's copy of a repository, fetched up to date with the job's token.
285
fn cached_repo(home: &Home, cfg: &RunnerConfig, claim: &Claim) -> Result<Repo> {
286
    let dir: PathBuf = home.root.join("repos").join(claim.repo.replace('/', "__"));
287
    let set_remote = |repo: &mut Repo| -> Result<()> {
288
        repo.config.set("remote.origin.url", &claim.clone_url).map_err(|e| anyhow::anyhow!("{e}"))?;
289
        repo.config.set("remote.origin.token", &claim.token).map_err(|e| anyhow::anyhow!("{e}"))?;
290
        if let Some(ca) = &cfg.ca {
291
            repo.config.set("remote.origin.ca", &ca.to_string_lossy()).map_err(|e| anyhow::anyhow!("{e}"))?;
292
        }
293
        repo.save_config().map_err(|e| anyhow::anyhow!("{e}"))
294
    };
295
    if dir.join(".oxy").is_dir() {
296
        let mut repo = Repo::open(&dir).map_err(|e| anyhow::anyhow!("{e}"))?;
297
        set_remote(&mut repo)?;
298
        repo.fetch("origin").map_err(|e| anyhow::anyhow!("fetch {}: {e}", claim.clone_url))?;
299
        return Ok(repo);
300
    }
301
    // First job for this repository: clone with the job's token.
302
    std::env::set_var("OXY_TOKEN", &claim.token);
303
    if let Some(ca) = &cfg.ca {
304
        std::env::set_var("OXY_CA", ca);
305
    }
306
    let cloned = Repo::clone(&claim.clone_url, &dir);
307
    std::env::remove_var("OXY_TOKEN");
308
    std::env::remove_var("OXY_CA");
309
    let mut repo = cloned.map_err(|e| {
310
        let _ = std::fs::remove_dir_all(&dir);
311
        anyhow::anyhow!("clone {}: {e}", claim.clone_url)
312
    })?;
313
    set_remote(&mut repo)?;
314
    Ok(repo)
315
}
316
317
#[cfg(test)]
318
mod tests {
319
    use super::*;
320
321
    /// A hub that answers each request with the next of `codes`, counting them.
322
    fn fake_hub(codes: Vec<u16>) -> (String, std::sync::Arc<std::sync::atomic::AtomicUsize>) {
323
        use std::io::{Read, Write};
324
        let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
325
        let addr = listener.local_addr().unwrap();
326
        let seen = std::sync::Arc::new(std::sync::atomic::AtomicUsize::new(0));
327
        let count = seen.clone();
328
        std::thread::spawn(move || {
329
            for code in codes {
330
                let (mut s, _) = listener.accept().unwrap();
331
                // Read the whole request (headers, then Content-Length bytes
332
                // of body) before answering: closing early would reset the
333
                // connection while the client is still sending.
334
                let mut req = Vec::new();
335
                let mut buf = [0u8; 8192];
336
                loop {
337
                    let n = s.read(&mut buf).unwrap_or(0);
338
                    if n == 0 {
339
                        break;
340
                    }
341
                    req.extend_from_slice(&buf[..n]);
342
                    let text = String::from_utf8_lossy(&req);
343
                    if let Some(end) = text.find("\r\n\r\n") {
344
                        let len = text[..end]
345
                            .lines()
346
                            .find_map(|l| {
347
                                l.to_ascii_lowercase().strip_prefix("content-length:").map(|v| v.trim().parse::<usize>().unwrap_or(0))
348
                            })
349
                            .unwrap_or(0);
350
                        if req.len() >= end + 4 + len {
351
                            break;
352
                        }
353
                    }
354
                }
355
                count.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
356
                let reason = if code == 204 { "No Content" } else { "Error" };
357
                let _ = write!(s, "HTTP/1.1 {code} {reason}\r\nContent-Length: 0\r\nConnection: close\r\n\r\n");
358
            }
359
        });
360
        (format!("http://{addr}"), seen)
361
    }
362
363
    fn hub_at(base: String) -> Hub {
364
        Hub { base, token: "t".into(), agent: ureq::AgentBuilder::new().timeout(Duration::from_secs(5)).build() }
365
    }
366
367
    #[test]
368
    fn server_errors_are_tried_again_and_client_errors_are_not() {
369
        let quick = [Duration::from_millis(10); 3];
370
        let (base, seen) = fake_hub(vec![500, 503, 204]);
371
        let r = hub_at(base).post_with("/flow/jobs/1/log", &serde_json::json!({}), &quick).unwrap();
372
        assert!(r.is_none());
373
        assert_eq!(seen.load(std::sync::atomic::Ordering::SeqCst), 3, "two retries, then accepted");
374
375
        let (base, seen) = fake_hub(vec![500, 500, 500, 500]);
376
        let e = hub_at(base).post_with("/flow/claim", &serde_json::json!({}), &quick).unwrap_err().to_string();
377
        assert!(e.contains("HTTP 500"), "{e}");
378
        assert_eq!(seen.load(std::sync::atomic::Ordering::SeqCst), 4, "gives up after the last delay");
379
380
        let (base, seen) = fake_hub(vec![401]);
381
        assert!(hub_at(base).post_with("/flow/claim", &serde_json::json!({}), &quick).is_err());
382
        assert_eq!(seen.load(std::sync::atomic::Ordering::SeqCst), 1, "a refusal is final");
383
    }
384
385
    #[test]
386
    fn the_budget_admits_jobs_that_fit() {
387
        let b = Budget { max_jobs: 3, memory_mib: Some(24_576), cpus: Some(8) };
388
        let used = |jobs, memory_mib, cpus| Used { jobs, memory_mib, cpus };
389
        assert_eq!(b.room(used(0, 0, 0)), Some((None, None)), "a lone job may take everything");
390
        assert_eq!(b.room(used(1, 8192, 4)), Some((Some(16_384), Some(4))));
391
        assert_eq!(b.room(used(2, 16_384, 8)), None, "no vCPU left");
392
        assert_eq!(b.room(used(3, 1024, 1)), None, "at max_jobs");
393
        let one = Budget { max_jobs: 1, memory_mib: None, cpus: None };
394
        assert_eq!(one.room(used(0, 0, 0)), Some((None, None)));
395
        assert_eq!(one.room(used(1, 0, 0)), None, "the default runs one job at a time");
396
        let open = Budget { max_jobs: 2, memory_mib: None, cpus: None };
397
        assert_eq!(open.room(used(1, 8192, 4)), Some((None, None)), "no limits configured");
398
    }
399
}