| b6b7e4cf Andy McCall ↶ |
1 |
|
| 2 |
|
| 3 |
|
| 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 |
|
| 26 |
pub running: i64, |
| 74be9796 Andy McCall ↶ |
27 |
|
| 28 |
pub scope: String, |
| b6b7e4cf Andy McCall ↶ |
29 |
} |
| 30 |
|
| 74be9796 Andy McCall ↶ |
31 |
|
| 32 |
|
| 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 |
|
| 45 |
|
| 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 |
|
| b6b7e4cf Andy McCall ↶ |
66 |
#[derive(Template)] |
| 67 |
#[template(path = "admin_runners.html")] |
| 68 |
pub struct RunnersPage { |
| 69 |
shell: Shell, |
| 70 |
runners: Vec<RunnerRow>, |
| 71 |
|
| 72 |
pending: Vec<(String, i64, i64)>, |
| 73 |
|
| 74 |
new_token: Option<String>, |
| 75 |
hub: String, |
| 76 |
notice: Option<String>, |
| 77 |
error: Option<String>, |
| b66e70b7 Andy McCall ↶ |
78 |
|
| 79 |
queue: Vec<db::flow::QueueEntry>, |
| b6b7e4cf Andy McCall ↶ |
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)?; |
| 74be9796 Andy McCall ↶ |
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 |
} |
| b66e70b7 Andy McCall ↶ |
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 })) |
| b6b7e4cf Andy McCall ↶ |
100 |
} |
| 101 |
|
| 102 |
|
| 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 { |
| 74be9796 Andy McCall ↶ |
111 |
#[serde(rename = "_csrf")] |
| 112 |
csrf_token: String, |
| 113 |
} |
| 114 |
|
| 115 |
#[derive(Deserialize)] |
| 116 |
pub struct ScopeForm { |
| b6b7e4cf Andy McCall ↶ |
117 |
#[serde(rename = "_csrf")] |
| 118 |
csrf_token: String, |
| 74be9796 Andy McCall ↶ |
119 |
|
| 120 |
#[serde(default)] |
| 121 |
scope: String, |
| b6b7e4cf Andy McCall ↶ |
122 |
} |
| 123 |
|
| 74be9796 Andy McCall ↶ |
124 |
|
| 125 |
|
| 126 |
pub async fn new_token(State(app): State<Shared>, viewer: Viewer, Form(f): Form<ScopeForm>) -> Result<Page<RunnersPage>, Error> { |
| b6b7e4cf Andy McCall ↶ |
127 |
let shell = Shell::new(&app, "/admin/runners", &viewer); |
| 128 |
let me = require_admin(&viewer, &shell)?; |
| 129 |
csrf(&viewer, &f.csrf_token, &shell)?; |
| 74be9796 Andy McCall ↶ |
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 |
}; |
| b6b7e4cf Andy McCall ↶ |
134 |
let token = format!("flowreg_{}", crate::auth::random_hex(24)); |
| 74be9796 Andy McCall ↶ |
135 |
runners::add_registration(&app.db, &blake3::hash(token.as_bytes()).to_hex(), &me.username, &scope) |
| b6b7e4cf Andy McCall ↶ |
136 |
.await |
| 137 |
.map_err(|e| Error::from_db(shell.clone(), e))?; |
| 74be9796 Andy McCall ↶ |
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 |
|
| 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 |
| b6b7e4cf Andy McCall ↶ |
163 |
} |
| 164 |
|
| 165 |
#[derive(Deserialize)] |
| 166 |
pub struct StateForm { |
| 167 |
#[serde(rename = "_csrf")] |
| 168 |
csrf_token: String, |
| 169 |
|
| 170 |
state: String, |
| 171 |
} |
| 172 |
|
| 173 |
|
| 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 |
|
| 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 |
|
| 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 |
|
| 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 |
} |
| 5dead1f4 Andy McCall ↶ |
279 |
|
| 280 |
|
| 281 |
|
| 282 |
#[derive(Template)] |
| 283 |
#[template(path = "admin_runner_settings.html")] |
| 284 |
pub struct SettingsPage { |
| 285 |
shell: Shell, |
| 286 |
default_m: u64, |
| 287 |
max_m: u64, |
| 288 |
grace_m: i64, |
| 289 |
|
| 290 |
file_default_m: u64, |
| 291 |
flow_repos: Vec<String>, |
| 292 |
notice: Option<String>, |
| 293 |
error: Option<String>, |
| 294 |
} |
| 295 |
|
| 296 |
async fn settings_page(app: &Shared, shell: Shell, notice: Option<String>, error: Option<String>) -> Page<SettingsPage> { |
| 297 |
let l = crate::flow::limits(app).await; |
| 298 |
Page(SettingsPage { |
| 299 |
shell, |
| 300 |
default_m: l.default_s / 60, |
| 301 |
max_m: l.max_s / 60, |
| 302 |
grace_m: l.grace_ms / 60_000, |
| 303 |
file_default_m: app.config.flow.job_timeout_minutes, |
| 304 |
flow_repos: app.config.flow.repos.clone(), |
| 305 |
notice, |
| 306 |
error, |
| 307 |
}) |
| 308 |
} |
| 309 |
|
| 310 |
|
| 311 |
pub async fn settings(State(app): State<Shared>, viewer: Viewer) -> Result<Page<SettingsPage>, Error> { |
| 312 |
let shell = Shell::new(&app, "/admin/runners/settings", &viewer); |
| 313 |
require_admin(&viewer, &shell)?; |
| 314 |
Ok(settings_page(&app, shell, None, None).await) |
| 315 |
} |
| 316 |
|
| 317 |
#[derive(Deserialize)] |
| 318 |
pub struct SettingsForm { |
| 319 |
#[serde(rename = "_csrf")] |
| 320 |
csrf_token: String, |
| 321 |
default_minutes: String, |
| 322 |
max_minutes: String, |
| 323 |
grace_minutes: String, |
| 324 |
} |
| 325 |
|
| 326 |
|
| 327 |
pub async fn save_settings(State(app): State<Shared>, viewer: Viewer, Form(f): Form<SettingsForm>) -> Result<Page<SettingsPage>, Error> { |
| 328 |
let shell = Shell::new(&app, "/admin/runners/settings", &viewer); |
| 329 |
let me = require_admin(&viewer, &shell)?; |
| 330 |
csrf(&viewer, &f.csrf_token, &shell)?; |
| 331 |
let num = |v: &str| v.trim().parse::<u64>().ok().filter(|n| *n > 0); |
| 332 |
let (Some(d), Some(m), Some(g)) = (num(&f.default_minutes), num(&f.max_minutes), num(&f.grace_minutes)) else { |
| 333 |
return Ok(settings_page(&app, shell, None, Some("Each limit is a whole number of minutes, at least 1.".into())).await); |
| 334 |
}; |
| 335 |
if d > m { |
| 336 |
return Ok(settings_page(&app, shell, None, Some("The default cannot be longer than the maximum.".into())).await); |
| 337 |
} |
| 338 |
if m > 24 * 60 { |
| 339 |
return Ok(settings_page(&app, shell, None, Some("A job may run for a day at most (1440 minutes).".into())).await); |
| 340 |
} |
| 341 |
let e = |e| Error::from_db(shell.clone(), e); |
| 342 |
accounts::set_setting(&app.db, crate::flow::SETTING_DEFAULT, &d.to_string()).await.map_err(e)?; |
| 343 |
accounts::set_setting(&app.db, crate::flow::SETTING_MAX, &m.to_string()).await.map_err(e)?; |
| 344 |
accounts::set_setting(&app.db, crate::flow::SETTING_GRACE, &g.to_string()).await.map_err(e)?; |
| 345 |
accounts::audit( |
| 346 |
&app.db, |
| 347 |
Some(&me), |
| 348 |
"flow.settings", |
| 349 |
"", |
| 350 |
&format!("job time limit {d} min by default, {m} min at most; lost after {g} min more"), |
| 351 |
) |
| 352 |
.await |
| 353 |
.ok(); |
| 354 |
Ok(settings_page(&app, shell, Some("Saved. Jobs claimed from now on run under these limits.".into()), None).await) |
| 355 |
} |