forge
Explore
Log in

Don't you dare go Hollow

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 commit

2e29cbcf4cef4a19ff87691bfec4a1cced5f963eAhmet Kaan GümüşParent: 8298537
Some checks failed
Show checks
  • 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
Show full message
✨ 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
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 {
7777 pub labels: Vec<String>,
7878 pub created_at: String,
7979 pub last_seen_at: Option<String>,
80+ pub stopped_at: Option<String>,
8081 pub disabled: bool,
8182 pub concurrency_override: Option<u32>,
8283 pub reported: RunnerReport,
@@ -176,7 +177,7 @@ pub const RUNNER_FIELDS: &[RunnerField] = &[
176177 },
177178 RunnerField {
178179 key: "name",
179- kind: FieldKind::ReadOnly,
180+ kind: FieldKind::Live,
180181 },
181182 RunnerField {
182183 key: "url",
@@ -225,6 +226,13 @@ pub fn validate_runner_field(
225226 i64::from(MAX_CONCURRENCY),
226227 "concurrency",
227228 ),
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+ }
228236 "labels" => {
229237 let labels: Vec<String> = raw
230238 .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,
2929 reported_memory_bytes, reported_config, config_overrides, \
3030 (SELECT COUNT(*) FROM ci_jobs WHERE ci_jobs.runner_id = ci_runners.id AND ci_jobs.state = 'running'), \
3131 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";
3333 const RUNNER_JOB_COLS: &str = "j.id, j.run_id, j.name, j.spec, j.state, j.runner_id, j.exit_code, \
3434 j.message, j.queued_at, j.started_at, j.finished_at, j.heartbeat_at, j.cancel_requested, \
3535 j.log_bytes, j.oom_kills, r.number, u.username, p.name";
@@ -50,6 +50,7 @@ fn map_runner(row: &Row) -> Result<CiRunner> {
5050 labels,
5151 created_at: col_text(row, 3)?,
5252 last_seen_at: col_opt_text(row, 4)?,
53+ stopped_at: col_opt_text(row, 22)?,
5354 disabled: col_bool(row, 5)?,
5455 concurrency_override: opt_u32(row, 6)?,
5556 reported: RunnerReport {
@@ -444,6 +445,17 @@ impl Store {
444445 Ok(token)
445446 }
446447
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+
447459 pub async fn registration_token_used(&self, token_hash: &str) -> Result<bool> {
448460 let conn = self.inner.conn.lock().await;
449461 let mut rows = conn
@@ -660,6 +672,21 @@ impl Store {
660672 Some(raw) => Some(validate_runner_field(key, raw).map_err(Error::Invalid)?),
661673 None => None,
662674 };
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+ }
663690 if field.key == "concurrency" {
664691 let n = parsed.as_ref().and_then(serde_json::Value::as_u64);
665692 return self
@@ -2167,6 +2194,7 @@ mod tests {
21672194 labels: labels.iter().map(|s| s.to_string()).collect(),
21682195 created_at: now_stamp(),
21692196 last_seen_at: None,
2197+ stopped_at: None,
21702198 disabled: false,
21712199 concurrency_override: None,
21722200 reported: RunnerReport::default(),
@@ -2177,6 +2205,30 @@ mod tests {
21772205 }
21782206 }
21792207
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+
21802232 #[tokio::test]
21812233 async fn registration_token_is_single_use_and_expires() {
21822234 let fx = fixture().await;
crates/forge-core/src/store/health.rsmodified+8 -4
@@ -1,12 +1,15 @@
11 use super::{Store, col_int, fetch_opt};
2+use crate::ci::CiRunner;
23 use crate::error::{Error, Result};
34 use crate::time::{stamp_ago, stamp_to_unix};
45
56 pub const RUNNER_ONLINE_SECS: i64 = 90;
67
7-pub fn runner_is_online(disabled: bool, last_seen_at: Option<&str>, now_unix: i64) -> bool {
8- !disabled
9- && last_seen_at
8+pub fn runner_is_online(runner: &CiRunner, now_unix: i64) -> bool {
9+ let seen = runner.last_seen_at.as_deref();
10+ !runner.disabled
11+ && runner.stopped_at.as_deref() != seen
12+ && seen
1013 .and_then(stamp_to_unix)
1114 .is_some_and(|seen| now_unix.saturating_sub(seen) <= RUNNER_ONLINE_SECS)
1215 }
@@ -38,7 +41,8 @@ impl Store {
3841 };
3942 let online = fetch_opt(
4043 &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",
4246 (since,),
4347 |row| col_int(row, 0),
4448 )
crates/forge-core/src/store/migrate.rsmodified+4 -0
@@ -139,6 +139,10 @@ pub const MIGRATIONS: &[(u32, &str)] = &[
139139 76,
140140 include_str!("../../migrations/0076_milestone_title_repair.sql"),
141141 ),
142+ (
143+ 77,
144+ include_str!("../../migrations/0077_runner_stopped_at.sql"),
145+ ),
142146 ];
143147
144148 pub fn latest_schema_version() -> u32 {
crates/forge-runner/src/cli.rsmodified+31 -4
@@ -55,6 +55,10 @@ enum Command {
5555 #[arg(long)]
5656 config: Option<PathBuf>,
5757 },
58+ Unregister {
59+ #[arg(long)]
60+ config: Option<PathBuf>,
61+ },
5862 Check {
5963 #[arg(long)]
6064 work_dir: Option<PathBuf>,
@@ -189,6 +193,15 @@ async fn run(cli: Cli) -> Result<ExitCode, Box<dyn std::error::Error>> {
189193 );
190194 Ok(ExitCode::SUCCESS)
191195 }
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+ }
192205 Command::Run { config: path } => {
193206 let path = path.map_or_else(config::default_config_path, Ok)?;
194207 let mut cfg = config::load(&path)?;
@@ -236,6 +249,8 @@ async fn run(cli: Cli) -> Result<ExitCode, Box<dyn std::error::Error>> {
236249 (Arc::new(executor), map)
237250 }
238251 };
252+ let stop_url = cfg.url.clone();
253+ let stop_secret = cfg.runner_secret.clone();
239254 let mut runner =
240255 Runner::new(cfg, executor, RunOptions::default())?.with_pressure(pressure);
241256 if cache_cap > 0 {
@@ -248,13 +263,25 @@ async fn run(cli: Cli) -> Result<ExitCode, Box<dyn std::error::Error>> {
248263 }
249264 let stop = shutdown.clone();
250265 tokio::spawn(async move {
251- if tokio::signal::ctrl_c().await.is_ok() {
252- tracing::info!("interrupt received, cancelling running jobs");
253- stop.cancel();
266+ let Ok(mut term) =
267+ tokio::signal::unix::signal(tokio::signal::unix::SignalKind::terminate())
268+ else {
269+ return;
270+ };
271+ tokio::select! {
272+ _ = tokio::signal::ctrl_c() => {}
273+ _ = term.recv() => {}
254274 }
275+ tracing::info!("stop signal received, cancelling running jobs");
276+ stop.cancel();
255277 });
256278 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+ }
258285 RunEnd::Updated | RunEnd::Restart => Ok(ExitCode::from(update::RESTART_EXIT_CODE)),
259286 }
260287 }
crates/forge-runner/src/client.rsmodified+22 -0
@@ -159,6 +159,28 @@ impl ForgeClient {
159159 }
160160 }
161161
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+
162184 pub async fn get_config(
163185 &self,
164186 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) {
293293 };
294294 let mut offline = std::collections::BTreeSet::new();
295295 for runner in &runners {
296- let online = forge_core::store::health::runner_is_online(
297- runner.disabled,
298- runner.last_seen_at.as_deref(),
299- now,
300- );
296+ let online = forge_core::store::health::runner_is_online(runner, now);
301297 state.ci_live.note_runner_online(&runner.id, online);
302298 }
303299 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> {
476476 }
477477 }
478478
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+
479520 const INSTALL_SCRIPT: &str = include_str!("install.sh");
480521
481522 #[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() {
14181418 401
14191419 );
14201420 }
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() {
4040 id "$RUNNER_USER" >/dev/null 2>&1 || fail "there is no user $RUNNER_USER"
4141 home=$(getent passwd "$RUNNER_USER" | cut -d: -f6)
4242 [ -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
4349 loginctl disable-linger "$RUNNER_USER" || true
4450 loginctl terminate-user "$RUNNER_USER" 2>/dev/null || true
4551 pkill -KILL -u "$RUNNER_USER" || true
@@ -49,7 +55,11 @@ uninstall() {
4955 /home/?*) [ -d "$home" ] && rm -rf --one-file-system -- "$home" ;;
5056 esac
5157 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
5363 }
5464
5565 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
156156 if runner.disabled {
157157 return ("runner-dot is-disabled", g::t(lang, K::Disabled));
158158 }
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+ ) {
160166 ("runner-dot is-online", s(lang, "online", "çevrim içi"))
161167 } else {
162168 ("runner-dot is-offline", s(lang, "offline", "çevrim dışı"))
@@ -602,6 +608,9 @@ fn field_rows(runner: &CiRunner) -> Vec<FieldRow> {
602608 let reported = runner.reported_config.get(field.key);
603609 let overridden = if field.key == "concurrency" {
604610 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()))
605614 } else {
606615 runner.config_overrides.get(field.key).cloned()
607616 };
@@ -641,7 +650,7 @@ const TABS: [(&str, &[&str]); 8] = [
641650 ("overview", &[]),
642651 (
643652 "general",
644- &["concurrency", "labels", "executor", "auto_update"],
653+ &["name", "concurrency", "labels", "executor", "auto_update"],
645654 ),
646655 ("jobs", &[]),
647656 (
crates/forge-web/src/routes.snapmodified+2 -0
@@ -245,6 +245,8 @@ route /api/v1/ci/runners/install/forge Only([GET])
245245 route /api/v1/ci/runners/log Only([POST])
246246 route /api/v1/ci/runners/metrics Only([POST])
247247 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])
248250 route /api/v1/repos/{owner}/{repo} Only([GET])
249251 route /api/v1/repos/{owner}/{repo}/commits/{sha}/statuses Only([GET])
250252 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
496496 subordinate id range and lingering, downloads the forge's own binary (the token authorizes the
497497 download, and the script checks its sha256), runs `forge runner check`, registers, and starts the
498498 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
500-has no `runner.toml`. The steps below do the same by hand.
499+`ci`). `--uninstall` stops the runner, removes it from the forge with its own secret
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.
501502
502503 ### 1. Check the host
503504
@@ -515,10 +516,11 @@ The builtin executor needs:
515516 Run the check:
516517
517518 ```sh
518-forge runner check
519+systemd-run --user -P forge runner check
519520 ```
520521
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,
522524 with the reason, and exits non-zero when a check fails. Pass `--work-dir` to test the filesystem
523525 that your jobs will use.
524526
@@ -757,7 +759,8 @@ systemctl --user enable --now forge-runner.service
757759 journalctl --user -u forge-runner.service -f
758760 ```
759761
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
761764 whose runner disappears without reporting is failed as `runner lost` after about two minutes, with
762765 no heartbeat.
763766