| 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, |
| 27 |
|
| 28 |
pub scope: String, |
| 29 |
|
| 30 |
|
| 31 |
pub swarm: String, |
| 32 |
|
| 33 |
pub jobs: Vec<(String, i64, String, Option<i64>)>, |
| 34 |
} |
| 35 |
|
| 36 |
impl RunnerRow { |
| 37 |
|
| 38 |
|
| 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 |
|
| 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 |
|
| 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 |
|
| 86 |
|
| 87 |
|
| 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 |
|
| 100 |
|
| 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 |
|
| 121 |
#[derive(Template)] |
| 122 |
#[template(path = "admin_runners.html")] |
| 123 |
pub struct RunnersPage { |
| 124 |
shell: Shell, |
| 125 |
runners: Vec<RunnerRow>, |
| 126 |
|
| 127 |
pending: Vec<(String, i64, i64)>, |
| 128 |
|
| 129 |
new_token: Option<String>, |
| 130 |
hub: String, |
| 131 |
notice: Option<String>, |
| 132 |
error: Option<String>, |
| 133 |
|
| 134 |
|
| 135 |
queue: Vec<db::flow::QueueEntry>, |
| 136 |
|
| 137 |
queue_total: usize, |
| 138 |
filter: QueueFilter, |
| 139 |
|
| 140 |
queue_repos: Vec<String>, |
| 141 |
queue_runners: Vec<String>, |
| 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> { |
| 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> { |
| 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)?; |
| 166 |
let all = db::flow::queue(&app.db).await.map_err(e)?; |
| 167 |
let mut rows = Vec::with_capacity(list.len()); |
| 168 |
for r in list { |
| 169 |
let scope = scope_words(app, &r.scope()).await; |
| 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(); |
| 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 }); |
| 181 |
} |
| 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 |
})) |
| 204 |
} |
| 205 |
|
| 206 |
|
| 207 |
pub async fn list(State(app): State<Shared>, viewer: Viewer, Query(filter): Query<QueueFilter>) -> Result<Page<RunnersPage>, Error> { |
| 208 |
let shell = Shell::new(&app, "/admin/runners", &viewer); |
| 209 |
require_admin(&viewer, &shell)?; |
| 210 |
page_filtered(&app, shell, None, None, None, filter).await |
| 211 |
} |
| 212 |
|
| 213 |
#[derive(Deserialize)] |
| 214 |
pub struct CsrfOnly { |
| 215 |
#[serde(rename = "_csrf")] |
| 216 |
csrf_token: String, |
| 217 |
} |
| 218 |
|
| 219 |
#[derive(Deserialize)] |
| 220 |
pub struct ScopeForm { |
| 221 |
#[serde(rename = "_csrf")] |
| 222 |
csrf_token: String, |
| 223 |
|
| 224 |
#[serde(default)] |
| 225 |
scope: String, |
| 226 |
} |
| 227 |
|
| 228 |
|
| 229 |
|
| 230 |
pub async fn new_token(State(app): State<Shared>, viewer: Viewer, Form(f): Form<ScopeForm>) -> Result<Page<RunnersPage>, Error> { |
| 231 |
let shell = Shell::new(&app, "/admin/runners", &viewer); |
| 232 |
let me = require_admin(&viewer, &shell)?; |
| 233 |
csrf(&viewer, &f.csrf_token, &shell)?; |
| 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 |
}; |
| 238 |
let token = format!("flowreg_{}", crate::auth::random_hex(24)); |
| 239 |
runners::add_registration(&app.db, &blake3::hash(token.as_bytes()).to_hex(), &me.username, &scope) |
| 240 |
.await |
| 241 |
.map_err(|e| Error::from_db(shell.clone(), e))?; |
| 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 |
|
| 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 |
| 267 |
} |
| 268 |
|
| 269 |
#[derive(Deserialize)] |
| 270 |
pub struct LimitsForm { |
| 271 |
#[serde(rename = "_csrf")] |
| 272 |
csrf_token: String, |
| 273 |
|
| 274 |
#[serde(default)] |
| 275 |
labels: String, |
| 276 |
|
| 277 |
#[serde(default)] |
| 278 |
timeout_minutes: String, |
| 279 |
} |
| 280 |
|
| 281 |
|
| 282 |
|
| 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)] |
| 321 |
pub struct StateForm { |
| 322 |
#[serde(rename = "_csrf")] |
| 323 |
csrf_token: String, |
| 324 |
|
| 325 |
state: String, |
| 326 |
} |
| 327 |
|
| 328 |
|
| 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 |
|
| 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>, |
| 388 |
declines: Vec<crate::db::flow::RunnerDecline>, |
| 389 |
older: Option<i64>, |
| 390 |
jobs: i64, |
| 391 |
passed: i64, |
| 392 |
busy_ms: i64, |
| 393 |
} |
| 394 |
|
| 395 |
impl RunnerPage { |
| 396 |
|
| 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 |
|
| 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); |
| 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 })) |
| 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 |
} |
| 436 |
|
| 437 |
|
| 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 |
|
| 447 |
file_default_m: u64, |
| 448 |
flow_repos: Vec<String>, |
| 449 |
|
| 450 |
priority: String, |
| 451 |
|
| 452 |
expedite_cap: i64, |
| 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(), |
| 466 |
expedite_cap: accounts::setting(&app.db, "flow_expedite_cap").await.ok().flatten().and_then(|v| v.parse().ok()).unwrap_or(2), |
| 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()), |
| 473 |
notice, |
| 474 |
error, |
| 475 |
}) |
| 476 |
} |
| 477 |
|
| 478 |
#[derive(Deserialize)] |
| 479 |
pub struct PriorityForm { |
| 480 |
#[serde(rename = "_csrf")] |
| 481 |
csrf_token: String, |
| 482 |
priority: String, |
| 483 |
#[serde(default)] |
| 484 |
expedite_cap: Option<String>, |
| 485 |
} |
| 486 |
|
| 487 |
|
| 488 |
|
| 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 |
} |
| 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 |
}; |
| 503 |
accounts::set_setting(&app.db, "flow_priority", &f.priority).await.map_err(|e| Error::from_db(shell.clone(), e))?; |
| 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 |
} |
| 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 |
|
| 517 |
|
| 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 |
|
| 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 |
} |
| 563 |
|
| 564 |
|
| 565 |
|
| 566 |
pub struct Place { |
| 567 |
pub name: String, |
| 568 |
|
| 569 |
pub kind: &'static str, |
| 570 |
pub title: String, |
| 571 |
} |
| 572 |
|
| 573 |
pub struct ImageRow { |
| 574 |
pub hash: String, |
| 575 |
pub arch: String, |
| 576 |
|
| 577 |
pub size: Option<i64>, |
| 578 |
pub places: Vec<Place>, |
| 579 |
|
| 580 |
pub sent: Option<(String, i64)>, |
| 581 |
|
| 582 |
pub uses: Vec<(String, i64, i64)>, |
| 583 |
pub last_used: i64, |
| 584 |
} |
| 585 |
|
| 586 |
impl ImageRow { |
| 587 |
|
| 588 |
|
| 589 |
|
| 590 |
pub fn stranded(&self) -> bool { |
| 591 |
self.places.iter().all(|p| p.kind == "peer") |
| 592 |
} |
| 593 |
} |
| 594 |
|
| 595 |
#[derive(Template)] |
| 596 |
#[template(path = "admin_images.html")] |
| 597 |
pub struct ImagesPage { |
| 598 |
shell: Shell, |
| 599 |
images: Vec<ImageRow>, |
| 600 |
on_hub: usize, |
| 601 |
|
| 602 |
swarm: Vec<String>, |
| 603 |
|
| 604 |
|
| 605 |
backdrop: String, |
| 606 |
} |
| 607 |
|
| 608 |
|
| 609 |
|
| 610 |
fn swarm_json(images: &[ImageRow]) -> String { |
| 611 |
let mut nodes: Vec<String> = vec!["hub".into()]; |
| 612 |
let mut list = Vec::new(); |
| 613 |
for img in images { |
| 614 |
let (mut held, mut fetching) = (Vec::new(), Vec::new()); |
| 615 |
for p in &img.places { |
| 616 |
let i = match p.kind { |
| 617 |
"hub" => 0, |
| 618 |
_ => match nodes.iter().position(|n| *n == p.name) { |
| 619 |
Some(i) => i, |
| 620 |
None => { |
| 621 |
nodes.push(p.name.clone()); |
| 622 |
nodes.len() - 1 |
| 623 |
} |
| 624 |
}, |
| 625 |
}; |
| 626 |
if p.kind == "fetching" { |
| 627 |
fetching.push(i); |
| 628 |
} else { |
| 629 |
held.push(i); |
| 630 |
} |
| 631 |
} |
| 632 |
list.push(serde_json::json!({ "held": held, "fetching": fetching })); |
| 633 |
} |
| 634 |
serde_json::json!({ "scene": "swarm", "nodes": nodes, "images": list }).to_string().replace('<', "\\u003c") |
| 635 |
} |
| 636 |
|
| 637 |
|
| 638 |
|
| 639 |
pub async fn images(State(app): State<Shared>, viewer: Viewer) -> Result<Page<ImagesPage>, Error> { |
| 640 |
let shell = Shell::new(&app, "/admin/runners/images", &viewer); |
| 641 |
require_admin(&viewer, &shell)?; |
| 642 |
let e = |e| Error::from_db(shell.clone(), e); |
| 643 |
let kept = crate::images::kept(&app.db).await.map_err(e)?; |
| 644 |
let uses = crate::images::uses(&app.db, db::now_ms() - 90 * 24 * 3600 * 1000).await.map_err(e)?; |
| 645 |
let archs = crate::images::reported_archs(&app.db).await.map_err(e)?; |
| 646 |
let list = runners::list(&app.db).await.map_err(e)?; |
| 647 |
let fetching = app.swarm.fetching_now(); |
| 648 |
let mut rows: HashMap<String, ImageRow> = HashMap::new(); |
| 649 |
let row = |rows: &mut HashMap<String, ImageRow>, hash: &str| -> () { |
| 650 |
rows.entry(hash.to_ascii_lowercase()).or_insert_with(|| ImageRow { |
| 651 |
hash: hash.to_ascii_lowercase(), |
| 652 |
arch: archs.get(&hash.to_ascii_lowercase()).cloned().unwrap_or_default(), |
| 653 |
size: None, |
| 654 |
places: Vec::new(), |
| 655 |
sent: None, |
| 656 |
uses: Vec::new(), |
| 657 |
last_used: 0, |
| 658 |
}); |
| 659 |
}; |
| 660 |
for k in &kept { |
| 661 |
row(&mut rows, &k.hash); |
| 662 |
let r = rows.get_mut(&k.hash.to_ascii_lowercase()).expect("added"); |
| 663 |
r.size = Some(k.size); |
| 664 |
if r.arch.is_empty() { |
| 665 |
r.arch = k.arch.clone(); |
| 666 |
} |
| 667 |
r.sent = Some((k.uploader.clone(), k.created_ms)); |
| 668 |
|
| 669 |
|
| 670 |
r.places.push(if k.source == "peer" { |
| 671 |
Place { |
| 672 |
name: "manifest".into(), |
| 673 |
kind: "peer", |
| 674 |
title: format!("The hub keeps only its manifest, sent by {}; runners holding it serve its {} chunks", k.holder, k.chunks), |
| 675 |
} |
| 676 |
} else { |
| 677 |
Place { name: "hub".into(), kind: "hub", title: format!("{} chunks kept by the hub", k.chunks) } |
| 678 |
}); |
| 679 |
} |
| 680 |
let mut swarm = Vec::new(); |
| 681 |
for runner in &list { |
| 682 |
if let Some(a) = app.swarm.addr(runner.id) { |
| 683 |
swarm.push(if a.site.is_empty() { runner.name.clone() } else { format!("{} ({})", runner.name, a.site) }); |
| 684 |
} |
| 685 |
for h in runner.image_list().unwrap_or_default() { |
| 686 |
row(&mut rows, &h); |
| 687 |
rows.get_mut(&h.to_ascii_lowercase()).expect("added").places.push(Place { |
| 688 |
name: runner.name.clone(), |
| 689 |
kind: "holds", |
| 690 |
title: format!("{} holds it ({})", runner.name, runner.status()), |
| 691 |
}); |
| 692 |
} |
| 693 |
} |
| 694 |
for (image, who) in &fetching { |
| 695 |
row(&mut rows, image); |
| 696 |
for id in who { |
| 697 |
if let Some(runner) = list.iter().find(|r| r.id == *id) { |
| 698 |
rows.get_mut(image).expect("added").places.push(Place { |
| 699 |
name: runner.name.clone(), |
| 700 |
kind: "fetching", |
| 701 |
title: format!("{} is fetching it from the swarm now", runner.name), |
| 702 |
}); |
| 703 |
} |
| 704 |
} |
| 705 |
} |
| 706 |
for u in uses { |
| 707 |
if !jet::images::is_hash(&u.image) { |
| 708 |
continue; |
| 709 |
} |
| 710 |
row(&mut rows, &u.image); |
| 711 |
let r = rows.get_mut(&u.image).expect("added"); |
| 712 |
r.last_used = r.last_used.max(u.last_ms); |
| 713 |
r.uses.push((format!("{}/{}", u.owner, u.name), u.jobs, u.last_ms)); |
| 714 |
} |
| 715 |
let mut images: Vec<ImageRow> = rows.into_values().collect(); |
| 716 |
images.sort_by(|a, b| b.last_used.cmp(&a.last_used).then_with(|| a.hash.cmp(&b.hash))); |
| 717 |
let on_hub = kept.len(); |
| 718 |
let backdrop = swarm_json(&images); |
| 719 |
Ok(Page(ImagesPage { shell, images, on_hub, swarm, backdrop })) |
| 720 |
} |