From 2e29cbcf4cef4a19ff87691bfec4a1cced5f963e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ahmet=20Kaan=20G=C3=BCm=C3=BC=C5=9F?= Date: Tue, 1 Dec 2026 23:11:57 +0300 Subject: [PATCH] =?UTF-8?q?=E2=9C=A8=20feat:=20runners=20handle=20SIGTERM,?= =?UTF-8?q?=20report=20a=20clean=20stop=20so=20they=20show=20offline=20at?= =?UTF-8?q?=20once,=20and=20can=20unregister=20themselves=20(install.sh=20?= =?UTF-8?q?--uninstall=20uses=20it);=20runner=20name=20is=20editable=20fro?= =?UTF-8?q?m=20the=20admin=20page;=20docs:=20runner=20check=20runs=20under?= =?UTF-8?q?=20systemd-run=20--user?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../migrations/0077_runner_stopped_at.sql | 1 + crates/forge-core/src/ci.rs | 10 +++- crates/forge-core/src/store/ci.rs | 54 ++++++++++++++++++- crates/forge-core/src/store/health.rs | 12 +++-- crates/forge-core/src/store/migrate.rs | 4 ++ crates/forge-runner/src/cli.rs | 35 ++++++++++-- crates/forge-runner/src/client.rs | 22 ++++++++ crates/forge-web-app/src/alerts.rs | 6 +-- crates/forge-web-app/src/ci/api.rs | 41 ++++++++++++++ crates/forge-web-app/src/ci/api_tests.rs | 51 ++++++++++++++++++ crates/forge-web-app/src/ci/install.sh | 12 ++++- .../src/pages/admin_runners.rs | 13 ++++- crates/forge-web/src/routes.snap | 2 + docs/ci.md | 13 +++-- 14 files changed, 253 insertions(+), 23 deletions(-) create mode 100644 crates/forge-core/migrations/0077_runner_stopped_at.sql diff --git a/crates/forge-core/migrations/0077_runner_stopped_at.sql b/crates/forge-core/migrations/0077_runner_stopped_at.sql new file mode 100644 index 0000000..6828818 --- /dev/null +++ b/crates/forge-core/migrations/0077_runner_stopped_at.sql @@ -0,0 +1 @@ +ALTER TABLE ci_runners ADD COLUMN stopped_at TEXT; diff --git a/crates/forge-core/src/ci.rs b/crates/forge-core/src/ci.rs index 90711ea..80081a7 100644 --- a/crates/forge-core/src/ci.rs +++ b/crates/forge-core/src/ci.rs @@ -77,6 +77,7 @@ pub struct CiRunner { pub labels: Vec, pub created_at: String, pub last_seen_at: Option, + pub stopped_at: Option, pub disabled: bool, pub concurrency_override: Option, pub reported: RunnerReport, @@ -176,7 +177,7 @@ pub const RUNNER_FIELDS: &[RunnerField] = &[ }, RunnerField { key: "name", - kind: FieldKind::ReadOnly, + kind: FieldKind::Live, }, RunnerField { key: "url", @@ -225,6 +226,13 @@ pub fn validate_runner_field( i64::from(MAX_CONCURRENCY), "concurrency", ), + "name" => { + if raw.is_empty() || raw.len() > 100 { + Err("a runner name needs 1 to 100 bytes".into()) + } else { + Ok(Value::from(raw)) + } + } "labels" => { let labels: Vec = raw .split(',') diff --git a/crates/forge-core/src/store/ci.rs b/crates/forge-core/src/store/ci.rs index bbdcecd..d88fd54 100644 --- a/crates/forge-core/src/store/ci.rs +++ b/crates/forge-core/src/store/ci.rs @@ -29,7 +29,7 @@ const RUNNER_COLS: &str = "id, name, labels, created_at, last_seen_at, disabled, reported_memory_bytes, reported_config, config_overrides, \ (SELECT COUNT(*) FROM ci_jobs WHERE ci_jobs.runner_id = ci_runners.id AND ci_jobs.state = 'running'), \ reported_build, reported_boot_id, restart_mode, restart_requested_at, reported_capabilities, \ - reported_memory_budget, reported_memory_free, reported_memory_reserve"; + reported_memory_budget, reported_memory_free, reported_memory_reserve, stopped_at"; const RUNNER_JOB_COLS: &str = "j.id, j.run_id, j.name, j.spec, j.state, j.runner_id, j.exit_code, \ j.message, j.queued_at, j.started_at, j.finished_at, j.heartbeat_at, j.cancel_requested, \ j.log_bytes, j.oom_kills, r.number, u.username, p.name"; @@ -50,6 +50,7 @@ fn map_runner(row: &Row) -> Result { labels, created_at: col_text(row, 3)?, last_seen_at: col_opt_text(row, 4)?, + stopped_at: col_opt_text(row, 22)?, disabled: col_bool(row, 5)?, concurrency_override: opt_u32(row, 6)?, reported: RunnerReport { @@ -444,6 +445,17 @@ impl Store { Ok(token) } + pub async fn mark_runner_stopped(&self, id: &str) -> Result<()> { + let conn = self.inner.conn.lock().await; + conn.execute( + "UPDATE ci_runners SET stopped_at = last_seen_at WHERE id = ?1", + (id.to_owned(),), + ) + .await + .map_err(db_err)?; + Ok(()) + } + pub async fn registration_token_used(&self, token_hash: &str) -> Result { let conn = self.inner.conn.lock().await; let mut rows = conn @@ -660,6 +672,21 @@ impl Store { Some(raw) => Some(validate_runner_field(key, raw).map_err(Error::Invalid)?), None => None, }; + if field.key == "name" { + let conn = self.inner.conn.lock().await; + let runner = load_runner(&conn, id).await?.ok_or(Error::NotFound)?; + let name = parsed + .or_else(|| runner.reported_config.get("name").cloned()) + .and_then(|v| v.as_str().map(str::to_owned)) + .ok_or_else(|| Error::Invalid("the runner never reported its name".into()))?; + conn.execute( + "UPDATE ci_runners SET name = ?2 WHERE id = ?1", + (id.to_owned(), name), + ) + .await + .map_err(db_err)?; + return Ok(()); + } if field.key == "concurrency" { let n = parsed.as_ref().and_then(serde_json::Value::as_u64); return self @@ -2167,6 +2194,7 @@ mod tests { labels: labels.iter().map(|s| s.to_string()).collect(), created_at: now_stamp(), last_seen_at: None, + stopped_at: None, disabled: false, concurrency_override: None, reported: RunnerReport::default(), @@ -2177,6 +2205,30 @@ mod tests { } } + #[tokio::test] + async fn runner_name_can_be_changed_and_never_emptied() { + let fx = fixture().await; + let (runner, _) = runner_with(&fx.store, &fx.tahinli.id, &[]).await; + fx.store + .set_runner_field(&runner.id, "name", Some("beefy-1")) + .await + .unwrap(); + let empty = fx + .store + .set_runner_field(&runner.id, "name", Some(" ")) + .await; + assert!(matches!(empty, Err(Error::Invalid(_))), "{empty:?}"); + let names: Vec = fx + .store + .list_runners() + .await + .unwrap() + .into_iter() + .map(|r| r.name) + .collect(); + assert_eq!(names, vec!["beefy-1".to_string()]); + } + #[tokio::test] async fn registration_token_is_single_use_and_expires() { let fx = fixture().await; diff --git a/crates/forge-core/src/store/health.rs b/crates/forge-core/src/store/health.rs index 07fc41e..09e88b1 100644 --- a/crates/forge-core/src/store/health.rs +++ b/crates/forge-core/src/store/health.rs @@ -1,12 +1,15 @@ use super::{Store, col_int, fetch_opt}; +use crate::ci::CiRunner; use crate::error::{Error, Result}; use crate::time::{stamp_ago, stamp_to_unix}; pub const RUNNER_ONLINE_SECS: i64 = 90; -pub fn runner_is_online(disabled: bool, last_seen_at: Option<&str>, now_unix: i64) -> bool { - !disabled - && last_seen_at +pub fn runner_is_online(runner: &CiRunner, now_unix: i64) -> bool { + let seen = runner.last_seen_at.as_deref(); + !runner.disabled + && runner.stopped_at.as_deref() != seen + && seen .and_then(stamp_to_unix) .is_some_and(|seen| now_unix.saturating_sub(seen) <= RUNNER_ONLINE_SECS) } @@ -38,7 +41,8 @@ impl Store { }; let online = fetch_opt( &conn, - "SELECT COUNT(*) FROM ci_runners WHERE disabled = 0 AND last_seen_at > ?1", + "SELECT COUNT(*) FROM ci_runners WHERE disabled = 0 AND last_seen_at > ?1 \ + AND stopped_at IS NOT last_seen_at", (since,), |row| col_int(row, 0), ) diff --git a/crates/forge-core/src/store/migrate.rs b/crates/forge-core/src/store/migrate.rs index 1f1d199..8f27a2a 100644 --- a/crates/forge-core/src/store/migrate.rs +++ b/crates/forge-core/src/store/migrate.rs @@ -139,6 +139,10 @@ pub const MIGRATIONS: &[(u32, &str)] = &[ 76, include_str!("../../migrations/0076_milestone_title_repair.sql"), ), + ( + 77, + include_str!("../../migrations/0077_runner_stopped_at.sql"), + ), ]; pub fn latest_schema_version() -> u32 { diff --git a/crates/forge-runner/src/cli.rs b/crates/forge-runner/src/cli.rs index aed2e23..6c12195 100644 --- a/crates/forge-runner/src/cli.rs +++ b/crates/forge-runner/src/cli.rs @@ -55,6 +55,10 @@ enum Command { #[arg(long)] config: Option, }, + Unregister { + #[arg(long)] + config: Option, + }, Check { #[arg(long)] work_dir: Option, @@ -189,6 +193,15 @@ async fn run(cli: Cli) -> Result> { ); Ok(ExitCode::SUCCESS) } + Command::Unregister { config: path } => { + let path = path.map_or_else(config::default_config_path, Ok)?; + let cfg = config::load(&path)?; + ForgeClient::new(&cfg.url)? + .unregister(&cfg.runner_secret) + .await?; + println!("runner {} removed from {}", cfg.name, cfg.url); + Ok(ExitCode::SUCCESS) + } Command::Run { config: path } => { let path = path.map_or_else(config::default_config_path, Ok)?; let mut cfg = config::load(&path)?; @@ -236,6 +249,8 @@ async fn run(cli: Cli) -> Result> { (Arc::new(executor), map) } }; + let stop_url = cfg.url.clone(); + let stop_secret = cfg.runner_secret.clone(); let mut runner = Runner::new(cfg, executor, RunOptions::default())?.with_pressure(pressure); if cache_cap > 0 { @@ -248,13 +263,25 @@ async fn run(cli: Cli) -> Result> { } let stop = shutdown.clone(); tokio::spawn(async move { - if tokio::signal::ctrl_c().await.is_ok() { - tracing::info!("interrupt received, cancelling running jobs"); - stop.cancel(); + let Ok(mut term) = + tokio::signal::unix::signal(tokio::signal::unix::SignalKind::terminate()) + else { + return; + }; + tokio::select! { + _ = tokio::signal::ctrl_c() => {} + _ = term.recv() => {} } + tracing::info!("stop signal received, cancelling running jobs"); + stop.cancel(); }); match runner.run(shutdown).await { - RunEnd::Stopped => Ok(ExitCode::SUCCESS), + RunEnd::Stopped => { + if let Err(e) = ForgeClient::new(&stop_url)?.stopped(&stop_secret).await { + tracing::warn!(error = %e, "could not tell the forge the runner stopped"); + } + Ok(ExitCode::SUCCESS) + } RunEnd::Updated | RunEnd::Restart => Ok(ExitCode::from(update::RESTART_EXIT_CODE)), } } diff --git a/crates/forge-runner/src/client.rs b/crates/forge-runner/src/client.rs index 207034b..0ad21cd 100644 --- a/crates/forge-runner/src/client.rs +++ b/crates/forge-runner/src/client.rs @@ -159,6 +159,28 @@ impl ForgeClient { } } + pub async fn unregister(&self, runner_secret: &str) -> Result<(), ClientError> { + let resp = self + .http + .delete(self.url("/api/v1/ci/runners/self")) + .bearer_auth(runner_secret) + .timeout(REQUEST_TIMEOUT) + .send() + .await?; + empty_or_error(resp).await + } + + pub async fn stopped(&self, runner_secret: &str) -> Result<(), ClientError> { + let resp = self + .http + .post(self.url("/api/v1/ci/runners/stopped")) + .bearer_auth(runner_secret) + .timeout(REQUEST_TIMEOUT) + .send() + .await?; + empty_or_error(resp).await + } + pub async fn get_config( &self, runner_secret: &str, diff --git a/crates/forge-web-app/src/alerts.rs b/crates/forge-web-app/src/alerts.rs index ed71bdb..4f8314f 100644 --- a/crates/forge-web-app/src/alerts.rs +++ b/crates/forge-web-app/src/alerts.rs @@ -293,11 +293,7 @@ pub async fn check_runners(state: &AppState, now: i64) { }; let mut offline = std::collections::BTreeSet::new(); for runner in &runners { - let online = forge_core::store::health::runner_is_online( - runner.disabled, - runner.last_seen_at.as_deref(), - now, - ); + let online = forge_core::store::health::runner_is_online(runner, now); state.ci_live.note_runner_online(&runner.id, online); } let ids: Vec<&str> = runners.iter().map(|r| r.id.as_str()).collect(); diff --git a/crates/forge-web-app/src/ci/api.rs b/crates/forge-web-app/src/ci/api.rs index 42daa3c..1efeba8 100644 --- a/crates/forge-web-app/src/ci/api.rs +++ b/crates/forge-web-app/src/ci/api.rs @@ -476,6 +476,47 @@ async fn runner_binary(cx: &Cx) -> topcoat::Result { } } +#[route(POST "/api/v1/ci/runners/stopped")] +async fn runner_stopped(cx: &Cx) -> topcoat::Result { + let state = context::(cx); + let runner = match runner_from(state, headers(cx)).await { + Ok(runner) => runner, + Err(res) => return Ok(*res), + }; + if let Err(e) = state.store.mark_runner_stopped(&runner.id).await { + return Ok(*api::internal(e)); + } + state.ci_live.note_runner_online(&runner.id, false); + Ok(empty(StatusCode::NO_CONTENT)) +} + +#[route(DELETE "/api/v1/ci/runners/self")] +async fn runner_unregister(cx: &Cx) -> topcoat::Result { + let state = context::(cx); + let runner = match runner_from(state, headers(cx)).await { + Ok(runner) => runner, + Err(res) => return Ok(*res), + }; + if let Err(e) = state.store.delete_runner(&runner.id).await { + return Ok(*api::internal(e)); + } + state.ci_live.bump_runners(); + crate::audit::record( + &state.store, + Some(cx), + crate::audit::Actor::Cli, + forge_core::audit::AuditAction::CiRunnerDeleted, + crate::audit::Target { + kind: "ci_runner", + id: &runner.id, + name: &runner.name, + }, + json!({ "runner_id": runner.id, "by": "runner" }), + ) + .await; + Ok(empty(StatusCode::NO_CONTENT)) +} + const INSTALL_SCRIPT: &str = include_str!("install.sh"); #[route(GET "/api/v1/ci/runners/install.sh")] diff --git a/crates/forge-web-app/src/ci/api_tests.rs b/crates/forge-web-app/src/ci/api_tests.rs index b35aaad..f8b8f86 100644 --- a/crates/forge-web-app/src/ci/api_tests.rs +++ b/crates/forge-web-app/src/ci/api_tests.rs @@ -1418,3 +1418,54 @@ async fn install_script_and_binary_follow_the_registration_token() { 401 ); } + +#[tokio::test] +async fn a_stopped_runner_is_offline_until_it_calls_again_and_can_remove_itself() { + let env = bare(|_| {}).await; + let (runner, secret) = runner(&env, &[]).await; + let now = crate::views::now_unix(); + let online = |store: Store| async move { + let found = store.list_runners().await.unwrap(); + forge_core::store::health::runner_is_online(&found[0], now) + }; + let sent = send( + &env.router, + "POST", + "/api/v1/ci/runners/stopped", + &[bearer(&secret)], + Vec::new(), + ) + .await; + assert_eq!(sent.status, 204); + assert!(!online(env.store.clone()).await); + tokio::time::sleep(std::time::Duration::from_millis(1100)).await; + env.store.runner_by_secret(&secret).await.unwrap(); + assert!(online(env.store.clone()).await); + + let sent = send( + &env.router, + "DELETE", + "/api/v1/ci/runners/self", + &[bearer(&secret)], + Vec::new(), + ) + .await; + assert_eq!(sent.status, 204); + assert!( + env.store + .list_runners() + .await + .unwrap() + .iter() + .all(|r| r.id != runner.id) + ); + let sent = send( + &env.router, + "DELETE", + "/api/v1/ci/runners/self", + &[bearer(&secret)], + Vec::new(), + ) + .await; + assert_eq!(sent.status, 401); +} diff --git a/crates/forge-web-app/src/ci/install.sh b/crates/forge-web-app/src/ci/install.sh index f2fd6a3..2e3045b 100644 --- a/crates/forge-web-app/src/ci/install.sh +++ b/crates/forge-web-app/src/ci/install.sh @@ -40,6 +40,12 @@ uninstall() { id "$RUNNER_USER" >/dev/null 2>&1 || fail "there is no user $RUNNER_USER" home=$(getent passwd "$RUNNER_USER" | cut -d: -f6) [ -f "$home/.config/forge-runner/runner.toml" ] || fail "$RUNNER_USER has no forge runner, so it is not removed" + user_ctl stop forge-runner.service 2>/dev/null || true + if as_user "$home/.local/bin/forge" runner unregister; then + removed_on_forge=1 + else + removed_on_forge=0 + fi loginctl disable-linger "$RUNNER_USER" || true loginctl terminate-user "$RUNNER_USER" 2>/dev/null || true pkill -KILL -u "$RUNNER_USER" || true @@ -49,7 +55,11 @@ uninstall() { /home/?*) [ -d "$home" ] && rm -rf --one-file-system -- "$home" ;; esac sed -i "/^$RUNNER_USER:/d" /etc/subuid /etc/subgid - echo "removed $RUNNER_USER. Delete the runner at $URL/admin/runners too." + if [ "$removed_on_forge" = 1 ]; then + echo "removed $RUNNER_USER and its runner on $URL" + else + echo "removed $RUNNER_USER. The forge did not accept the unregister: delete the runner at $URL/admin/runners" + fi } install_runner() { diff --git a/crates/forge-web-pages/src/pages/admin_runners.rs b/crates/forge-web-pages/src/pages/admin_runners.rs index dc77ff9..2c3ce1d 100644 --- a/crates/forge-web-pages/src/pages/admin_runners.rs +++ b/crates/forge-web-pages/src/pages/admin_runners.rs @@ -156,7 +156,13 @@ fn dot_of(lang: Lang, runner: &CiRunner, now: i64) -> (&'static str, &'static st if runner.disabled { return ("runner-dot is-disabled", g::t(lang, K::Disabled)); } - if runner_is_online(false, runner.last_seen_at.as_deref(), now) { + if runner_is_online( + &CiRunner { + disabled: false, + ..runner.clone() + }, + now, + ) { ("runner-dot is-online", s(lang, "online", "çevrim içi")) } else { ("runner-dot is-offline", s(lang, "offline", "çevrim dışı")) @@ -602,6 +608,9 @@ fn field_rows(runner: &CiRunner) -> Vec { let reported = runner.reported_config.get(field.key); let overridden = if field.key == "concurrency" { runner.concurrency_override.map(serde_json::Value::from) + } else if field.key == "name" { + (reported.and_then(serde_json::Value::as_str) != Some(runner.name.as_str())) + .then(|| serde_json::Value::from(runner.name.as_str())) } else { runner.config_overrides.get(field.key).cloned() }; @@ -641,7 +650,7 @@ const TABS: [(&str, &[&str]); 8] = [ ("overview", &[]), ( "general", - &["concurrency", "labels", "executor", "auto_update"], + &["name", "concurrency", "labels", "executor", "auto_update"], ), ("jobs", &[]), ( diff --git a/crates/forge-web/src/routes.snap b/crates/forge-web/src/routes.snap index 0dca597..dc22517 100644 --- a/crates/forge-web/src/routes.snap +++ b/crates/forge-web/src/routes.snap @@ -245,6 +245,8 @@ route /api/v1/ci/runners/install/forge Only([GET]) route /api/v1/ci/runners/log Only([POST]) route /api/v1/ci/runners/metrics Only([POST]) route /api/v1/ci/runners/register Only([POST]) +route /api/v1/ci/runners/self Only([DELETE]) +route /api/v1/ci/runners/stopped Only([POST]) route /api/v1/repos/{owner}/{repo} Only([GET]) route /api/v1/repos/{owner}/{repo}/commits/{sha}/statuses Only([GET]) route /api/v1/repos/{owner}/{repo}/issues Only([GET]) diff --git a/docs/ci.md b/docs/ci.md index 3e5e958..6acc68c 100644 --- a/docs/ci.md +++ b/docs/ci.md @@ -496,8 +496,9 @@ It installs `git`, `passt`, `newuidmap` and `systemd-container`, creates the use subordinate id range and lingering, downloads the forge's own binary (the token authorizes the download, and the script checks its sha256), runs `forge runner check`, registers, and starts the systemd user service. Options: `--name` (default: the hostname), `--labels`, `--user` (default -`ci`). `--uninstall` removes the runner user, its files and its id ranges; it refuses a user that -has no `runner.toml`. The steps below do the same by hand. +`ci`). `--uninstall` stops the runner, removes it from the forge with its own secret +(`forge runner unregister`), then removes the runner user, its files and its id ranges; it refuses a +user that has no `runner.toml`. The steps below do the same by hand. ### 1. Check the host @@ -515,10 +516,11 @@ The builtin executor needs: Run the check: ```sh -forge runner check +systemd-run --user -P forge runner check ``` -It runs one trivial job through the real sandbox. It prints `ok` or `FAIL` for each requirement, +Run it under the user's systemd, as the service will run: a plain `su` or `machinectl shell` session +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, with the reason, and exits non-zero when a check fails. Pass `--work-dir` to test the filesystem that your jobs will use. @@ -757,7 +759,8 @@ systemctl --user enable --now forge-runner.service journalctl --user -u forge-runner.service -f ``` -On shutdown the runner stops claiming, and it cancels and reports any job still running. A job +On SIGTERM or SIGINT the runner stops claiming, cancels and reports any job still running, and tells +the forge it stopped, so it shows offline at once instead of after 90 seconds without contact. A job whose runner disappears without reporting is failed as `runner lost` after about two minutes, with no heartbeat.