OXYGENHUB
◆ v0.3.0 oxygenhub / crates / hub / src / web / runners.rs
10.5 KiB · Rust · last changed Runners: the queue on Admin → Runners, and the runner API (refs #41, part 4) 1 month ago source blame history raw
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,
27
    /// The repositories it serves, in words.
28
    pub scope: String,
29
}
30
31
/// A scope in words: the whole site, an owner's repositories, or one
32
/// repository.
33
async fn scope_words(app: &Shared, s: &runners::Scope) -> String {
34
    match s.repo_id {
35
        Some(id) => match db::repos::get_by_id(&app.db, id).await.ok().flatten() {
36
            Some(r) => format!("{}/{}", r.owner, r.name),
37
            None => "a removed repository".into(),
38
        },
39
        None if s.owner.is_empty() => "the whole site".into(),
40
        None => format!("{}'s repositories", s.owner),
41
    }
42
}
43
44
/// A scope as typed: empty for the whole site, an owner, or
45
/// `owner/repository`.
46
async fn parse_scope(app: &Shared, text: &str) -> Result<runners::Scope, String> {
47
    let text = text.trim().trim_matches('/');
48
    if text.is_empty() {
49
        return Ok(runners::Scope::default());
50
    }
51
    if let Some((owner, name)) = text.split_once('/') {
52
        return match db::repos::get(&app.db, owner, name).await {
53
            Ok(Some(r)) => Ok(runners::Scope { owner: r.owner.clone(), repo_id: Some(r.id) }),
54
            _ => Err(format!("There is no repository {text}.")),
55
        };
56
    }
57
    let user = accounts::account_by_name(&app.db, text).await.ok().flatten().is_some();
58
    let org = accounts::org_by_name(&app.db, text).await.ok().flatten().is_some();
59
    if user || org {
60
        Ok(runners::Scope { owner: text.to_string(), repo_id: None })
61
    } else {
62
        Err(format!("There is no user or organisation {text}."))
63
    }
64
}
65
66
#[derive(Template)]
67
#[template(path = "admin_runners.html")]
68
pub struct RunnersPage {
69
    shell: Shell,
70
    runners: Vec<RunnerRow>,
71
    /// Registration tokens waiting to be used: (created by, created, expires).
72
    pending: Vec<(String, i64, i64)>,
73
    /// A token just made, shown once, with the command that uses it.
74
    new_token: Option<String>,
75
    hub: String,
76
    notice: Option<String>,
77
    error: Option<String>,
78
    /// Running jobs, then queued ones in the order runners claim them.
79
    queue: Vec<db::flow::QueueEntry>,
80
}
81
82
async fn page(
83
    app: &Shared,
84
    shell: Shell,
85
    new_token: Option<String>,
86
    notice: Option<String>,
87
    error: Option<String>,
88
) -> Result<Page<RunnersPage>, Error> {
89
    let e = |e| Error::from_db(shell.clone(), e);
90
    let list = runners::list(&app.db).await.map_err(e)?;
91
    let running: HashMap<i64, i64> = runners::running(&app.db).await.map_err(e)?.into_iter().collect();
92
    let pending = runners::pending_registrations(&app.db).await.map_err(e)?;
93
    let mut rows = Vec::with_capacity(list.len());
94
    for r in list {
95
        let scope = scope_words(app, &r.scope()).await;
96
        rows.push(RunnerRow { running: running.get(&r.id).copied().unwrap_or(0), scope, r });
97
    }
98
    let queue = db::flow::queue(&app.db).await.map_err(e)?;
99
    Ok(Page(RunnersPage { hub: app.config.base_url().to_string(), shell, runners: rows, pending, new_token, notice, error, queue }))
100
}
101
102
/// `GET /admin/runners`.
103
pub async fn list(State(app): State<Shared>, viewer: Viewer) -> Result<Page<RunnersPage>, Error> {
104
    let shell = Shell::new(&app, "/admin/runners", &viewer);
105
    require_admin(&viewer, &shell)?;
106
    page(&app, shell, None, None, None).await
107
}
108
109
#[derive(Deserialize)]
110
pub struct CsrfOnly {
111
    #[serde(rename = "_csrf")]
112
    csrf_token: String,
113
}
114
115
#[derive(Deserialize)]
116
pub struct ScopeForm {
117
    #[serde(rename = "_csrf")]
118
    csrf_token: String,
119
    /// Empty for the whole site, an owner, or `owner/repository`.
120
    #[serde(default)]
121
    scope: String,
122
}
123
124
/// `POST /admin/runners/token`: a one-time registration token, shown once,
125
/// for a runner of the scope given.
126
pub async fn new_token(State(app): State<Shared>, viewer: Viewer, Form(f): Form<ScopeForm>) -> Result<Page<RunnersPage>, Error> {
127
    let shell = Shell::new(&app, "/admin/runners", &viewer);
128
    let me = require_admin(&viewer, &shell)?;
129
    csrf(&viewer, &f.csrf_token, &shell)?;
130
    let scope = match parse_scope(&app, &f.scope).await {
131
        Ok(s) => s,
132
        Err(e) => return page(&app, shell, None, None, Some(e)).await,
133
    };
134
    let token = format!("flowreg_{}", crate::auth::random_hex(24));
135
    runners::add_registration(&app.db, &blake3::hash(token.as_bytes()).to_hex(), &me.username, &scope)
136
        .await
137
        .map_err(|e| Error::from_db(shell.clone(), e))?;
138
    let words = scope_words(&app, &scope).await;
139
    accounts::audit(&app.db, Some(&me), "flow.runner.token", "", &format!("registration token created for {words}")).await.ok();
140
    page(&app, shell, Some(token), Some(format!("The runner it registers will take jobs from {words}.")), None).await
141
}
142
143
/// `POST /admin/runners/{id}/scope`: change the repositories a runner serves.
144
pub async fn set_scope(
145
    State(app): State<Shared>,
146
    viewer: Viewer,
147
    Path(id): Path<i64>,
148
    Form(f): Form<ScopeForm>,
149
) -> Result<Page<RunnersPage>, Error> {
150
    let shell = Shell::new(&app, "/admin/runners", &viewer);
151
    let me = require_admin(&viewer, &shell)?;
152
    csrf(&viewer, &f.csrf_token, &shell)?;
153
    let r =
154
        runners::get(&app.db, id).await.map_err(|e| Error::from_db(shell.clone(), e))?.ok_or_else(|| Error::not_found(shell.clone()))?;
155
    let scope = match parse_scope(&app, &f.scope).await {
156
        Ok(s) => s,
157
        Err(e) => return page(&app, shell, None, None, Some(e)).await,
158
    };
159
    runners::set_scope(&app.db, id, &scope).await.map_err(|e| Error::from_db(shell.clone(), e))?;
160
    let words = scope_words(&app, &scope).await;
161
    accounts::audit(&app.db, Some(&me), "flow.runner.scope", &r.name, &words).await.ok();
162
    page(&app, shell, None, Some(format!("{} now takes jobs from {words}.", r.name)), None).await
163
}
164
165
#[derive(Deserialize)]
166
pub struct StateForm {
167
    #[serde(rename = "_csrf")]
168
    csrf_token: String,
169
    /// `active`, `draining` or `disabled`.
170
    state: String,
171
}
172
173
/// `POST /admin/runners/{id}/state`: drain, disable or resume a runner.
174
pub async fn set_state(
175
    State(app): State<Shared>,
176
    viewer: Viewer,
177
    Path(id): Path<i64>,
178
    Form(f): Form<StateForm>,
179
) -> Result<Response, Error> {
180
    let shell = Shell::new(&app, "/admin/runners", &viewer);
181
    let me = require_admin(&viewer, &shell)?;
182
    csrf(&viewer, &f.csrf_token, &shell)?;
183
    if !matches!(f.state.as_str(), "active" | "draining" | "disabled") {
184
        return Err(Error::bad(shell, "a runner is active, draining or disabled"));
185
    }
186
    let r =
187
        runners::get(&app.db, id).await.map_err(|e| Error::from_db(shell.clone(), e))?.ok_or_else(|| Error::not_found(shell.clone()))?;
188
    runners::set_state(&app.db, id, &f.state).await.map_err(|e| Error::from_db(shell.clone(), e))?;
189
    accounts::audit(&app.db, Some(&me), "flow.runner.state", &r.name, &f.state).await.ok();
190
    Ok(Redirect::to("/admin/runners").into_response())
191
}
192
193
/// `POST /admin/runners/{id}/remove`: forget a runner that runs nothing.
194
pub async fn remove(
195
    State(app): State<Shared>,
196
    viewer: Viewer,
197
    Path(id): Path<i64>,
198
    Form(f): Form<CsrfOnly>,
199
) -> Result<Page<RunnersPage>, Error> {
200
    let shell = Shell::new(&app, "/admin/runners", &viewer);
201
    let me = require_admin(&viewer, &shell)?;
202
    csrf(&viewer, &f.csrf_token, &shell)?;
203
    let e = |e| Error::from_db(shell.clone(), e);
204
    let r = runners::get(&app.db, id).await.map_err(e)?.ok_or_else(|| Error::not_found(shell.clone()))?;
205
    let busy = runners::running(&app.db).await.map_err(e)?.into_iter().any(|(rid, n)| rid == id && n > 0);
206
    if busy {
207
        return page(
208
            &app,
209
            shell,
210
            None,
211
            None,
212
            Some(format!("{} is running jobs: drain it first, then remove it when they finish.", r.name)),
213
        )
214
        .await;
215
    }
216
    runners::remove(&app.db, id).await.map_err(e)?;
217
    accounts::audit(&app.db, Some(&me), "flow.runner.remove", &r.name, "").await.ok();
218
    let also = if r.source == "config" {
219
        " It is configured in hub.toml; remove its token there too, or it comes back on its next claim."
220
    } else {
221
        ""
222
    };
223
    page(&app, shell, None, Some(format!("Removed {}.{also}", r.name)), None).await
224
}
225
226
#[derive(Template)]
227
#[template(path = "admin_runner.html")]
228
pub struct RunnerPage {
229
    shell: Shell,
230
    r: runners::Runner,
231
    running: i64,
232
    history: Vec<runners::RunnerJob>,
233
    older: Option<i64>,
234
    jobs: i64,
235
    passed: i64,
236
    busy_ms: i64,
237
}
238
239
impl RunnerPage {
240
    /// Time spent running jobs, as pages show durations.
241
    pub fn busy(&self) -> String {
242
        crate::flow::human_ms(self.busy_ms)
243
    }
244
}
245
246
#[derive(Deserialize, Default)]
247
pub struct HistoryQuery {
248
    before: Option<i64>,
249
}
250
251
const PER_PAGE: i64 = 50;
252
253
/// `GET /admin/runners/{id}`: a runner and the jobs it ran.
254
pub async fn show(
255
    State(app): State<Shared>,
256
    viewer: Viewer,
257
    Path(id): Path<i64>,
258
    Query(q): Query<HistoryQuery>,
259
) -> Result<Page<RunnerPage>, Error> {
260
    let shell = Shell::new(&app, &format!("/admin/runners/{id}"), &viewer);
261
    require_admin(&viewer, &shell)?;
262
    let e = |e| Error::from_db(shell.clone(), e);
263
    let r = runners::get(&app.db, id).await.map_err(e)?.ok_or_else(|| Error::not_found(shell.clone()))?;
264
    let mut history = runners::history(&app.db, id, PER_PAGE + 1, q.before).await.map_err(e)?;
265
    let older = (history.len() as i64 > PER_PAGE).then(|| history[PER_PAGE as usize - 1].started_ms).flatten();
266
    history.truncate(PER_PAGE as usize);
267
    let (jobs, passed, busy_ms) = runners::totals(&app.db, id).await.map_err(e)?;
268
    let running = runners::running(&app.db).await.map_err(e)?.into_iter().find(|(rid, _)| *rid == id).map(|(_, n)| n).unwrap_or(0);
269
    Ok(Page(RunnerPage { shell, r, running, history, older, jobs, passed, busy_ms }))
270
}
271
272
pub fn duration(j: &runners::RunnerJob) -> String {
273
    match (j.started_ms, j.finished_ms) {
274
        (Some(a), Some(b)) => crate::flow::human_ms(b - a),
275
        (Some(a), None) => crate::flow::human_ms(db::now_ms() - a),
276
        _ => "–".into(),
277
    }
278
}