OXYGENHUB
◆ v0.9.1 oxygenhub / crates / hub / src / web / runners.rs
26.9 KiB · Rust · last changed Flow priorities: an organisation's level, and a cap on expedited runs 19 days ago source blame history raw
b6b7e4cf Andy McCall ↶ 1
//! Admin → Runners (hub spec §13.2): the OxygenFlow runners of this hub,
2
//! what they are and are running, their history, registration tokens, and
3
//! draining, disabling and removing them.
4
5
use super::settings::csrf;
6
use super::{filters, Error, Page, Shell};
7
use crate::auth::Viewer;
8
use crate::db::{self, accounts, runners};
9
use crate::Shared;
10
use askama::Template;
11
use axum::extract::{Form, Path, Query, State};
12
use axum::response::{IntoResponse, Redirect, Response};
13
use serde::Deserialize;
14
use std::collections::HashMap;
15
16
fn require_admin(viewer: &Viewer, shell: &Shell) -> Result<accounts::Account, Error> {
17
    match viewer.account() {
18
        Some(a) if a.is_admin => Ok(a.clone()),
19
        _ => Err(Error::not_found(shell.clone())),
20
    }
21
}
22
23
pub struct RunnerRow {
24
    pub r: runners::Runner,
25
    /// Jobs it is running now.
26
    pub running: i64,
74be9796 Andy McCall ↶ 27
    /// The repositories it serves, in words.
28
    pub scope: String,
a46d15e7 Andy McCall ↶ 29
    /// Where its peers reach it in the image swarm, and its site
30
    /// (oxygenhub#144); empty when it is not in one.
31
    pub swarm: String,
e9b9619c Andy McCall ↶ 32
    /// The jobs it runs now: (repository, run, job, started).
33
    pub jobs: Vec<(String, i64, String, Option<i64>)>,
b6b7e4cf Andy McCall ↶ 34
}
35
e9b9619c Andy McCall ↶ 36
impl RunnerRow {
37
    /// What it is doing (oxygenhub#243): `disabled`, `draining`, `idle`,
38
    /// or `running N of M`.
39
    pub fn doing(&self) -> String {
40
        match self.r.state.as_str() {
41
            "disabled" => "disabled".into(),
42
            "draining" if self.running > 0 => format!("draining, {} left", self.running),
43
            "draining" => "draining".into(),
44
            _ if self.running > 0 => format!("running {} of {}", self.running, self.r.max_jobs),
45
            _ => "idle".into(),
46
        }
47
    }
48
49
    /// The jobs it runs, for the status's tooltip.
50
    pub fn jobs_line(&self) -> String {
51
        let now = crate::db::now_ms();
52
        self.jobs
53
            .iter()
54
            .map(|(repo, run, job, started)| match started {
55
                Some(t) => format!("{repo} #{run} {job}, {} min", (now - t).max(0) / 60_000),
56
                None => format!("{repo} #{run} {job}"),
57
            })
58
            .collect::<Vec<_>>()
59
            .join("; ")
60
    }
61
}
62
63
/// The queue's filters (oxygenhub#243), kept in the URL.
64
#[derive(Deserialize, Default, Clone)]
65
pub struct QueueFilter {
66
    #[serde(default)]
67
    pub repo: String,
68
    #[serde(default)]
69
    pub status: String,
70
    #[serde(default)]
71
    pub runner: String,
72
}
73
74
impl QueueFilter {
75
    fn keeps(&self, q: &db::flow::QueueEntry) -> bool {
76
        (self.repo.is_empty() || format!("{}/{}", q.owner, q.name) == self.repo)
77
            && (self.status.is_empty() || q.status == self.status)
78
            && (self.runner.is_empty() || q.runner == self.runner)
79
    }
80
81
    pub fn any(&self) -> bool {
82
        !(self.repo.is_empty() && self.status.is_empty() && self.runner.is_empty())
83
    }
84
}
85
74be9796 Andy McCall ↶ 86
/// A scope in words: the whole site, an owner's repositories, or one
87
/// repository.
88
async fn scope_words(app: &Shared, s: &runners::Scope) -> String {
89
    match s.repo_id {
90
        Some(id) => match db::repos::get_by_id(&app.db, id).await.ok().flatten() {
91
            Some(r) => format!("{}/{}", r.owner, r.name),
92
            None => "a removed repository".into(),
93
        },
94
        None if s.owner.is_empty() => "the whole site".into(),
95
        None => format!("{}'s repositories", s.owner),
96
    }
97
}
98
99
/// A scope as typed: empty for the whole site, an owner, or
100
/// `owner/repository`.
101
async fn parse_scope(app: &Shared, text: &str) -> Result<runners::Scope, String> {
102
    let text = text.trim().trim_matches('/');
103
    if text.is_empty() {
104
        return Ok(runners::Scope::default());
105
    }
106
    if let Some((owner, name)) = text.split_once('/') {
107
        return match db::repos::get(&app.db, owner, name).await {
108
            Ok(Some(r)) => Ok(runners::Scope { owner: r.owner.clone(), repo_id: Some(r.id) }),
109
            _ => Err(format!("There is no repository {text}.")),
110
        };
111
    }
112
    let user = accounts::account_by_name(&app.db, text).await.ok().flatten().is_some();
113
    let org = accounts::org_by_name(&app.db, text).await.ok().flatten().is_some();
114
    if user || org {
115
        Ok(runners::Scope { owner: text.to_string(), repo_id: None })
116
    } else {
117
        Err(format!("There is no user or organisation {text}."))
118
    }
119
}
120
b6b7e4cf Andy McCall ↶ 121
#[derive(Template)]
122
#[template(path = "admin_runners.html")]
123
pub struct RunnersPage {
124
    shell: Shell,
125
    runners: Vec<RunnerRow>,
126
    /// Registration tokens waiting to be used: (created by, created, expires).
127
    pending: Vec<(String, i64, i64)>,
128
    /// A token just made, shown once, with the command that uses it.
129
    new_token: Option<String>,
130
    hub: String,
131
    notice: Option<String>,
132
    error: Option<String>,
e9b9619c Andy McCall ↶ 133
    /// Running jobs, then queued ones in the order runners claim them,
134
    /// as the filter keeps them.
b66e70b7 Andy McCall ↶ 135
    queue: Vec<db::flow::QueueEntry>,
e9b9619c Andy McCall ↶ 136
    /// How many there are, unfiltered.
137
    queue_total: usize,
138
    filter: QueueFilter,
139
    /// The repositories and runners in the queue, for the filter's choices.
140
    queue_repos: Vec<String>,
141
    queue_runners: Vec<String>,
b6b7e4cf Andy McCall ↶ 142
}
143
144
async fn page(
145
    app: &Shared,
146
    shell: Shell,
147
    new_token: Option<String>,
148
    notice: Option<String>,
149
    error: Option<String>,
150
) -> Result<Page<RunnersPage>, Error> {
e9b9619c Andy McCall ↶ 151
    page_filtered(app, shell, new_token, notice, error, QueueFilter::default()).await
152
}
153
154
async fn page_filtered(
155
    app: &Shared,
156
    shell: Shell,
157
    new_token: Option<String>,
158
    notice: Option<String>,
159
    error: Option<String>,
160
    filter: QueueFilter,
161
) -> Result<Page<RunnersPage>, Error> {
b6b7e4cf Andy McCall ↶ 162
    let e = |e| Error::from_db(shell.clone(), e);
163
    let list = runners::list(&app.db).await.map_err(e)?;
164
    let running: HashMap<i64, i64> = runners::running(&app.db).await.map_err(e)?.into_iter().collect();
165
    let pending = runners::pending_registrations(&app.db).await.map_err(e)?;
e9b9619c Andy McCall ↶ 166
    let all = db::flow::queue(&app.db).await.map_err(e)?;
74be9796 Andy McCall ↶ 167
    let mut rows = Vec::with_capacity(list.len());
168
    for r in list {
169
        let scope = scope_words(app, &r.scope()).await;
a46d15e7 Andy McCall ↶ 170
        let swarm = app
171
            .swarm
172
            .addr(r.id)
173
            .map(|s| if s.site.is_empty() { s.addr } else { format!("{} · site {}", s.addr, s.site) })
174
            .unwrap_or_default();
e9b9619c Andy McCall ↶ 175
        let jobs = all
176
            .iter()
177
            .filter(|q| q.status == "running" && q.runner == r.name)
178
            .map(|q| (format!("{}/{}", q.owner, q.name), q.run_number, q.job.clone(), q.started_ms))
179
            .collect();
180
        rows.push(RunnerRow { running: running.get(&r.id).copied().unwrap_or(0), scope, swarm, jobs, r });
74be9796 Andy McCall ↶ 181
    }
e9b9619c Andy McCall ↶ 182
    let mut queue_repos: Vec<String> = all.iter().map(|q| format!("{}/{}", q.owner, q.name)).collect();
183
    queue_repos.sort();
184
    queue_repos.dedup();
185
    let mut queue_runners: Vec<String> = all.iter().filter(|q| !q.runner.is_empty()).map(|q| q.runner.clone()).collect();
186
    queue_runners.sort();
187
    queue_runners.dedup();
188
    let queue_total = all.len();
189
    let queue = all.into_iter().filter(|q| filter.keeps(q)).collect();
190
    Ok(Page(RunnersPage {
191
        hub: app.config.base_url().to_string(),
192
        shell,
193
        runners: rows,
194
        pending,
195
        new_token,
196
        notice,
197
        error,
198
        queue,
199
        queue_total,
200
        filter,
201
        queue_repos,
202
        queue_runners,
203
    }))
b6b7e4cf Andy McCall ↶ 204
}
205
206
/// `GET /admin/runners`.
e9b9619c Andy McCall ↶ 207
pub async fn list(State(app): State<Shared>, viewer: Viewer, Query(filter): Query<QueueFilter>) -> Result<Page<RunnersPage>, Error> {
b6b7e4cf Andy McCall ↶ 208
    let shell = Shell::new(&app, "/admin/runners", &viewer);
209
    require_admin(&viewer, &shell)?;
e9b9619c Andy McCall ↶ 210
    page_filtered(&app, shell, None, None, None, filter).await
b6b7e4cf Andy McCall ↶ 211
}
212
213
#[derive(Deserialize)]
214
pub struct CsrfOnly {
74be9796 Andy McCall ↶ 215
    #[serde(rename = "_csrf")]
216
    csrf_token: String,
217
}
218
219
#[derive(Deserialize)]
220
pub struct ScopeForm {
b6b7e4cf Andy McCall ↶ 221
    #[serde(rename = "_csrf")]
222
    csrf_token: String,
74be9796 Andy McCall ↶ 223
    /// Empty for the whole site, an owner, or `owner/repository`.
224
    #[serde(default)]
225
    scope: String,
b6b7e4cf Andy McCall ↶ 226
}
227
74be9796 Andy McCall ↶ 228
/// `POST /admin/runners/token`: a one-time registration token, shown once,
229
/// for a runner of the scope given.
230
pub async fn new_token(State(app): State<Shared>, viewer: Viewer, Form(f): Form<ScopeForm>) -> Result<Page<RunnersPage>, Error> {
b6b7e4cf Andy McCall ↶ 231
    let shell = Shell::new(&app, "/admin/runners", &viewer);
232
    let me = require_admin(&viewer, &shell)?;
233
    csrf(&viewer, &f.csrf_token, &shell)?;
74be9796 Andy McCall ↶ 234
    let scope = match parse_scope(&app, &f.scope).await {
235
        Ok(s) => s,
236
        Err(e) => return page(&app, shell, None, None, Some(e)).await,
237
    };
b6b7e4cf Andy McCall ↶ 238
    let token = format!("flowreg_{}", crate::auth::random_hex(24));
74be9796 Andy McCall ↶ 239
    runners::add_registration(&app.db, &blake3::hash(token.as_bytes()).to_hex(), &me.username, &scope)
b6b7e4cf Andy McCall ↶ 240
        .await
241
        .map_err(|e| Error::from_db(shell.clone(), e))?;
74be9796 Andy McCall ↶ 242
    let words = scope_words(&app, &scope).await;
243
    accounts::audit(&app.db, Some(&me), "flow.runner.token", "", &format!("registration token created for {words}")).await.ok();
244
    page(&app, shell, Some(token), Some(format!("The runner it registers will take jobs from {words}.")), None).await
245
}
246
247
/// `POST /admin/runners/{id}/scope`: change the repositories a runner serves.
248
pub async fn set_scope(
249
    State(app): State<Shared>,
250
    viewer: Viewer,
251
    Path(id): Path<i64>,
252
    Form(f): Form<ScopeForm>,
253
) -> Result<Page<RunnersPage>, Error> {
254
    let shell = Shell::new(&app, "/admin/runners", &viewer);
255
    let me = require_admin(&viewer, &shell)?;
256
    csrf(&viewer, &f.csrf_token, &shell)?;
257
    let r =
258
        runners::get(&app.db, id).await.map_err(|e| Error::from_db(shell.clone(), e))?.ok_or_else(|| Error::not_found(shell.clone()))?;
259
    let scope = match parse_scope(&app, &f.scope).await {
260
        Ok(s) => s,
261
        Err(e) => return page(&app, shell, None, None, Some(e)).await,
262
    };
263
    runners::set_scope(&app.db, id, &scope).await.map_err(|e| Error::from_db(shell.clone(), e))?;
264
    let words = scope_words(&app, &scope).await;
265
    accounts::audit(&app.db, Some(&me), "flow.runner.scope", &r.name, &words).await.ok();
266
    page(&app, shell, None, Some(format!("{} now takes jobs from {words}.", r.name)), None).await
b6b7e4cf Andy McCall ↶ 267
}
268
269
#[derive(Deserialize)]
7f5f6c05 Andy McCall ↶ 270
pub struct LimitsForm {
271
    #[serde(rename = "_csrf")]
272
    csrf_token: String,
273
    /// Comma-separated.
274
    #[serde(default)]
275
    labels: String,
276
    /// Minutes; empty for the site's limit.
277
    #[serde(default)]
278
    timeout_minutes: String,
279
}
280
281
/// `POST /admin/runners/{id}/limits`: the labels an administrator gives a
282
/// runner and its own job time limit (#98).
283
pub async fn set_limits(
284
    State(app): State<Shared>,
285
    viewer: Viewer,
286
    Path(id): Path<i64>,
287
    Form(f): Form<LimitsForm>,
288
) -> Result<Response, Error> {
289
    let shell = Shell::new(&app, &format!("/admin/runners/{id}"), &viewer);
290
    let me = require_admin(&viewer, &shell)?;
291
    csrf(&viewer, &f.csrf_token, &shell)?;
292
    let r =
293
        runners::get(&app.db, id).await.map_err(|e| Error::from_db(shell.clone(), e))?.ok_or_else(|| Error::not_found(shell.clone()))?;
294
    let mut labels: Vec<String> = Vec::new();
295
    for l in f.labels.split([',', ' ']).map(str::trim).filter(|l| !l.is_empty()) {
296
        if !l.chars().all(|c| c.is_ascii_alphanumeric() || matches!(c, '-' | '_' | '.')) || l.len() > 40 {
297
            return Err(Error::bad(shell, format!("label {l:?}: letters, digits, - _ and . only, up to 40 characters")));
298
        }
299
        if !labels.iter().any(|x| x == l) {
300
            labels.push(l.to_string());
301
        }
302
    }
303
    let timeout = match f.timeout_minutes.trim() {
304
        "" => None,
305
        t => match t.parse::<i64>() {
306
            Ok(m) if (1..=24 * 60).contains(&m) => Some(m),
307
            _ => return Err(Error::bad(shell, "a time limit is a whole number of minutes from 1 to 1440")),
308
        },
309
    };
310
    runners::set_limits(&app.db, id, &labels.join(","), timeout).await.map_err(|e| Error::from_db(shell.clone(), e))?;
311
    let words = format!(
312
        "labels {}; time limit {}",
313
        if labels.is_empty() { "none".to_string() } else { labels.join(", ") },
314
        timeout.map(|m| format!("{m} min")).unwrap_or_else(|| "the site's".into())
315
    );
316
    accounts::audit(&app.db, Some(&me), "flow.runner.limits", &r.name, &words).await.ok();
317
    Ok(Redirect::to(&format!("/admin/runners/{id}")).into_response())
318
}
319
320
#[derive(Deserialize)]
b6b7e4cf Andy McCall ↶ 321
pub struct StateForm {
322
    #[serde(rename = "_csrf")]
323
    csrf_token: String,
324
    /// `active`, `draining` or `disabled`.
325
    state: String,
326
}
327
328
/// `POST /admin/runners/{id}/state`: drain, disable or resume a runner.
329
pub async fn set_state(
330
    State(app): State<Shared>,
331
    viewer: Viewer,
332
    Path(id): Path<i64>,
333
    Form(f): Form<StateForm>,
334
) -> Result<Response, Error> {
335
    let shell = Shell::new(&app, "/admin/runners", &viewer);
336
    let me = require_admin(&viewer, &shell)?;
337
    csrf(&viewer, &f.csrf_token, &shell)?;
338
    if !matches!(f.state.as_str(), "active" | "draining" | "disabled") {
339
        return Err(Error::bad(shell, "a runner is active, draining or disabled"));
340
    }
341
    let r =
342
        runners::get(&app.db, id).await.map_err(|e| Error::from_db(shell.clone(), e))?.ok_or_else(|| Error::not_found(shell.clone()))?;
343
    runners::set_state(&app.db, id, &f.state).await.map_err(|e| Error::from_db(shell.clone(), e))?;
344
    accounts::audit(&app.db, Some(&me), "flow.runner.state", &r.name, &f.state).await.ok();
345
    Ok(Redirect::to("/admin/runners").into_response())
346
}
347
348
/// `POST /admin/runners/{id}/remove`: forget a runner that runs nothing.
349
pub async fn remove(
350
    State(app): State<Shared>,
351
    viewer: Viewer,
352
    Path(id): Path<i64>,
353
    Form(f): Form<CsrfOnly>,
354
) -> Result<Page<RunnersPage>, Error> {
355
    let shell = Shell::new(&app, "/admin/runners", &viewer);
356
    let me = require_admin(&viewer, &shell)?;
357
    csrf(&viewer, &f.csrf_token, &shell)?;
358
    let e = |e| Error::from_db(shell.clone(), e);
359
    let r = runners::get(&app.db, id).await.map_err(e)?.ok_or_else(|| Error::not_found(shell.clone()))?;
360
    let busy = runners::running(&app.db).await.map_err(e)?.into_iter().any(|(rid, n)| rid == id && n > 0);
361
    if busy {
362
        return page(
363
            &app,
364
            shell,
365
            None,
366
            None,
367
            Some(format!("{} is running jobs: drain it first, then remove it when they finish.", r.name)),
368
        )
369
        .await;
370
    }
371
    runners::remove(&app.db, id).await.map_err(e)?;
372
    accounts::audit(&app.db, Some(&me), "flow.runner.remove", &r.name, "").await.ok();
373
    let also = if r.source == "config" {
374
        " It is configured in hub.toml; remove its token there too, or it comes back on its next claim."
375
    } else {
376
        ""
377
    };
378
    page(&app, shell, None, Some(format!("Removed {}.{also}", r.name)), None).await
379
}
380
381
#[derive(Template)]
382
#[template(path = "admin_runner.html")]
383
pub struct RunnerPage {
384
    shell: Shell,
385
    r: runners::Runner,
386
    running: i64,
387
    history: Vec<runners::RunnerJob>,
4d2e44d7 Andy McCall ↶ 388
    declines: Vec<crate::db::flow::RunnerDecline>,
b6b7e4cf Andy McCall ↶ 389
    older: Option<i64>,
390
    jobs: i64,
391
    passed: i64,
392
    busy_ms: i64,
393
}
394
395
impl RunnerPage {
396
    /// Time spent running jobs, as pages show durations.
397
    pub fn busy(&self) -> String {
398
        crate::flow::human_ms(self.busy_ms)
399
    }
400
}
401
402
#[derive(Deserialize, Default)]
403
pub struct HistoryQuery {
404
    before: Option<i64>,
405
}
406
407
const PER_PAGE: i64 = 50;
408
409
/// `GET /admin/runners/{id}`: a runner and the jobs it ran.
410
pub async fn show(
411
    State(app): State<Shared>,
412
    viewer: Viewer,
413
    Path(id): Path<i64>,
414
    Query(q): Query<HistoryQuery>,
415
) -> Result<Page<RunnerPage>, Error> {
416
    let shell = Shell::new(&app, &format!("/admin/runners/{id}"), &viewer);
417
    require_admin(&viewer, &shell)?;
418
    let e = |e| Error::from_db(shell.clone(), e);
419
    let r = runners::get(&app.db, id).await.map_err(e)?.ok_or_else(|| Error::not_found(shell.clone()))?;
420
    let mut history = runners::history(&app.db, id, PER_PAGE + 1, q.before).await.map_err(e)?;
421
    let older = (history.len() as i64 > PER_PAGE).then(|| history[PER_PAGE as usize - 1].started_ms).flatten();
422
    history.truncate(PER_PAGE as usize);
423
    let (jobs, passed, busy_ms) = runners::totals(&app.db, id).await.map_err(e)?;
424
    let running = runners::running(&app.db).await.map_err(e)?.into_iter().find(|(rid, _)| *rid == id).map(|(_, n)| n).unwrap_or(0);
4d2e44d7 Andy McCall ↶ 425
    let declines = crate::db::flow::declines_of_runner(&app.db, id, 20).await.map_err(e)?;
426
    Ok(Page(RunnerPage { shell, r, running, history, declines, older, jobs, passed, busy_ms }))
b6b7e4cf Andy McCall ↶ 427
}
428
429
pub fn duration(j: &runners::RunnerJob) -> String {
430
    match (j.started_ms, j.finished_ms) {
431
        (Some(a), Some(b)) => crate::flow::human_ms(b - a),
432
        (Some(a), None) => crate::flow::human_ms(db::now_ms() - a),
433
        _ => "–".into(),
434
    }
435
}
5dead1f4 Andy McCall ↶ 436
437
// ---------------------------------------------------------------- settings
438
439
#[derive(Template)]
440
#[template(path = "admin_runner_settings.html")]
441
pub struct SettingsPage {
442
    shell: Shell,
443
    default_m: u64,
444
    max_m: u64,
445
    grace_m: i64,
446
    /// What hub.toml says, shown beside a setting the page overrides.
447
    file_default_m: u64,
448
    flow_repos: Vec<String>,
107eaba5 Andy McCall ↶ 449
    /// The site's priority for jobs (oxygenhub#244): low, normal or high.
450
    priority: String,
76f93eae Andy McCall ↶ 451
    /// The most expedited runs one owner may have going at once.
452
    expedite_cap: i64,
5dead1f4 Andy McCall ↶ 453
    notice: Option<String>,
454
    error: Option<String>,
455
}
456
457
async fn settings_page(app: &Shared, shell: Shell, notice: Option<String>, error: Option<String>) -> Page<SettingsPage> {
458
    let l = crate::flow::limits(app).await;
459
    Page(SettingsPage {
460
        shell,
461
        default_m: l.default_s / 60,
462
        max_m: l.max_s / 60,
463
        grace_m: l.grace_ms / 60_000,
464
        file_default_m: app.config.flow.job_timeout_minutes,
465
        flow_repos: app.config.flow.repos.clone(),
76f93eae Andy McCall ↶ 466
        expedite_cap: accounts::setting(&app.db, "flow_expedite_cap").await.ok().flatten().and_then(|v| v.parse().ok()).unwrap_or(2),
107eaba5 Andy McCall ↶ 467
        priority: accounts::setting(&app.db, "flow_priority")
468
            .await
469
            .ok()
470
            .flatten()
471
            .filter(|p| !p.is_empty())
472
            .unwrap_or_else(|| "normal".into()),
5dead1f4 Andy McCall ↶ 473
        notice,
474
        error,
475
    })
476
}
477
107eaba5 Andy McCall ↶ 478
#[derive(Deserialize)]
479
pub struct PriorityForm {
480
    #[serde(rename = "_csrf")]
481
    csrf_token: String,
482
    priority: String,
76f93eae Andy McCall ↶ 483
    #[serde(default)]
484
    expedite_cap: Option<String>,
107eaba5 Andy McCall ↶ 485
}
486
487
/// `POST /admin/runners/priority` (oxygenhub#244): the level every job has
488
/// unless its organisation, repository or run says otherwise.
489
pub async fn save_priority(State(app): State<Shared>, viewer: Viewer, Form(f): Form<PriorityForm>) -> Result<Page<SettingsPage>, Error> {
490
    let shell = Shell::new(&app, "/admin/runners/settings", &viewer);
491
    let me = require_admin(&viewer, &shell)?;
492
    csrf(&viewer, &f.csrf_token, &shell)?;
493
    if !["low", "normal", "high"].contains(&f.priority.as_str()) {
494
        return Ok(settings_page(&app, shell, None, Some("Pick low, normal or high (urgent is for expediting one run).".into())).await);
495
    }
76f93eae Andy McCall ↶ 496
    let cap = match f.expedite_cap.as_deref().map(str::trim) {
497
        None | Some("") => None,
498
        Some(v) => match v.parse::<i64>() {
499
            Ok(n) if (0..=100).contains(&n) => Some(n),
500
            _ => return Ok(settings_page(&app, shell, None, Some("The cap is a whole number from 0 to 100.".into())).await),
501
        },
502
    };
107eaba5 Andy McCall ↶ 503
    accounts::set_setting(&app.db, "flow_priority", &f.priority).await.map_err(|e| Error::from_db(shell.clone(), e))?;
76f93eae Andy McCall ↶ 504
    if let Some(n) = cap {
505
        accounts::set_setting(&app.db, "flow_expedite_cap", &n.to_string()).await.map_err(|e| Error::from_db(shell.clone(), e))?;
506
    }
107eaba5 Andy McCall ↶ 507
    accounts::audit(&app.db, Some(&me), "flow.priority", "site", &f.priority).await.ok();
508
    Ok(settings_page(
509
        &app,
510
        shell,
511
        Some(format!("Saved: jobs are {} unless their organisation, repository or run says otherwise.", f.priority)),
512
        None,
513
    )
514
    .await)
515
}
516
5dead1f4 Andy McCall ↶ 517
/// `GET /admin/runners/settings` (oxygenhub#89).
518
pub async fn settings(State(app): State<Shared>, viewer: Viewer) -> Result<Page<SettingsPage>, Error> {
519
    let shell = Shell::new(&app, "/admin/runners/settings", &viewer);
520
    require_admin(&viewer, &shell)?;
521
    Ok(settings_page(&app, shell, None, None).await)
522
}
523
524
#[derive(Deserialize)]
525
pub struct SettingsForm {
526
    #[serde(rename = "_csrf")]
527
    csrf_token: String,
528
    default_minutes: String,
529
    max_minutes: String,
530
    grace_minutes: String,
531
}
532
533
/// `POST /admin/runners/settings`: the site's job time limits.
534
pub async fn save_settings(State(app): State<Shared>, viewer: Viewer, Form(f): Form<SettingsForm>) -> Result<Page<SettingsPage>, Error> {
535
    let shell = Shell::new(&app, "/admin/runners/settings", &viewer);
536
    let me = require_admin(&viewer, &shell)?;
537
    csrf(&viewer, &f.csrf_token, &shell)?;
538
    let num = |v: &str| v.trim().parse::<u64>().ok().filter(|n| *n > 0);
539
    let (Some(d), Some(m), Some(g)) = (num(&f.default_minutes), num(&f.max_minutes), num(&f.grace_minutes)) else {
540
        return Ok(settings_page(&app, shell, None, Some("Each limit is a whole number of minutes, at least 1.".into())).await);
541
    };
542
    if d > m {
543
        return Ok(settings_page(&app, shell, None, Some("The default cannot be longer than the maximum.".into())).await);
544
    }
545
    if m > 24 * 60 {
546
        return Ok(settings_page(&app, shell, None, Some("A job may run for a day at most (1440 minutes).".into())).await);
547
    }
548
    let e = |e| Error::from_db(shell.clone(), e);
549
    accounts::set_setting(&app.db, crate::flow::SETTING_DEFAULT, &d.to_string()).await.map_err(e)?;
550
    accounts::set_setting(&app.db, crate::flow::SETTING_MAX, &m.to_string()).await.map_err(e)?;
551
    accounts::set_setting(&app.db, crate::flow::SETTING_GRACE, &g.to_string()).await.map_err(e)?;
552
    accounts::audit(
553
        &app.db,
554
        Some(&me),
555
        "flow.settings",
556
        "",
557
        &format!("job time limit {d} min by default, {m} min at most; lost after {g} min more"),
558
    )
559
    .await
560
    .ok();
561
    Ok(settings_page(&app, shell, Some("Saved. Jobs claimed from now on run under these limits.".into()), None).await)
562
}
6ca0b971 Andy McCall ↶ 563
564
/// Where one image is: the hub, a runner holding it, or a runner fetching
565
/// it from the swarm now.
566
pub struct Place {
567
    pub name: String,
568
    /// `hub`, `holds` or `fetching`.
569
    pub kind: &'static str,
570
    pub title: String,
571
}
572
573
pub struct ImageRow {
574
    pub hash: String,
575
    pub arch: String,
576
    /// Its size, when the hub keeps it (runners do not say).
577
    pub size: Option<i64>,
578
    pub places: Vec<Place>,
579
    /// Who sent it to the hub, and when.
580
    pub sent: Option<(String, i64)>,
581
    /// Repositories whose jobs ran on it in the last 90 days.
582
    pub uses: Vec<(String, i64, i64)>,
583
    pub last_used: i64,
584
}
585
586
impl ImageRow {
587
    /// Nowhere a job could get it: not on the hub, on no runner.
588
    pub fn stranded(&self) -> bool {
589
        self.places.is_empty()
590
    }
591
}
592
593
#[derive(Template)]
594
#[template(path = "admin_images.html")]
595
pub struct ImagesPage {
596
    shell: Shell,
597
    images: Vec<ImageRow>,
598
    on_hub: usize,
599
    /// Runners in the image swarm, as "name (site)".
600
    swarm: Vec<String>,
6246d1e5 Andy McCall ↶ 601
    /// The swarm backdrop's data (docs/backgrounds.md §2): the hub and the
602
    /// runners, and for each image who holds it and who fetches it now.
603
    backdrop: String,
6ca0b971 Andy McCall ↶ 604
}
605
6246d1e5 Andy McCall ↶ 606
/// The swarm's data, `{scene, nodes: [name], images: [{held, fetching}]}`,
607
/// the hub first, from the page's own rows.
608
fn swarm_json(images: &[ImageRow]) -> String {
609
    let mut nodes: Vec<String> = vec!["hub".into()];
610
    let mut list = Vec::new();
611
    for img in images {
612
        let (mut held, mut fetching) = (Vec::new(), Vec::new());
613
        for p in &img.places {
614
            let i = match p.kind {
615
                "hub" => 0,
616
                _ => match nodes.iter().position(|n| *n == p.name) {
617
                    Some(i) => i,
618
                    None => {
619
                        nodes.push(p.name.clone());
620
                        nodes.len() - 1
621
                    }
622
                },
623
            };
624
            if p.kind == "fetching" {
625
                fetching.push(i);
626
            } else {
627
                held.push(i);
628
            }
629
        }
630
        list.push(serde_json::json!({ "held": held, "fetching": fetching }));
631
    }
632
    serde_json::json!({ "scene": "swarm", "nodes": nodes, "images": list }).to_string().replace('<', "\\u003c")
633
}
634
6ca0b971 Andy McCall ↶ 635
/// `GET /admin/runners/images` (C0, docs/cylinder.md): every runner image,
636
/// where it is and what uses it.
637
pub async fn images(State(app): State<Shared>, viewer: Viewer) -> Result<Page<ImagesPage>, Error> {
638
    let shell = Shell::new(&app, "/admin/runners/images", &viewer);
639
    require_admin(&viewer, &shell)?;
640
    let e = |e| Error::from_db(shell.clone(), e);
641
    let kept = crate::images::kept(&app.db).await.map_err(e)?;
642
    let uses = crate::images::uses(&app.db, db::now_ms() - 90 * 24 * 3600 * 1000).await.map_err(e)?;
643
    let archs = crate::images::reported_archs(&app.db).await.map_err(e)?;
644
    let list = runners::list(&app.db).await.map_err(e)?;
645
    let fetching = app.swarm.fetching_now();
646
    let mut rows: HashMap<String, ImageRow> = HashMap::new();
647
    let row = |rows: &mut HashMap<String, ImageRow>, hash: &str| -> () {
648
        rows.entry(hash.to_ascii_lowercase()).or_insert_with(|| ImageRow {
649
            hash: hash.to_ascii_lowercase(),
650
            arch: archs.get(&hash.to_ascii_lowercase()).cloned().unwrap_or_default(),
651
            size: None,
652
            places: Vec::new(),
653
            sent: None,
654
            uses: Vec::new(),
655
            last_used: 0,
656
        });
657
    };
658
    for k in &kept {
659
        row(&mut rows, &k.hash);
660
        let r = rows.get_mut(&k.hash.to_ascii_lowercase()).expect("added");
661
        r.size = Some(k.size);
662
        if r.arch.is_empty() {
663
            r.arch = k.arch.clone();
664
        }
665
        r.sent = Some((k.uploader.clone(), k.created_ms));
666
        r.places.push(Place { name: "hub".into(), kind: "hub", title: format!("{} chunks kept by the hub", k.chunks) });
667
    }
668
    let mut swarm = Vec::new();
669
    for runner in &list {
670
        if let Some(a) = app.swarm.addr(runner.id) {
671
            swarm.push(if a.site.is_empty() { runner.name.clone() } else { format!("{} ({})", runner.name, a.site) });
672
        }
673
        for h in runner.image_list().unwrap_or_default() {
674
            row(&mut rows, &h);
675
            rows.get_mut(&h.to_ascii_lowercase()).expect("added").places.push(Place {
676
                name: runner.name.clone(),
677
                kind: "holds",
678
                title: format!("{} holds it ({})", runner.name, runner.status()),
679
            });
680
        }
681
    }
682
    for (image, who) in &fetching {
683
        row(&mut rows, image);
684
        for id in who {
685
            if let Some(runner) = list.iter().find(|r| r.id == *id) {
686
                rows.get_mut(image).expect("added").places.push(Place {
687
                    name: runner.name.clone(),
688
                    kind: "fetching",
689
                    title: format!("{} is fetching it from the swarm now", runner.name),
690
                });
691
            }
692
        }
693
    }
694
    for u in uses {
695
        if !jet::images::is_hash(&u.image) {
696
            continue;
697
        }
698
        row(&mut rows, &u.image);
699
        let r = rows.get_mut(&u.image).expect("added");
700
        r.last_used = r.last_used.max(u.last_ms);
701
        r.uses.push((format!("{}/{}", u.owner, u.name), u.jobs, u.last_ms));
702
    }
703
    let mut images: Vec<ImageRow> = rows.into_values().collect();
704
    images.sort_by(|a, b| b.last_used.cmp(&a.last_used).then_with(|| a.hash.cmp(&b.hash)));
705
    let on_hub = kept.len();
6246d1e5 Andy McCall ↶ 706
    let backdrop = swarm_json(&images);
707
    Ok(Page(ImagesPage { shell, images, on_hub, swarm, backdrop }))
6ca0b971 Andy McCall ↶ 708
}