OXYGENHUB
# 67634e22f48f +4 oxygenflow / crates / flow / src / runner.rs
27.3 KiB · Rust · last changed Register runners with a token; describe them in claims 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};
f98a8f78 Andy McCall ↶ 9
use flow_core::api::{Claim, ClaimRequest, Finish, LogBatch, Record, Register, Registered, RunnerInfo, MAX_RECORD_TEXT};
e0918b88 Andy McCall 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
1b2229da Andy McCall ↶ 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.
e0918b88 Andy McCall 32
    fn post(&self, path: &str, body: &impl serde::Serialize) -> Result<Option<ureq::Response>> {
1b2229da Andy McCall ↶ 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>> {
e0918b88 Andy McCall 37
        let url = format!("{}/api/v1{path}", self.base);
1b2229da Andy McCall ↶ 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
            }
e0918b88 Andy McCall 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
a67b97e9 Andy McCall ↶ 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
e0918b88 Andy McCall 96
    pub fn finish(&self, job: i64, f: &Finish) -> Result<()> {
97
        self.post(&format!("/flow/jobs/{job}/finish"), f)?;
98
        Ok(())
f98a8f78 Andy McCall ↶ 99
    }
100
}
101
102
/// `flow runner register`: exchange a one-time registration token from
103
/// the hub for this runner's credential, binding the runner's signing key,
104
/// and keep hub, credential and name in runner.toml.
105
pub fn register(home: &Home, hub: &str, token: &str, name: &str, ca: Option<PathBuf>, labels: Vec<String>) -> Result<Registered> {
106
    if home.config.runner.is_some() && !home.root.join(crate::home::RUNNER_TOML).is_file() {
107
        bail!("flow.toml already has a [runner] section; remove it to register this runner instead");
108
    }
109
    let key = home.runner_key(name)?;
110
    let hub = hub.trim_end_matches('/').to_string();
111
    let tls = oxy_core::protocol::tls_client_config(ca.as_deref()).map_err(|e| anyhow::anyhow!("{e}"))?;
112
    let agent = ureq::AgentBuilder::new().tls_config(tls).timeout(Duration::from_secs(60)).build();
113
    let req = Register {
114
        token: token.trim().to_string(),
115
        name: name.to_string(),
116
        identity: hex::encode(key.identity.encode()),
117
        info: RunnerInfo::here(labels.clone(), 1, None, None),
118
    };
119
    let url = format!("{hub}/api/v1/flow/runners/register");
120
    let got: Registered = match agent.post(&url).send_json(&req) {
121
        Ok(r) => r.into_json()?,
122
        Err(ureq::Error::Status(code, r)) => bail!("{url}: HTTP {code}: {}", r.into_string().unwrap_or_default()),
123
        Err(e) => bail!("{url}: {e}"),
124
    };
125
    let mut text = format!(
126
        "# Written by `flow runner register`; the credential is secret.\nhub = {hub:?}\ntoken = {:?}\nname = {:?}\n",
127
        got.credential, got.name
128
    );
129
    if let Some(ca) = &ca {
130
        text.push_str(&format!("ca = {:?}\n", ca.display().to_string()));
131
    }
132
    if !labels.is_empty() {
133
        text.push_str(&format!("labels = {labels:?}\n"));
134
    }
135
    let path = home.root.join(crate::home::RUNNER_TOML);
136
    {
137
        use std::io::Write;
138
        use std::os::unix::fs::OpenOptionsExt;
139
        let tmp = path.with_extension("toml.tmp");
140
        let mut f = std::fs::OpenOptions::new().write(true).create(true).truncate(true).mode(0o600).open(&tmp)?;
141
        f.write_all(text.as_bytes())?;
142
        f.sync_all()?;
143
        std::fs::rename(&tmp, &path)?;
e0918b88 Andy McCall 144
    }
f98a8f78 Andy McCall ↶ 145
    Ok(got)
e0918b88 Andy McCall 146
}
1b2229da Andy McCall ↶ 147
148
/// Waits before trying a hub request again after a server error.
149
const RETRY_DELAYS: [Duration; 3] = [Duration::from_secs(1), Duration::from_secs(2), Duration::from_secs(4)];
e0918b88 Andy McCall 150
bb643c25 Andy McCall ↶ 151
/// What the runner may run at once (flow.toml `[runner]`): at most
152
/// `max_jobs` jobs, whose sandboxes together fit `memory_mib` and `cpus`.
153
#[derive(Debug, Default, PartialEq, Eq)]
154
pub struct Budget {
155
    pub max_jobs: usize,
156
    pub memory_mib: Option<u32>,
157
    pub cpus: Option<u32>,
158
}
159
160
/// What is in use now.
161
#[derive(Debug, Default, Clone, Copy, PartialEq, Eq)]
162
pub struct Used {
163
    pub jobs: usize,
164
    pub memory_mib: u32,
165
    pub cpus: u32,
166
}
167
168
impl Budget {
169
    pub fn of(cfg: &RunnerConfig) -> Budget {
170
        Budget { max_jobs: cfg.max_jobs.unwrap_or(1).max(1), memory_mib: cfg.memory_mib, cpus: cfg.cpus }
171
    }
172
173
    /// The room to ask the hub for, or `None` when no job more can start.
174
    /// A lone job may use the whole budget even if it asks for more, so a
175
    /// large sandbox is never starved.
176
    pub fn room(&self, used: Used) -> Option<(Option<u32>, Option<u32>)> {
177
        if used.jobs >= self.max_jobs {
178
            return None;
179
        }
180
        if used.jobs == 0 {
181
            return Some((None, None));
182
        }
183
        let mem = self.memory_mib.map(|m| m.saturating_sub(used.memory_mib));
184
        let cpus = self.cpus.map(|c| c.saturating_sub(used.cpus));
185
        if mem == Some(0) || cpus == Some(0) {
186
            return None;
187
        }
188
        Some((mem, cpus))
189
    }
190
}
191
e0918b88 Andy McCall 192
pub fn serve(home: &Home) -> Result<()> {
193
    let cfg = home.config.runner.clone().context("flow.toml has no [runner] section")?;
194
    let hub = Hub::new(&cfg)?;
195
    let name = cfg.name.clone().unwrap_or_else(|| "flow".into());
bb643c25 Andy McCall ↶ 196
    let budget = Budget::of(&cfg);
47c1d64d Andy McCall ↶ 197
    let key = home.runner_key(&name)?;
198
    eprintln!(
199
        "flow runner {name}: polling {} (up to {} jobs at once), signing receipts as {}",
200
        cfg.hub,
201
        budget.max_jobs,
202
        key.identity.hash().to_hex()
203
    );
bb643c25 Andy McCall ↶ 204
    let used = std::sync::Mutex::new(Used::default());
e0918b88 Andy McCall 205
    let mut idle = Duration::from_secs(2);
bb643c25 Andy McCall ↶ 206
    std::thread::scope(|scope| loop {
207
        let room = budget.room(*used.lock().unwrap());
208
        let Some((free_memory_mib, free_cpus)) = room else {
209
            std::thread::sleep(Duration::from_millis(500));
210
            continue;
211
        };
f98a8f78 Andy McCall ↶ 212
        let req = ClaimRequest {
213
            runner: name.clone(),
214
            runtimes: vec!["microvm".into()],
215
            free_memory_mib,
216
            free_cpus,
217
            info: Some(RunnerInfo::here(cfg.labels.clone(), budget.max_jobs as u32, cfg.memory_mib, cfg.cpus)),
218
        };
e0918b88 Andy McCall 219
        match hub.claim(&req) {
220
            Ok(Some(claim)) => {
221
                idle = Duration::from_secs(2);
bb643c25 Andy McCall ↶ 222
                let (mem, cpus) = (claim.sandbox.memory_mib, claim.sandbox.cpus);
223
                {
224
                    let mut u = used.lock().unwrap();
225
                    u.jobs += 1;
226
                    u.memory_mib += mem;
227
                    u.cpus += cpus;
e0918b88 Andy McCall 228
                }
47c1d64d Andy McCall ↶ 229
                let (home, hub, cfg, used, key) = (home, &hub, &cfg, &used, &key);
bb643c25 Andy McCall ↶ 230
                scope.spawn(move || {
231
                    let id = claim.job_id;
232
                    eprintln!("job {id}: {} {} on {}", claim.repo, claim.job.name, claim.heads.first().map(|h| &h[..12]).unwrap_or("-"));
47c1d64d Andy McCall ↶ 233
                    let finish = run_claim(home, hub, cfg, key, &claim).unwrap_or_else(|e| Finish {
bb643c25 Andy McCall ↶ 234
                        exit_code: None,
235
                        duration_ms: 0,
236
                        receipt: None,
47c1d64d Andy McCall ↶ 237
                        signed_receipt: None,
bb643c25 Andy McCall ↶ 238
                        error: Some(format!("{e:#}")),
239
                    });
240
                    eprintln!(
241
                        "job {id}: exit {:?}{}",
242
                        finish.exit_code,
243
                        finish.error.as_deref().map(|e| format!(" ({e})")).unwrap_or_default()
244
                    );
245
                    if let Err(e) = hub.finish(id, &finish) {
246
                        eprintln!("job {id}: reporting failed: {e:#}");
247
                    }
248
                    let mut u = used.lock().unwrap();
249
                    u.jobs -= 1;
250
                    u.memory_mib -= mem;
251
                    u.cpus -= cpus;
252
                });
e0918b88 Andy McCall 253
            }
254
            Ok(None) => std::thread::sleep(idle),
255
            Err(e) => {
256
                eprintln!("claim: {e:#}");
257
                std::thread::sleep(idle);
258
                idle = (idle * 2).min(Duration::from_secs(60));
259
            }
260
        }
bb643c25 Andy McCall ↶ 261
    })
e0918b88 Andy McCall 262
}
263
264
/// Batches records to the hub every second (or every 200 lines).
265
struct LogSink<'a> {
266
    hub: &'a Hub,
267
    job: i64,
268
    buf: Vec<Record>,
269
    last: Instant,
270
}
271
272
impl LogSink<'_> {
273
    fn push(&mut self, mut r: Record) {
274
        if r.text.len() > MAX_RECORD_TEXT {
275
            let mut cut = MAX_RECORD_TEXT;
276
            while !r.text.is_char_boundary(cut) {
277
                cut -= 1;
278
            }
279
            r.text.truncate(cut);
280
        }
281
        self.buf.push(r);
282
        if self.buf.len() >= 200 || self.last.elapsed() >= Duration::from_secs(1) {
283
            self.flush();
284
        }
285
    }
286
287
    fn flush(&mut self) {
288
        if !self.buf.is_empty() {
289
            if let Err(e) = self.hub.log(self.job, std::mem::take(&mut self.buf)) {
290
                eprintln!("job {}: log: {e:#}", self.job);
291
            }
292
        }
293
        self.last = Instant::now();
294
    }
295
}
bb643c25 Andy McCall ↶ 296
297
/// Held while a job's workspace is prepared (see `run_claim`).
298
static PREPARE: std::sync::Mutex<()> = std::sync::Mutex::new(());
e0918b88 Andy McCall 299
47c1d64d Andy McCall ↶ 300
fn run_claim(home: &Home, hub: &Hub, cfg: &RunnerConfig, key: &RunnerKey, claim: &Claim) -> Result<Finish> {
e0918b88 Andy McCall 301
    let started = Instant::now();
302
    let mut sink = LogSink { hub, job: claim.job_id, buf: Vec::new(), last: Instant::now() };
303
    let note =
304
        |sink: &mut LogSink, text: String| sink.push(Record { t: started.elapsed().as_millis() as u64, stream: "flow".into(), text });
305
    let heads: Vec<ChangeHash> = claim.heads.iter().map(|h| ChangeHash::from_hex(h).context("bad head")).collect::<Result<_>>()?;
306
    note(&mut sink, format!("fetching {} for state {}", claim.repo, claim.heads.iter().map(|h| &h[..12]).collect::<Vec<_>>().join("+")));
bb643c25 Andy McCall ↶ 307
    // Preparing a workspace (the cached repositories, the export, the
308
    // image) is one job at a time: fetches into a cached repository must not
309
    // overlap, and the first clone passes its token through the process
310
    // environment. Only the microVMs run side by side.
311
    let mut preparing = Some(PREPARE.lock().unwrap_or_else(|p| p.into_inner()));
e0918b88 Andy McCall 312
    let repo = cached_repo(home, cfg, claim)?;
313
    let scratch = home.root.join("work").join(format!("job-{}", claim.job_id));
314
    let _ = std::fs::remove_dir_all(&scratch);
315
    std::fs::create_dir_all(scratch.join("tree"))?;
316
    let result = (|| -> Result<Finish> {
c23d5191 Andy McCall ↶ 317
        let mut files = workspace::export_state(&repo, &heads, &scratch.join("tree"))?;
318
        // Pinned subrepos (Oxygen spec §7.8), at their paths, as part of the
319
        // workspace and of the scope hash.
320
        for sub in &claim.subrepos {
321
            if sub.path.split('/').any(|p| p.is_empty() || p == "." || p == ".." || p == ".oxy") {
322
                bail!("subrepo path {:?} is not a clean relative path", sub.path);
323
            }
324
            note(
325
                &mut sink,
326
                format!(
327
                    "fetching subrepo {} at {} for {}",
328
                    sub.repo,
329
                    sub.heads.iter().map(|h| &h[..12]).collect::<Vec<_>>().join("+"),
330
                    sub.path
331
                ),
332
            );
333
            let sub_repo = cached_repo_at(home, cfg, &sub.repo, &sub.clone_url, &claim.token)?;
334
            let sub_heads: Vec<ChangeHash> =
335
                sub.heads.iter().map(|h| ChangeHash::from_hex(h).context("bad subrepo head")).collect::<Result<_>>()?;
336
            let dir = scratch.join("tree").join(&sub.path);
337
            std::fs::create_dir_all(&dir)?;
338
            let sub_files = workspace::export_state(&sub_repo, &sub_heads, &dir)?;
339
            files.extend(sub_files.into_iter().map(|(p, h)| (format!("{}/{p}", sub.path), h)));
340
        }
e0918b88 Andy McCall 341
        let scope_hash = scope_tree_hash(&claim.job.scope, files.iter().map(|(p, h)| (p.as_str(), *h)));
342
        workspace::image(&scratch.join("tree"), &scratch.join("workspace.ext4"))?;
343
        std::fs::remove_dir_all(scratch.join("tree"))?;
bb643c25 Andy McCall ↶ 344
        preparing.take();
e0918b88 Andy McCall 345
        note(
346
            &mut sink,
347
            format!(
348
                "booting a microVM: {} vCPU, {} MiB, rootfs {}",
349
                claim.sandbox.cpus,
350
                claim.sandbox.memory_mib,
351
                &claim.sandbox.rootfs[..12]
352
            ),
353
        );
a72abeee Andy McCall ↶ 354
        let job = claim.job.in_sandbox(&claim.sandbox).with_flow_env(&claim.flow_env());
e0918b88 Andy McCall 355
        let outcome = microvm::run(
356
            home,
357
            &claim.sandbox,
c4285535 Andy McCall ↶ 358
            &job,
e0918b88 Andy McCall 359
            &scratch.join("workspace.ext4"),
360
            &scratch,
361
            Duration::from_secs(claim.timeout_s),
362
            &mut |r| sink.push(r),
363
        )?;
a67b97e9 Andy McCall ↶ 364
        // A passing job's artifacts, read from its disks and uploaded; a
365
        // declared artifact that cannot be kept fails the job.
366
        let mut outputs = vec![];
367
        let mut output_error = None;
368
        if outcome.exit_code == Some(0) {
369
            for o in &claim.job.outputs {
370
                let (image, inner) = crate::outputs::locate(&claim.job, &scratch.join("workspace.ext4"), &scratch, &o.path);
371
                let kept = crate::outputs::read(&image, &inner, &scratch).and_then(|bytes| {
372
                    let blob = Repo::blob_ref(&bytes);
373
                    let named = hub.artifact(claim.job_id, &o.name, &bytes)?;
374
                    if named != blob.to_hex() {
375
                        bail!("the hub kept it as {named}, not {}", blob.to_hex());
376
                    }
377
                    note(&mut sink, format!("artifact {}: {} bytes, blob {}", o.name, bytes.len(), &named[..12]));
378
                    Ok(blob.0)
379
                });
380
                match kept {
381
                    Ok(b) => outputs.push(b),
382
                    Err(e) => {
383
                        output_error = Some(format!("artifact {}: {e:#}", o.name));
384
                        break;
385
                    }
386
                }
387
            }
388
        }
389
        if let Some(e) = &output_error {
390
            note(&mut sink, e.clone());
391
        }
392
        let receipt = outcome.exit_code.filter(|_| output_error.is_none()).map(|code| Receipt {
e0918b88 Andy McCall 393
            job_name: claim.job.name.clone(),
394
            pipeline_hash: hex32(&claim.pipeline_hash),
395
            scope_tree_hash: scope_hash,
396
            inputs: vec![],
397
            environment: outcome.environment.hash(),
a67b97e9 Andy McCall ↶ 398
            outputs,
e0918b88 Andy McCall 399
            exit_code: code as u32,
400
            duration_ms: outcome.duration_ms,
401
        });
47c1d64d Andy McCall ↶ 402
        let signed_receipt = match &receipt {
403
            Some(r) => Some(hex::encode(sign_receipt(&repo, &heads, cfg, key, claim, r)?.encode())),
404
            None => None,
405
        };
e0918b88 Andy McCall 406
        Ok(Finish {
407
            exit_code: outcome.exit_code,
408
            duration_ms: started.elapsed().as_millis() as u64,
409
            receipt,
47c1d64d Andy McCall ↶ 410
            signed_receipt,
a67b97e9 Andy McCall ↶ 411
            error: output_error.or_else(|| outcome.timed_out.then(|| "stopped at the time limit".to_string())),
e0918b88 Andy McCall 412
        })
413
    })();
414
    let _ = std::fs::remove_dir_all(&scratch);
415
    sink.flush();
416
    result
47c1d64d Andy McCall ↶ 417
}
418
419
/// Bind `receipt` to the state of `heads` in `repo` and sign it as the
420
/// runner (Oxygen spec §14.6). The state is computed here, not taken from
421
/// the claim, so the runner vouches only for what it fetched.
422
fn sign_receipt(
423
    repo: &Repo,
424
    heads: &[ChangeHash],
425
    cfg: &RunnerConfig,
426
    key: &RunnerKey,
427
    claim: &Claim,
428
    receipt: &Receipt,
429
) -> Result<oxy_core::receipt::SignedReceipt> {
430
    let state = state_of(heads);
431
    let run = format!("{}/{}/flow/{}", cfg.hub.trim_end_matches('/'), claim.repo, claim.run_number);
432
    Ok(oxy_core::receipt::SignedReceipt::sign(receipt.to_oxy(), repo.id()?, state, &run, &key.identity, &key.secret))
433
}
434
435
/// The ObjectRef of the state whose heads are `heads` (Oxygen spec §10.1).
436
pub fn state_of(heads: &[ChangeHash]) -> oxy_core::hash::ObjectRef {
437
    use oxy_core::hash::{hash_object, ObjectType};
438
    hash_object(ObjectType::State, &oxy_core::objects::StateObject::new(heads.to_vec()).encode())
e0918b88 Andy McCall 439
}
440
441
fn hex32(s: &str) -> [u8; 32] {
442
    let mut out = [0; 32];
443
    if let Ok(v) = hex::decode(s) {
444
        if v.len() == 32 {
445
            out.copy_from_slice(&v);
446
        }
447
    }
448
    out
449
}
450
451
/// The runner's copy of a repository, fetched up to date with the job's token.
452
fn cached_repo(home: &Home, cfg: &RunnerConfig, claim: &Claim) -> Result<Repo> {
c23d5191 Andy McCall ↶ 453
    cached_repo_at(home, cfg, &claim.repo, &claim.clone_url, &claim.token)
454
}
455
456
/// The runner's copy of `repo`, cloned or fetched with `token`.
457
fn cached_repo_at(home: &Home, cfg: &RunnerConfig, repo_name: &str, clone_url: &str, token: &str) -> Result<Repo> {
458
    let dir: PathBuf = home.root.join("repos").join(repo_name.replace('/', "__"));
e0918b88 Andy McCall 459
    let set_remote = |repo: &mut Repo| -> Result<()> {
c23d5191 Andy McCall ↶ 460
        repo.config.set("remote.origin.url", clone_url).map_err(|e| anyhow::anyhow!("{e}"))?;
461
        repo.config.set("remote.origin.token", token).map_err(|e| anyhow::anyhow!("{e}"))?;
e0918b88 Andy McCall 462
        if let Some(ca) = &cfg.ca {
463
            repo.config.set("remote.origin.ca", &ca.to_string_lossy()).map_err(|e| anyhow::anyhow!("{e}"))?;
464
        }
465
        repo.save_config().map_err(|e| anyhow::anyhow!("{e}"))
466
    };
467
    if dir.join(".oxy").is_dir() {
468
        let mut repo = Repo::open(&dir).map_err(|e| anyhow::anyhow!("{e}"))?;
469
        set_remote(&mut repo)?;
c23d5191 Andy McCall ↶ 470
        repo.fetch("origin").map_err(|e| anyhow::anyhow!("fetch {clone_url}: {e}"))?;
e0918b88 Andy McCall 471
        return Ok(repo);
472
    }
473
    // First job for this repository: clone with the job's token.
c23d5191 Andy McCall ↶ 474
    std::env::set_var("OXY_TOKEN", token);
e0918b88 Andy McCall 475
    if let Some(ca) = &cfg.ca {
476
        std::env::set_var("OXY_CA", ca);
477
    }
c23d5191 Andy McCall ↶ 478
    let cloned = Repo::clone(clone_url, &dir);
e0918b88 Andy McCall 479
    std::env::remove_var("OXY_TOKEN");
480
    std::env::remove_var("OXY_CA");
481
    let mut repo = cloned.map_err(|e| {
482
        let _ = std::fs::remove_dir_all(&dir);
c23d5191 Andy McCall ↶ 483
        anyhow::anyhow!("clone {}: {e}", clone_url)
e0918b88 Andy McCall 484
    })?;
485
    set_remote(&mut repo)?;
486
    Ok(repo)
bb643c25 Andy McCall ↶ 487
}
488
489
#[cfg(test)]
490
mod tests {
491
    use super::*;
1b2229da Andy McCall ↶ 492
493
    /// A hub that answers each request with the next of `codes`, counting them.
494
    fn fake_hub(codes: Vec<u16>) -> (String, std::sync::Arc<std::sync::atomic::AtomicUsize>) {
495
        use std::io::{Read, Write};
496
        let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
497
        let addr = listener.local_addr().unwrap();
498
        let seen = std::sync::Arc::new(std::sync::atomic::AtomicUsize::new(0));
499
        let count = seen.clone();
500
        std::thread::spawn(move || {
501
            for code in codes {
502
                let (mut s, _) = listener.accept().unwrap();
f3b4fdeb Andy McCall ↶ 503
                // Read the whole request (headers, then Content-Length bytes
504
                // of body) before answering: closing early would reset the
505
                // connection while the client is still sending.
506
                let mut req = Vec::new();
1b2229da Andy McCall ↶ 507
                let mut buf = [0u8; 8192];
f3b4fdeb Andy McCall ↶ 508
                loop {
509
                    let n = s.read(&mut buf).unwrap_or(0);
510
                    if n == 0 {
511
                        break;
512
                    }
513
                    req.extend_from_slice(&buf[..n]);
514
                    let text = String::from_utf8_lossy(&req);
515
                    if let Some(end) = text.find("\r\n\r\n") {
516
                        let len = text[..end]
517
                            .lines()
518
                            .find_map(|l| {
519
                                l.to_ascii_lowercase().strip_prefix("content-length:").map(|v| v.trim().parse::<usize>().unwrap_or(0))
520
                            })
521
                            .unwrap_or(0);
522
                        if req.len() >= end + 4 + len {
523
                            break;
524
                        }
525
                    }
526
                }
1b2229da Andy McCall ↶ 527
                count.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
528
                let reason = if code == 204 { "No Content" } else { "Error" };
529
                let _ = write!(s, "HTTP/1.1 {code} {reason}\r\nContent-Length: 0\r\nConnection: close\r\n\r\n");
530
            }
531
        });
532
        (format!("http://{addr}"), seen)
f98a8f78 Andy McCall ↶ 533
    }
534
535
    /// A hub that answers one request with `body` (status 200) and hands
536
    /// back what it was sent.
537
    fn fake_json_hub(body: &'static str) -> (String, std::sync::mpsc::Receiver<String>) {
538
        use std::io::{Read, Write};
539
        let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
540
        let addr = listener.local_addr().unwrap();
541
        let (tx, rx) = std::sync::mpsc::channel();
542
        std::thread::spawn(move || {
543
            let (mut s, _) = listener.accept().unwrap();
544
            let mut req = Vec::new();
545
            let mut buf = [0u8; 65536];
546
            loop {
547
                let n = s.read(&mut buf).unwrap_or(0);
548
                if n == 0 {
549
                    break;
550
                }
551
                req.extend_from_slice(&buf[..n]);
552
                let text = String::from_utf8_lossy(&req);
553
                if let Some(end) = text.find("\r\n\r\n") {
554
                    let len = text[..end]
555
                        .lines()
556
                        .find_map(|l| {
557
                            l.to_ascii_lowercase().strip_prefix("content-length:").map(|v| v.trim().parse::<usize>().unwrap_or(0))
558
                        })
559
                        .unwrap_or(0);
560
                    if req.len() >= end + 4 + len {
561
                        break;
562
                    }
563
                }
564
            }
565
            tx.send(String::from_utf8_lossy(&req).into_owned()).unwrap();
566
            let _ = write!(
567
                s,
568
                "HTTP/1.1 200 OK\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{body}",
569
                body.len()
570
            );
571
        });
572
        (format!("http://{addr}"), rx)
573
    }
574
575
    #[test]
576
    fn registering_binds_the_key_and_keeps_the_credential_private() {
577
        use std::os::unix::fs::PermissionsExt;
578
        let dir = tempfile::tempdir().unwrap();
579
        let home = Home::locate(Some(dir.path())).unwrap();
580
        let (hub, sent) = fake_json_hub(r#"{"id":7,"name":"plex","credential":"flowrunner_secret"}"#);
581
        let got = register(&home, &hub, " reg-token ", "plex", None, vec!["gpu".into()]).unwrap();
582
        assert_eq!((got.id, got.name.as_str()), (7, "plex"));
583
        let req = sent.recv().unwrap();
584
        assert!(req.starts_with("POST /api/v1/flow/runners/register"), "{req}");
585
        let body: Register = serde_json::from_str(&req[req.find("\r\n\r\n").unwrap() + 4..]).unwrap();
586
        assert_eq!((body.token.as_str(), body.info.labels.clone()), ("reg-token", vec!["gpu".to_string()]));
587
        let key = home.runner_key("plex").unwrap();
588
        assert_eq!(body.identity, hex::encode(key.identity.encode()), "the runner's signing identity");
589
        let path = dir.path().join(crate::home::RUNNER_TOML);
590
        assert_eq!(std::fs::metadata(&path).unwrap().permissions().mode() & 0o777, 0o600);
591
        // The runner then starts from runner.toml.
592
        let again = Home::locate(Some(dir.path())).unwrap();
593
        let cfg = again.config.runner.unwrap();
594
        assert_eq!((cfg.hub.as_str(), cfg.token.as_str(), cfg.name.as_deref()), (hub.as_str(), "flowrunner_secret", Some("plex")));
595
        assert_eq!(cfg.labels, ["gpu"]);
1b2229da Andy McCall ↶ 596
    }
597
598
    fn hub_at(base: String) -> Hub {
599
        Hub { base, token: "t".into(), agent: ureq::AgentBuilder::new().timeout(Duration::from_secs(5)).build() }
600
    }
601
602
    #[test]
603
    fn server_errors_are_tried_again_and_client_errors_are_not() {
604
        let quick = [Duration::from_millis(10); 3];
605
        let (base, seen) = fake_hub(vec![500, 503, 204]);
606
        let r = hub_at(base).post_with("/flow/jobs/1/log", &serde_json::json!({}), &quick).unwrap();
607
        assert!(r.is_none());
608
        assert_eq!(seen.load(std::sync::atomic::Ordering::SeqCst), 3, "two retries, then accepted");
609
610
        let (base, seen) = fake_hub(vec![500, 500, 500, 500]);
611
        let e = hub_at(base).post_with("/flow/claim", &serde_json::json!({}), &quick).unwrap_err().to_string();
612
        assert!(e.contains("HTTP 500"), "{e}");
613
        assert_eq!(seen.load(std::sync::atomic::Ordering::SeqCst), 4, "gives up after the last delay");
614
615
        let (base, seen) = fake_hub(vec![401]);
616
        assert!(hub_at(base).post_with("/flow/claim", &serde_json::json!({}), &quick).is_err());
617
        assert_eq!(seen.load(std::sync::atomic::Ordering::SeqCst), 1, "a refusal is final");
618
    }
bb643c25 Andy McCall ↶ 619
620
    #[test]
621
    fn the_budget_admits_jobs_that_fit() {
622
        let b = Budget { max_jobs: 3, memory_mib: Some(24_576), cpus: Some(8) };
623
        let used = |jobs, memory_mib, cpus| Used { jobs, memory_mib, cpus };
624
        assert_eq!(b.room(used(0, 0, 0)), Some((None, None)), "a lone job may take everything");
625
        assert_eq!(b.room(used(1, 8192, 4)), Some((Some(16_384), Some(4))));
626
        assert_eq!(b.room(used(2, 16_384, 8)), None, "no vCPU left");
627
        assert_eq!(b.room(used(3, 1024, 1)), None, "at max_jobs");
628
        let one = Budget { max_jobs: 1, memory_mib: None, cpus: None };
629
        assert_eq!(one.room(used(0, 0, 0)), Some((None, None)));
630
        assert_eq!(one.room(used(1, 0, 0)), None, "the default runs one job at a time");
631
        let open = Budget { max_jobs: 2, memory_mib: None, cpus: None };
632
        assert_eq!(open.room(used(1, 8192, 4)), Some((None, None)), "no limits configured");
633
    }
e0918b88 Andy McCall 634
}