Runners handle SIGTERM, report a clean stop so they show offline at once, and can unregister themselves (install.sh --uninstall uses it)
Browse files at this commit2e29cbcf4cef4a19ff87691bfec4a1cced5f963eParent: 8298537Some checks failed
Show checks
ci/buildFailedDetails
- feat
- runners handle SIGTERM, report a clean stop so they show offline at once, and can unregister themselves (install.sh --uninstall uses it)
- runner name is editable from the admin page
- docs
- runner check runs under systemd-run --user
14 changed files +253 -23
- crates/forge-core/migrations/0077_runner_stopped_at.sql +1 -0
- crates/forge-core/src/ci.rs +9 -1
- crates/forge-core/src/store/ci.rs +53 -1
- crates/forge-core/src/store/health.rs +8 -4
- crates/forge-core/src/store/migrate.rs +4 -0
- crates/forge-runner/src/cli.rs +31 -4
- crates/forge-runner/src/client.rs +22 -0
- crates/forge-web-app/src/alerts.rs +1 -5
- crates/forge-web-app/src/ci/api.rs +41 -0
- crates/forge-web-app/src/ci/api_tests.rs +51 -0
- crates/forge-web-app/src/ci/install.sh +11 -1
- crates/forge-web-pages/src/pages/admin_runners.rs +11 -2
- crates/forge-web/src/routes.snap +2 -0
- docs/ci.md +8 -5
crates/forge-core/migrations/0077_runner_stopped_at.sqladded+1 -0
| @@ -0,0 +1 @@ | |||
| 1 | +ALTER TABLE ci_runners ADD COLUMN stopped_at TEXT; | ||
crates/forge-core/src/ci.rsmodified+9 -1
| @@ -77,6 +77,7 @@ pub struct CiRunner { | |||
| 77 | pub labels: Vec<String>, | 77 | pub labels: Vec<String>, |
| 78 | pub created_at: String, | 78 | pub created_at: String, |
| 79 | pub last_seen_at: Option<String>, | 79 | pub last_seen_at: Option<String>, |
| 80 | + pub stopped_at: Option<String>, | ||
| 80 | pub disabled: bool, | 81 | pub disabled: bool, |
| 81 | pub concurrency_override: Option<u32>, | 82 | pub concurrency_override: Option<u32>, |
| 82 | pub reported: RunnerReport, | 83 | pub reported: RunnerReport, |
| @@ -176,7 +177,7 @@ pub const RUNNER_FIELDS: &[RunnerField] = &[ | |||
| 176 | }, | 177 | }, |
| 177 | RunnerField { | 178 | RunnerField { |
| 178 | key: "name", | 179 | key: "name", |
| 179 | - kind: FieldKind::ReadOnly, | 180 | + kind: FieldKind::Live, |
| 180 | }, | 181 | }, |
| 181 | RunnerField { | 182 | RunnerField { |
| 182 | key: "url", | 183 | key: "url", |
| @@ -225,6 +226,13 @@ pub fn validate_runner_field( | |||
| 225 | i64::from(MAX_CONCURRENCY), | 226 | i64::from(MAX_CONCURRENCY), |
| 226 | "concurrency", | 227 | "concurrency", |
| 227 | ), | 228 | ), |
| 229 | + "name" => { | ||
| 230 | + if raw.is_empty() || raw.len() > 100 { | ||
| 231 | + Err("a runner name needs 1 to 100 bytes".into()) | ||
| 232 | + } else { | ||
| 233 | + Ok(Value::from(raw)) | ||
| 234 | + } | ||
| 235 | + } | ||
| 228 | "labels" => { | 236 | "labels" => { |
| 229 | let labels: Vec<String> = raw | 237 | let labels: Vec<String> = raw |
| 230 | .split(',') | 238 | .split(',') |
crates/forge-core/src/store/ci.rsmodified+53 -1
| @@ -29,7 +29,7 @@ const RUNNER_COLS: &str = "id, name, labels, created_at, last_seen_at, disabled, | |||
| 29 | reported_memory_bytes, reported_config, config_overrides, \ | 29 | reported_memory_bytes, reported_config, config_overrides, \ |
| 30 | (SELECT COUNT(*) FROM ci_jobs WHERE ci_jobs.runner_id = ci_runners.id AND ci_jobs.state = 'running'), \ | 30 | (SELECT COUNT(*) FROM ci_jobs WHERE ci_jobs.runner_id = ci_runners.id AND ci_jobs.state = 'running'), \ |
| 31 | reported_build, reported_boot_id, restart_mode, restart_requested_at, reported_capabilities, \ | 31 | reported_build, reported_boot_id, restart_mode, restart_requested_at, reported_capabilities, \ |
| 32 | - reported_memory_budget, reported_memory_free, reported_memory_reserve"; | 32 | + reported_memory_budget, reported_memory_free, reported_memory_reserve, stopped_at"; |
| 33 | const RUNNER_JOB_COLS: &str = "j.id, j.run_id, j.name, j.spec, j.state, j.runner_id, j.exit_code, \ | 33 | const RUNNER_JOB_COLS: &str = "j.id, j.run_id, j.name, j.spec, j.state, j.runner_id, j.exit_code, \ |
| 34 | j.message, j.queued_at, j.started_at, j.finished_at, j.heartbeat_at, j.cancel_requested, \ | 34 | j.message, j.queued_at, j.started_at, j.finished_at, j.heartbeat_at, j.cancel_requested, \ |
| 35 | j.log_bytes, j.oom_kills, r.number, u.username, p.name"; | 35 | j.log_bytes, j.oom_kills, r.number, u.username, p.name"; |
| @@ -50,6 +50,7 @@ fn map_runner(row: &Row) -> Result<CiRunner> { | |||
| 50 | labels, | 50 | labels, |
| 51 | created_at: col_text(row, 3)?, | 51 | created_at: col_text(row, 3)?, |
| 52 | last_seen_at: col_opt_text(row, 4)?, | 52 | last_seen_at: col_opt_text(row, 4)?, |
| 53 | + stopped_at: col_opt_text(row, 22)?, | ||
| 53 | disabled: col_bool(row, 5)?, | 54 | disabled: col_bool(row, 5)?, |
| 54 | concurrency_override: opt_u32(row, 6)?, | 55 | concurrency_override: opt_u32(row, 6)?, |
| 55 | reported: RunnerReport { | 56 | reported: RunnerReport { |
| @@ -444,6 +445,17 @@ impl Store { | |||
| 444 | Ok(token) | 445 | Ok(token) |
| 445 | } | 446 | } |
| 446 | 447 | ||
| 448 | + pub async fn mark_runner_stopped(&self, id: &str) -> Result<()> { | ||
| 449 | + let conn = self.inner.conn.lock().await; | ||
| 450 | + conn.execute( | ||
| 451 | + "UPDATE ci_runners SET stopped_at = last_seen_at WHERE id = ?1", | ||
| 452 | + (id.to_owned(),), | ||
| 453 | + ) | ||
| 454 | + .await | ||
| 455 | + .map_err(db_err)?; | ||
| 456 | + Ok(()) | ||
| 457 | + } | ||
| 458 | + | ||
| 447 | pub async fn registration_token_used(&self, token_hash: &str) -> Result<bool> { | 459 | pub async fn registration_token_used(&self, token_hash: &str) -> Result<bool> { |
| 448 | let conn = self.inner.conn.lock().await; | 460 | let conn = self.inner.conn.lock().await; |
| 449 | let mut rows = conn | 461 | let mut rows = conn |
| @@ -660,6 +672,21 @@ impl Store { | |||
| 660 | Some(raw) => Some(validate_runner_field(key, raw).map_err(Error::Invalid)?), | 672 | Some(raw) => Some(validate_runner_field(key, raw).map_err(Error::Invalid)?), |
| 661 | None => None, | 673 | None => None, |
| 662 | }; | 674 | }; |
| 675 | + if field.key == "name" { | ||
| 676 | + let conn = self.inner.conn.lock().await; | ||
| 677 | + let runner = load_runner(&conn, id).await?.ok_or(Error::NotFound)?; | ||
| 678 | + let name = parsed | ||
| 679 | + .or_else(|| runner.reported_config.get("name").cloned()) | ||
| 680 | + .and_then(|v| v.as_str().map(str::to_owned)) | ||
| 681 | + .ok_or_else(|| Error::Invalid("the runner never reported its name".into()))?; | ||
| 682 | + conn.execute( | ||
| 683 | + "UPDATE ci_runners SET name = ?2 WHERE id = ?1", | ||
| 684 | + (id.to_owned(), name), | ||
| 685 | + ) | ||
| 686 | + .await | ||
| 687 | + .map_err(db_err)?; | ||
| 688 | + return Ok(()); | ||
| 689 | + } | ||
| 663 | if field.key == "concurrency" { | 690 | if field.key == "concurrency" { |
| 664 | let n = parsed.as_ref().and_then(serde_json::Value::as_u64); | 691 | let n = parsed.as_ref().and_then(serde_json::Value::as_u64); |
| 665 | return self | 692 | return self |
| @@ -2167,6 +2194,7 @@ mod tests { | |||
| 2167 | labels: labels.iter().map(|s| s.to_string()).collect(), | 2194 | labels: labels.iter().map(|s| s.to_string()).collect(), |
| 2168 | created_at: now_stamp(), | 2195 | created_at: now_stamp(), |
| 2169 | last_seen_at: None, | 2196 | last_seen_at: None, |
| 2197 | + stopped_at: None, | ||
| 2170 | disabled: false, | 2198 | disabled: false, |
| 2171 | concurrency_override: None, | 2199 | concurrency_override: None, |
| 2172 | reported: RunnerReport::default(), | 2200 | reported: RunnerReport::default(), |
| @@ -2177,6 +2205,30 @@ mod tests { | |||
| 2177 | } | 2205 | } |
| 2178 | } | 2206 | } |
| 2179 | 2207 | ||
| 2208 | + #[tokio::test] | ||
| 2209 | + async fn runner_name_can_be_changed_and_never_emptied() { | ||
| 2210 | + let fx = fixture().await; | ||
| 2211 | + let (runner, _) = runner_with(&fx.store, &fx.tahinli.id, &[]).await; | ||
| 2212 | + fx.store | ||
| 2213 | + .set_runner_field(&runner.id, "name", Some("beefy-1")) | ||
| 2214 | + .await | ||
| 2215 | + .unwrap(); | ||
| 2216 | + let empty = fx | ||
| 2217 | + .store | ||
| 2218 | + .set_runner_field(&runner.id, "name", Some(" ")) | ||
| 2219 | + .await; | ||
| 2220 | + assert!(matches!(empty, Err(Error::Invalid(_))), "{empty:?}"); | ||
| 2221 | + let names: Vec<String> = fx | ||
| 2222 | + .store | ||
| 2223 | + .list_runners() | ||
| 2224 | + .await | ||
| 2225 | + .unwrap() | ||
| 2226 | + .into_iter() | ||
| 2227 | + .map(|r| r.name) | ||
| 2228 | + .collect(); | ||
| 2229 | + assert_eq!(names, vec!["beefy-1".to_string()]); | ||
| 2230 | + } | ||
| 2231 | + | ||
| 2180 | #[tokio::test] | 2232 | #[tokio::test] |
| 2181 | async fn registration_token_is_single_use_and_expires() { | 2233 | async fn registration_token_is_single_use_and_expires() { |
| 2182 | let fx = fixture().await; | 2234 | let fx = fixture().await; |
crates/forge-core/src/store/health.rsmodified+8 -4
| @@ -1,12 +1,15 @@ | |||
| 1 | use super::{Store, col_int, fetch_opt}; | 1 | use super::{Store, col_int, fetch_opt}; |
| 2 | +use crate::ci::CiRunner; | ||
| 2 | use crate::error::{Error, Result}; | 3 | use crate::error::{Error, Result}; |
| 3 | use crate::time::{stamp_ago, stamp_to_unix}; | 4 | use crate::time::{stamp_ago, stamp_to_unix}; |
| 4 | 5 | ||
| 5 | pub const RUNNER_ONLINE_SECS: i64 = 90; | 6 | pub const RUNNER_ONLINE_SECS: i64 = 90; |
| 6 | 7 | ||
| 7 | -pub fn runner_is_online(disabled: bool, last_seen_at: Option<&str>, now_unix: i64) -> bool { | 8 | +pub fn runner_is_online(runner: &CiRunner, now_unix: i64) -> bool { |
| 8 | - !disabled | 9 | + let seen = runner.last_seen_at.as_deref(); |
| 9 | - && last_seen_at | 10 | + !runner.disabled |
| 11 | + && runner.stopped_at.as_deref() != seen | ||
| 12 | + && seen | ||
| 10 | .and_then(stamp_to_unix) | 13 | .and_then(stamp_to_unix) |
| 11 | .is_some_and(|seen| now_unix.saturating_sub(seen) <= RUNNER_ONLINE_SECS) | 14 | .is_some_and(|seen| now_unix.saturating_sub(seen) <= RUNNER_ONLINE_SECS) |
| 12 | } | 15 | } |
| @@ -38,7 +41,8 @@ impl Store { | |||
| 38 | }; | 41 | }; |
| 39 | let online = fetch_opt( | 42 | let online = fetch_opt( |
| 40 | &conn, | 43 | &conn, |
| 41 | - "SELECT COUNT(*) FROM ci_runners WHERE disabled = 0 AND last_seen_at > ?1", | 44 | + "SELECT COUNT(*) FROM ci_runners WHERE disabled = 0 AND last_seen_at > ?1 \ |
| 45 | + AND stopped_at IS NOT last_seen_at", | ||
| 42 | (since,), | 46 | (since,), |
| 43 | |row| col_int(row, 0), | 47 | |row| col_int(row, 0), |
| 44 | ) | 48 | ) |
crates/forge-core/src/store/migrate.rsmodified+4 -0
| @@ -139,6 +139,10 @@ pub const MIGRATIONS: &[(u32, &str)] = &[ | |||
| 139 | 76, | 139 | 76, |
| 140 | include_str!("../../migrations/0076_milestone_title_repair.sql"), | 140 | include_str!("../../migrations/0076_milestone_title_repair.sql"), |
| 141 | ), | 141 | ), |
| 142 | + ( | ||
| 143 | + 77, | ||
| 144 | + include_str!("../../migrations/0077_runner_stopped_at.sql"), | ||
| 145 | + ), | ||
| 142 | ]; | 146 | ]; |
| 143 | 147 | ||
| 144 | pub fn latest_schema_version() -> u32 { | 148 | pub fn latest_schema_version() -> u32 { |
crates/forge-runner/src/cli.rsmodified+31 -4
| @@ -55,6 +55,10 @@ enum Command { | |||
| 55 | #[arg(long)] | 55 | #[arg(long)] |
| 56 | config: Option<PathBuf>, | 56 | config: Option<PathBuf>, |
| 57 | }, | 57 | }, |
| 58 | + Unregister { | ||
| 59 | + #[arg(long)] | ||
| 60 | + config: Option<PathBuf>, | ||
| 61 | + }, | ||
| 58 | Check { | 62 | Check { |
| 59 | #[arg(long)] | 63 | #[arg(long)] |
| 60 | work_dir: Option<PathBuf>, | 64 | work_dir: Option<PathBuf>, |
| @@ -189,6 +193,15 @@ async fn run(cli: Cli) -> Result<ExitCode, Box<dyn std::error::Error>> { | |||
| 189 | ); | 193 | ); |
| 190 | Ok(ExitCode::SUCCESS) | 194 | Ok(ExitCode::SUCCESS) |
| 191 | } | 195 | } |
| 196 | + Command::Unregister { config: path } => { | ||
| 197 | + let path = path.map_or_else(config::default_config_path, Ok)?; | ||
| 198 | + let cfg = config::load(&path)?; | ||
| 199 | + ForgeClient::new(&cfg.url)? | ||
| 200 | + .unregister(&cfg.runner_secret) | ||
| 201 | + .await?; | ||
| 202 | + println!("runner {} removed from {}", cfg.name, cfg.url); | ||
| 203 | + Ok(ExitCode::SUCCESS) | ||
| 204 | + } | ||
| 192 | Command::Run { config: path } => { | 205 | Command::Run { config: path } => { |
| 193 | let path = path.map_or_else(config::default_config_path, Ok)?; | 206 | let path = path.map_or_else(config::default_config_path, Ok)?; |
| 194 | let mut cfg = config::load(&path)?; | 207 | let mut cfg = config::load(&path)?; |
| @@ -236,6 +249,8 @@ async fn run(cli: Cli) -> Result<ExitCode, Box<dyn std::error::Error>> { | |||
| 236 | (Arc::new(executor), map) | 249 | (Arc::new(executor), map) |
| 237 | } | 250 | } |
| 238 | }; | 251 | }; |
| 252 | + let stop_url = cfg.url.clone(); | ||
| 253 | + let stop_secret = cfg.runner_secret.clone(); | ||
| 239 | let mut runner = | 254 | let mut runner = |
| 240 | Runner::new(cfg, executor, RunOptions::default())?.with_pressure(pressure); | 255 | Runner::new(cfg, executor, RunOptions::default())?.with_pressure(pressure); |
| 241 | if cache_cap > 0 { | 256 | if cache_cap > 0 { |
| @@ -248,13 +263,25 @@ async fn run(cli: Cli) -> Result<ExitCode, Box<dyn std::error::Error>> { | |||
| 248 | } | 263 | } |
| 249 | let stop = shutdown.clone(); | 264 | let stop = shutdown.clone(); |
| 250 | tokio::spawn(async move { | 265 | tokio::spawn(async move { |
| 251 | - if tokio::signal::ctrl_c().await.is_ok() { | 266 | + let Ok(mut term) = |
| 252 | - tracing::info!("interrupt received, cancelling running jobs"); | 267 | + tokio::signal::unix::signal(tokio::signal::unix::SignalKind::terminate()) |
| 253 | - stop.cancel(); | 268 | + else { |
| 269 | + return; | ||
| 270 | + }; | ||
| 271 | + tokio::select! { | ||
| 272 | + _ = tokio::signal::ctrl_c() => {} | ||
| 273 | + _ = term.recv() => {} | ||
| 254 | } | 274 | } |
| 275 | + tracing::info!("stop signal received, cancelling running jobs"); | ||
| 276 | + stop.cancel(); | ||
| 255 | }); | 277 | }); |
| 256 | match runner.run(shutdown).await { | 278 | match runner.run(shutdown).await { |
| 257 | - RunEnd::Stopped => Ok(ExitCode::SUCCESS), | 279 | + RunEnd::Stopped => { |
| 280 | + if let Err(e) = ForgeClient::new(&stop_url)?.stopped(&stop_secret).await { | ||
| 281 | + tracing::warn!(error = %e, "could not tell the forge the runner stopped"); | ||
| 282 | + } | ||
| 283 | + Ok(ExitCode::SUCCESS) | ||
| 284 | + } | ||
| 258 | RunEnd::Updated | RunEnd::Restart => Ok(ExitCode::from(update::RESTART_EXIT_CODE)), | 285 | RunEnd::Updated | RunEnd::Restart => Ok(ExitCode::from(update::RESTART_EXIT_CODE)), |
| 259 | } | 286 | } |
| 260 | } | 287 | } |
crates/forge-runner/src/client.rsmodified+22 -0
| @@ -159,6 +159,28 @@ impl ForgeClient { | |||
| 159 | } | 159 | } |
| 160 | } | 160 | } |
| 161 | 161 | ||
| 162 | + pub async fn unregister(&self, runner_secret: &str) -> Result<(), ClientError> { | ||
| 163 | + let resp = self | ||
| 164 | + .http | ||
| 165 | + .delete(self.url("/api/v1/ci/runners/self")) | ||
| 166 | + .bearer_auth(runner_secret) | ||
| 167 | + .timeout(REQUEST_TIMEOUT) | ||
| 168 | + .send() | ||
| 169 | + .await?; | ||
| 170 | + empty_or_error(resp).await | ||
| 171 | + } | ||
| 172 | + | ||
| 173 | + pub async fn stopped(&self, runner_secret: &str) -> Result<(), ClientError> { | ||
| 174 | + let resp = self | ||
| 175 | + .http | ||
| 176 | + .post(self.url("/api/v1/ci/runners/stopped")) | ||
| 177 | + .bearer_auth(runner_secret) | ||
| 178 | + .timeout(REQUEST_TIMEOUT) | ||
| 179 | + .send() | ||
| 180 | + .await?; | ||
| 181 | + empty_or_error(resp).await | ||
| 182 | + } | ||
| 183 | + | ||
| 162 | pub async fn get_config( | 184 | pub async fn get_config( |
| 163 | &self, | 185 | &self, |
| 164 | runner_secret: &str, | 186 | runner_secret: &str, |
crates/forge-web-app/src/alerts.rsmodified+1 -5
| @@ -293,11 +293,7 @@ pub async fn check_runners(state: &AppState, now: i64) { | |||
| 293 | }; | 293 | }; |
| 294 | let mut offline = std::collections::BTreeSet::new(); | 294 | let mut offline = std::collections::BTreeSet::new(); |
| 295 | for runner in &runners { | 295 | for runner in &runners { |
| 296 | - let online = forge_core::store::health::runner_is_online( | 296 | + let online = forge_core::store::health::runner_is_online(runner, now); |
| 297 | - runner.disabled, | ||
| 298 | - runner.last_seen_at.as_deref(), | ||
| 299 | - now, | ||
| 300 | - ); | ||
| 301 | state.ci_live.note_runner_online(&runner.id, online); | 297 | state.ci_live.note_runner_online(&runner.id, online); |
| 302 | } | 298 | } |
| 303 | let ids: Vec<&str> = runners.iter().map(|r| r.id.as_str()).collect(); | 299 | let ids: Vec<&str> = runners.iter().map(|r| r.id.as_str()).collect(); |
crates/forge-web-app/src/ci/api.rsmodified+41 -0
| @@ -476,6 +476,47 @@ async fn runner_binary(cx: &Cx) -> topcoat::Result<Response> { | |||
| 476 | } | 476 | } |
| 477 | } | 477 | } |
| 478 | 478 | ||
| 479 | +#[route(POST "/api/v1/ci/runners/stopped")] | ||
| 480 | +async fn runner_stopped(cx: &Cx) -> topcoat::Result<Response> { | ||
| 481 | + let state = context::<AppState>(cx); | ||
| 482 | + let runner = match runner_from(state, headers(cx)).await { | ||
| 483 | + Ok(runner) => runner, | ||
| 484 | + Err(res) => return Ok(*res), | ||
| 485 | + }; | ||
| 486 | + if let Err(e) = state.store.mark_runner_stopped(&runner.id).await { | ||
| 487 | + return Ok(*api::internal(e)); | ||
| 488 | + } | ||
| 489 | + state.ci_live.note_runner_online(&runner.id, false); | ||
| 490 | + Ok(empty(StatusCode::NO_CONTENT)) | ||
| 491 | +} | ||
| 492 | + | ||
| 493 | +#[route(DELETE "/api/v1/ci/runners/self")] | ||
| 494 | +async fn runner_unregister(cx: &Cx) -> topcoat::Result<Response> { | ||
| 495 | + let state = context::<AppState>(cx); | ||
| 496 | + let runner = match runner_from(state, headers(cx)).await { | ||
| 497 | + Ok(runner) => runner, | ||
| 498 | + Err(res) => return Ok(*res), | ||
| 499 | + }; | ||
| 500 | + if let Err(e) = state.store.delete_runner(&runner.id).await { | ||
| 501 | + return Ok(*api::internal(e)); | ||
| 502 | + } | ||
| 503 | + state.ci_live.bump_runners(); | ||
| 504 | + crate::audit::record( | ||
| 505 | + &state.store, | ||
| 506 | + Some(cx), | ||
| 507 | + crate::audit::Actor::Cli, | ||
| 508 | + forge_core::audit::AuditAction::CiRunnerDeleted, | ||
| 509 | + crate::audit::Target { | ||
| 510 | + kind: "ci_runner", | ||
| 511 | + id: &runner.id, | ||
| 512 | + name: &runner.name, | ||
| 513 | + }, | ||
| 514 | + json!({ "runner_id": runner.id, "by": "runner" }), | ||
| 515 | + ) | ||
| 516 | + .await; | ||
| 517 | + Ok(empty(StatusCode::NO_CONTENT)) | ||
| 518 | +} | ||
| 519 | + | ||
| 479 | const INSTALL_SCRIPT: &str = include_str!("install.sh"); | 520 | const INSTALL_SCRIPT: &str = include_str!("install.sh"); |
| 480 | 521 | ||
| 481 | #[route(GET "/api/v1/ci/runners/install.sh")] | 522 | #[route(GET "/api/v1/ci/runners/install.sh")] |
crates/forge-web-app/src/ci/api_tests.rsmodified+51 -0
| @@ -1418,3 +1418,54 @@ async fn install_script_and_binary_follow_the_registration_token() { | |||
| 1418 | 401 | 1418 | 401 |
| 1419 | ); | 1419 | ); |
| 1420 | } | 1420 | } |
| 1421 | + | ||
| 1422 | +#[tokio::test] | ||
| 1423 | +async fn a_stopped_runner_is_offline_until_it_calls_again_and_can_remove_itself() { | ||
| 1424 | + let env = bare(|_| {}).await; | ||
| 1425 | + let (runner, secret) = runner(&env, &[]).await; | ||
| 1426 | + let now = crate::views::now_unix(); | ||
| 1427 | + let online = |store: Store| async move { | ||
| 1428 | + let found = store.list_runners().await.unwrap(); | ||
| 1429 | + forge_core::store::health::runner_is_online(&found[0], now) | ||
| 1430 | + }; | ||
| 1431 | + let sent = send( | ||
| 1432 | + &env.router, | ||
| 1433 | + "POST", | ||
| 1434 | + "/api/v1/ci/runners/stopped", | ||
| 1435 | + &[bearer(&secret)], | ||
| 1436 | + Vec::new(), | ||
| 1437 | + ) | ||
| 1438 | + .await; | ||
| 1439 | + assert_eq!(sent.status, 204); | ||
| 1440 | + assert!(!online(env.store.clone()).await); | ||
| 1441 | + tokio::time::sleep(std::time::Duration::from_millis(1100)).await; | ||
| 1442 | + env.store.runner_by_secret(&secret).await.unwrap(); | ||
| 1443 | + assert!(online(env.store.clone()).await); | ||
| 1444 | + | ||
| 1445 | + let sent = send( | ||
| 1446 | + &env.router, | ||
| 1447 | + "DELETE", | ||
| 1448 | + "/api/v1/ci/runners/self", | ||
| 1449 | + &[bearer(&secret)], | ||
| 1450 | + Vec::new(), | ||
| 1451 | + ) | ||
| 1452 | + .await; | ||
| 1453 | + assert_eq!(sent.status, 204); | ||
| 1454 | + assert!( | ||
| 1455 | + env.store | ||
| 1456 | + .list_runners() | ||
| 1457 | + .await | ||
| 1458 | + .unwrap() | ||
| 1459 | + .iter() | ||
| 1460 | + .all(|r| r.id != runner.id) | ||
| 1461 | + ); | ||
| 1462 | + let sent = send( | ||
| 1463 | + &env.router, | ||
| 1464 | + "DELETE", | ||
| 1465 | + "/api/v1/ci/runners/self", | ||
| 1466 | + &[bearer(&secret)], | ||
| 1467 | + Vec::new(), | ||
| 1468 | + ) | ||
| 1469 | + .await; | ||
| 1470 | + assert_eq!(sent.status, 401); | ||
| 1471 | +} | ||
crates/forge-web-app/src/ci/install.shmodified+11 -1
| @@ -40,6 +40,12 @@ uninstall() { | |||
| 40 | id "$RUNNER_USER" >/dev/null 2>&1 || fail "there is no user $RUNNER_USER" | 40 | id "$RUNNER_USER" >/dev/null 2>&1 || fail "there is no user $RUNNER_USER" |
| 41 | home=$(getent passwd "$RUNNER_USER" | cut -d: -f6) | 41 | home=$(getent passwd "$RUNNER_USER" | cut -d: -f6) |
| 42 | [ -f "$home/.config/forge-runner/runner.toml" ] || fail "$RUNNER_USER has no forge runner, so it is not removed" | 42 | [ -f "$home/.config/forge-runner/runner.toml" ] || fail "$RUNNER_USER has no forge runner, so it is not removed" |
| 43 | + user_ctl stop forge-runner.service 2>/dev/null || true | ||
| 44 | + if as_user "$home/.local/bin/forge" runner unregister; then | ||
| 45 | + removed_on_forge=1 | ||
| 46 | + else | ||
| 47 | + removed_on_forge=0 | ||
| 48 | + fi | ||
| 43 | loginctl disable-linger "$RUNNER_USER" || true | 49 | loginctl disable-linger "$RUNNER_USER" || true |
| 44 | loginctl terminate-user "$RUNNER_USER" 2>/dev/null || true | 50 | loginctl terminate-user "$RUNNER_USER" 2>/dev/null || true |
| 45 | pkill -KILL -u "$RUNNER_USER" || true | 51 | pkill -KILL -u "$RUNNER_USER" || true |
| @@ -49,7 +55,11 @@ uninstall() { | |||
| 49 | /home/?*) [ -d "$home" ] && rm -rf --one-file-system -- "$home" ;; | 55 | /home/?*) [ -d "$home" ] && rm -rf --one-file-system -- "$home" ;; |
| 50 | esac | 56 | esac |
| 51 | sed -i "/^$RUNNER_USER:/d" /etc/subuid /etc/subgid | 57 | sed -i "/^$RUNNER_USER:/d" /etc/subuid /etc/subgid |
| 52 | - echo "removed $RUNNER_USER. Delete the runner at $URL/admin/runners too." | 58 | + if [ "$removed_on_forge" = 1 ]; then |
| 59 | + echo "removed $RUNNER_USER and its runner on $URL" | ||
| 60 | + else | ||
| 61 | + echo "removed $RUNNER_USER. The forge did not accept the unregister: delete the runner at $URL/admin/runners" | ||
| 62 | + fi | ||
| 53 | } | 63 | } |
| 54 | 64 | ||
| 55 | install_runner() { | 65 | install_runner() { |
crates/forge-web-pages/src/pages/admin_runners.rsmodified+11 -2
| @@ -156,7 +156,13 @@ fn dot_of(lang: Lang, runner: &CiRunner, now: i64) -> (&'static str, &'static st | |||
| 156 | if runner.disabled { | 156 | if runner.disabled { |
| 157 | return ("runner-dot is-disabled", g::t(lang, K::Disabled)); | 157 | return ("runner-dot is-disabled", g::t(lang, K::Disabled)); |
| 158 | } | 158 | } |
| 159 | - if runner_is_online(false, runner.last_seen_at.as_deref(), now) { | 159 | + if runner_is_online( |
| 160 | + &CiRunner { | ||
| 161 | + disabled: false, | ||
| 162 | + ..runner.clone() | ||
| 163 | + }, | ||
| 164 | + now, | ||
| 165 | + ) { | ||
| 160 | ("runner-dot is-online", s(lang, "online", "çevrim içi")) | 166 | ("runner-dot is-online", s(lang, "online", "çevrim içi")) |
| 161 | } else { | 167 | } else { |
| 162 | ("runner-dot is-offline", s(lang, "offline", "çevrim dışı")) | 168 | ("runner-dot is-offline", s(lang, "offline", "çevrim dışı")) |
| @@ -602,6 +608,9 @@ fn field_rows(runner: &CiRunner) -> Vec<FieldRow> { | |||
| 602 | let reported = runner.reported_config.get(field.key); | 608 | let reported = runner.reported_config.get(field.key); |
| 603 | let overridden = if field.key == "concurrency" { | 609 | let overridden = if field.key == "concurrency" { |
| 604 | runner.concurrency_override.map(serde_json::Value::from) | 610 | runner.concurrency_override.map(serde_json::Value::from) |
| 611 | + } else if field.key == "name" { | ||
| 612 | + (reported.and_then(serde_json::Value::as_str) != Some(runner.name.as_str())) | ||
| 613 | + .then(|| serde_json::Value::from(runner.name.as_str())) | ||
| 605 | } else { | 614 | } else { |
| 606 | runner.config_overrides.get(field.key).cloned() | 615 | runner.config_overrides.get(field.key).cloned() |
| 607 | }; | 616 | }; |
| @@ -641,7 +650,7 @@ const TABS: [(&str, &[&str]); 8] = [ | |||
| 641 | ("overview", &[]), | 650 | ("overview", &[]), |
| 642 | ( | 651 | ( |
| 643 | "general", | 652 | "general", |
| 644 | - &["concurrency", "labels", "executor", "auto_update"], | 653 | + &["name", "concurrency", "labels", "executor", "auto_update"], |
| 645 | ), | 654 | ), |
| 646 | ("jobs", &[]), | 655 | ("jobs", &[]), |
| 647 | ( | 656 | ( |
crates/forge-web/src/routes.snapmodified+2 -0
| @@ -245,6 +245,8 @@ route /api/v1/ci/runners/install/forge Only([GET]) | |||
| 245 | route /api/v1/ci/runners/log Only([POST]) | 245 | route /api/v1/ci/runners/log Only([POST]) |
| 246 | route /api/v1/ci/runners/metrics Only([POST]) | 246 | route /api/v1/ci/runners/metrics Only([POST]) |
| 247 | route /api/v1/ci/runners/register Only([POST]) | 247 | route /api/v1/ci/runners/register Only([POST]) |
| 248 | +route /api/v1/ci/runners/self Only([DELETE]) | ||
| 249 | +route /api/v1/ci/runners/stopped Only([POST]) | ||
| 248 | route /api/v1/repos/{owner}/{repo} Only([GET]) | 250 | route /api/v1/repos/{owner}/{repo} Only([GET]) |
| 249 | route /api/v1/repos/{owner}/{repo}/commits/{sha}/statuses Only([GET]) | 251 | route /api/v1/repos/{owner}/{repo}/commits/{sha}/statuses Only([GET]) |
| 250 | route /api/v1/repos/{owner}/{repo}/issues Only([GET]) | 252 | route /api/v1/repos/{owner}/{repo}/issues Only([GET]) |
docs/ci.mdmodified+8 -5
| @@ -496,8 +496,9 @@ It installs `git`, `passt`, `newuidmap` and `systemd-container`, creates the use | |||
| 496 | subordinate id range and lingering, downloads the forge's own binary (the token authorizes the | 496 | subordinate id range and lingering, downloads the forge's own binary (the token authorizes the |
| 497 | download, and the script checks its sha256), runs `forge runner check`, registers, and starts the | 497 | download, and the script checks its sha256), runs `forge runner check`, registers, and starts the |
| 498 | systemd user service. Options: `--name` (default: the hostname), `--labels`, `--user` (default | 498 | systemd user service. Options: `--name` (default: the hostname), `--labels`, `--user` (default |
| 499 | -`ci`). `--uninstall` removes the runner user, its files and its id ranges; it refuses a user that | 499 | +`ci`). `--uninstall` stops the runner, removes it from the forge with its own secret |
| 500 | -has no `runner.toml`. The steps below do the same by hand. | 500 | +(`forge runner unregister`), then removes the runner user, its files and its id ranges; it refuses a |
| 501 | +user that has no `runner.toml`. The steps below do the same by hand. | ||
| 501 | 502 | ||
| 502 | ### 1. Check the host | 503 | ### 1. Check the host |
| 503 | 504 | ||
| @@ -515,10 +516,11 @@ The builtin executor needs: | |||
| 515 | Run the check: | 516 | Run the check: |
| 516 | 517 | ||
| 517 | ```sh | 518 | ```sh |
| 518 | -forge runner check | 519 | +systemd-run --user -P forge runner check |
| 519 | ``` | 520 | ``` |
| 520 | 521 | ||
| 521 | -It runs one trivial job through the real sandbox. It prints `ok` or `FAIL` for each requirement, | 522 | +Run it under the user's systemd, as the service will run: a plain `su` or `machinectl shell` session |
| 523 | +cannot create job cgroups, so it reports a false cgroup failure. It runs one trivial job through the real sandbox. It prints `ok` or `FAIL` for each requirement, | ||
| 522 | with the reason, and exits non-zero when a check fails. Pass `--work-dir` to test the filesystem | 524 | with the reason, and exits non-zero when a check fails. Pass `--work-dir` to test the filesystem |
| 523 | that your jobs will use. | 525 | that your jobs will use. |
| 524 | 526 | ||
| @@ -757,7 +759,8 @@ systemctl --user enable --now forge-runner.service | |||
| 757 | journalctl --user -u forge-runner.service -f | 759 | journalctl --user -u forge-runner.service -f |
| 758 | ``` | 760 | ``` |
| 759 | 761 | ||
| 760 | -On shutdown the runner stops claiming, and it cancels and reports any job still running. A job | 762 | +On SIGTERM or SIGINT the runner stops claiming, cancels and reports any job still running, and tells |
| 763 | +the forge it stopped, so it shows offline at once instead of after 90 seconds without contact. A job | ||
| 761 | whose runner disappears without reporting is failed as `runner lost` after about two minutes, with | 764 | whose runner disappears without reporting is failed as `runner lost` after about two minutes, with |
| 762 | no heartbeat. | 765 | no heartbeat. |
| 763 | 766 | ||