forge
Explore
Log in

Don't you dare go Hollow

Restart a runner from the admin pages, after its jobs or now

Browse files at this commit

767f2d06c7c0c4ba7a09b3edd0495adcfa43bbf8Ahmet Kaan GümüşParent: c80f705
  • feat
    • restart a runner from the admin pages, after its jobs or now
Show full message
✨ feat: restart a runner from the admin pages, after its jobs or now

A runner that advertises the restart capability gets the request in the claim answer or heartbeat, stops claiming, drains or cancels its jobs and exits 75. The request clears when it reports a new boot id.
crates/forge-ci/src/proto.rsmodified+53 -0
@@ -64,6 +64,50 @@ pub struct ClaimRequest {
6464 /// The runner's build identity (`0.1.0 (cf8e648, 2026-10-20)`). Absent from an older runner.
6565 #[serde(default, skip_serializing_if = "Option::is_none")]
6666 pub build: Option<String>,
67+ /// Random per process start. The forge sees a restart when it changes.
68+ #[serde(default, skip_serializing_if = "Option::is_none")]
69+ pub boot_id: Option<String>,
70+ /// Features this runner has, such as [`CAP_RESTART`]. The crate version is the same for every
71+ /// build, so the forge gates features on this list. Absent from an older runner.
72+ #[serde(default, skip_serializing_if = "Vec::is_empty")]
73+ pub capabilities: Vec<String>,
74+}
75+
76+/// The capability of a runner that obeys [`RESTART_HEADER`].
77+pub const CAP_RESTART: &str = "restart";
78+
79+/// Response header on a claim: an admin asked this runner to restart. The value is `drain` (finish
80+/// the running jobs first) or `now` (cancel them). Absent means no request. The runner stops
81+/// claiming, restarts the way a self-update does (exit 75), and the forge clears
82+/// the request when it sees a new boot id.
83+pub const RESTART_HEADER: &str = "Forge-Runner-Restart";
84+
85+/// How a runner restarts when an admin asks.
86+#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
87+#[serde(rename_all = "lowercase")]
88+pub enum RestartMode {
89+ /// Stop claiming, let the running jobs finish, then restart.
90+ Drain,
91+ /// Cancel the running jobs, then restart.
92+ Now,
93+}
94+
95+impl RestartMode {
96+ pub fn as_str(self) -> &'static str {
97+ match self {
98+ Self::Drain => "drain",
99+ Self::Now => "now",
100+ }
101+ }
102+
103+ /// Parses a header value. Anything else counts as no request.
104+ pub fn parse(text: &str) -> Option<Self> {
105+ match text.trim() {
106+ "drain" => Some(Self::Drain),
107+ "now" => Some(Self::Now),
108+ _ => None,
109+ }
110+ }
67111 }
68112
69113 /// Request header on a heartbeat: the runner's build identity, same value as `ClaimRequest::build`.
@@ -158,6 +202,9 @@ pub struct HeartbeatResponse {
158202 /// A runner at its limit does not claim, so it learns about a change from its heartbeats.
159203 #[serde(default, skip_serializing_if = "Option::is_none")]
160204 pub concurrency: Option<u32>,
205+ /// A restart an admin asked for. Absent from a forge that does not know the feature.
206+ #[serde(default, skip_serializing_if = "Option::is_none")]
207+ pub restart: Option<RestartMode>,
161208 }
162209
163210 /// `POST /api/v1/ci/jobs/{id}/finish`.
@@ -197,6 +244,8 @@ mod tests {
197244 concurrency: Some(2),
198245 version: Some("1.0.0".into()),
199246 cpus: Some(8),
247+ boot_id: Some("abc".into()),
248+ capabilities: vec![CAP_RESTART.into()],
200249 memory_bytes: Some(1 << 33),
201250 build: Some("0.1.0 (cf8e648, 2026-10-20)".into()),
202251 };
@@ -207,6 +256,10 @@ mod tests {
207256 assert_eq!(beat.concurrency, None);
208257 let json = serde_json::to_string(&beat).unwrap();
209258 assert_eq!(json, r#"{"cancel":false}"#);
259+ assert_eq!(beat.restart, None);
260+ let beat: HeartbeatResponse =
261+ serde_json::from_str(r#"{"cancel":false,"restart":"drain"}"#).unwrap();
262+ assert_eq!(beat.restart, Some(RestartMode::Drain));
210263 }
211264
212265 #[test]
crates/forge-core/migrations/0057_runner_restart.sqladded+8 -0
@@ -0,0 +1,8 @@
1+-- An admin can ask a runner to restart itself. The request stays until the runner reports a boot
2+-- id different from the one it had when asked. Applied by store/migrate.rs.
3+
4+ALTER TABLE ci_runners ADD COLUMN reported_boot_id TEXT NULL;
5+-- Comma separated features the runner says it has, such as "restart".
6+ALTER TABLE ci_runners ADD COLUMN reported_capabilities TEXT NULL;
7+ALTER TABLE ci_runners ADD COLUMN restart_mode TEXT NULL;
8+ALTER TABLE ci_runners ADD COLUMN restart_requested_at TEXT NULL;
crates/forge-core/src/audit.rsmodified+8 -2
@@ -60,6 +60,7 @@ pub enum AuditAction {
6060 CiSecretDeleted,
6161 CiRunnerRegistered,
6262 CiRunnerDeleted,
63+ CiRunnerRestartRequested,
6364 CiRunnerConfigChanged,
6465 CiRegistrationTokenCreated,
6566 AdvisoryAlertDismissed,
@@ -79,6 +80,7 @@ pub enum AuditAction {
7980 MailSettingsUpdated,
8081 MailTestQueued,
8182 ServerSettingsUpdated,
83+ ServerRestarted,
8284 SnippetCreated,
8385 SnippetUpdated,
8486 SnippetDeleted,
@@ -164,6 +166,7 @@ impl AuditAction {
164166 AuditAction::CiSecretDeleted,
165167 AuditAction::CiRunnerRegistered,
166168 AuditAction::CiRunnerDeleted,
169+ AuditAction::CiRunnerRestartRequested,
167170 AuditAction::CiRunnerConfigChanged,
168171 AuditAction::CiRegistrationTokenCreated,
169172 AuditAction::AdvisoryAlertDismissed,
@@ -183,6 +186,7 @@ impl AuditAction {
183186 AuditAction::MailSettingsUpdated,
184187 AuditAction::MailTestQueued,
185188 AuditAction::ServerSettingsUpdated,
189+ AuditAction::ServerRestarted,
186190 AuditAction::SnippetCreated,
187191 AuditAction::SnippetUpdated,
188192 AuditAction::SnippetDeleted,
@@ -267,6 +271,7 @@ impl AuditAction {
267271 AuditAction::CiSecretDeleted => "ci_secret_deleted",
268272 AuditAction::CiRunnerRegistered => "ci_runner_registered",
269273 AuditAction::CiRunnerDeleted => "ci_runner_deleted",
274+ AuditAction::CiRunnerRestartRequested => "ci_runner_restart_requested",
270275 AuditAction::CiRunnerConfigChanged => "ci_runner_config_changed",
271276 AuditAction::CiRegistrationTokenCreated => "ci_registration_token_created",
272277 AuditAction::AdvisoryAlertDismissed => "advisory_alert_dismissed",
@@ -286,6 +291,7 @@ impl AuditAction {
286291 AuditAction::MailSettingsUpdated => "mail_settings_updated",
287292 AuditAction::MailTestQueued => "mail_test_queued",
288293 AuditAction::ServerSettingsUpdated => "server_settings_updated",
294+ AuditAction::ServerRestarted => "server_restarted",
289295 AuditAction::SnippetCreated => "snippet_created",
290296 AuditAction::SnippetUpdated => "snippet_updated",
291297 AuditAction::SnippetDeleted => "snippet_deleted",
@@ -411,13 +417,13 @@ mod tests {
411417 #[test]
412418 fn names_are_unique_and_round_trip() {
413419 let mut names: Vec<&str> = AuditAction::ALL.iter().map(|a| a.as_str()).collect();
414- assert_eq!(names.len(), 99);
420+ assert_eq!(names.len(), 101);
415421 for action in AuditAction::ALL {
416422 assert_eq!(AuditAction::parse(action.as_str()), Some(*action));
417423 }
418424 names.sort();
419425 names.dedup();
420- assert_eq!(names.len(), 99);
426+ assert_eq!(names.len(), 101);
421427 assert_eq!(AuditAction::parse("nope"), None);
422428 }
423429
crates/forge-core/src/ci.rsmodified+53 -0
@@ -136,10 +136,48 @@ pub struct CiRunner {
136136 pub running_jobs: u32,
137137 /// The runner's effective config as it last reported it, by field key. Secrets are redacted.
138138 pub reported_config: BTreeMap<String, serde_json::Value>,
139+ /// A restart an admin asked for that the runner has not yet carried out.
140+ pub restart: Option<RunnerRestart>,
139141 /// Admin-set values by field key. A key here beats the runner's own runner.toml.
140142 pub config_overrides: BTreeMap<String, serde_json::Value>,
141143 }
142144
145+/// How a runner restarts when an admin asks.
146+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
147+pub enum RestartMode {
148+ /// Stop claiming, let the running jobs finish, then restart.
149+ Drain,
150+ /// Cancel the running jobs and restart at once.
151+ Now,
152+}
153+
154+impl RestartMode {
155+ pub fn as_str(self) -> &'static str {
156+ match self {
157+ Self::Drain => "drain",
158+ Self::Now => "now",
159+ }
160+ }
161+}
162+
163+impl std::str::FromStr for RestartMode {
164+ type Err = ();
165+ fn from_str(s: &str) -> std::result::Result<Self, ()> {
166+ match s {
167+ "drain" => Ok(Self::Drain),
168+ "now" => Ok(Self::Now),
169+ _ => Err(()),
170+ }
171+ }
172+}
173+
174+/// A pending runner restart: asked for, not yet seen to happen.
175+#[derive(Debug, Clone, PartialEq, Eq)]
176+pub struct RunnerRestart {
177+ pub mode: RestartMode,
178+ pub requested_at: String,
179+}
180+
143181 /// How a runner config field can be changed from the web UI.
144182 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
145183 pub enum FieldKind {
@@ -342,6 +380,21 @@ pub struct RunnerReport {
342380 pub memory_bytes: Option<u64>,
343381 /// The runner's build identity, like `0.1.0 (cf8e648, 2026-10-20)`.
344382 pub build: Option<String>,
383+ /// Random per process start. A change means the runner restarted.
384+ pub boot_id: Option<String>,
385+ /// Features the runner says it has. The crate version never changes between builds, so the
386+ /// forge gates features on these and not on the version.
387+ pub capabilities: Vec<String>,
388+}
389+
390+/// The capability of a runner that restarts when the forge asks.
391+pub const CAP_RESTART: &str = "restart";
392+
393+impl CiRunner {
394+ /// True when the runner advertises that it honours a restart request.
395+ pub fn supports_restart(&self) -> bool {
396+ self.reported.capabilities.iter().any(|c| c == CAP_RESTART)
397+ }
345398 }
346399
347400 /// The smallest and largest concurrency an admin may set.
crates/forge-core/src/store/ci.rsmodified+174 -3
@@ -15,7 +15,8 @@ use super::{
1515 };
1616 use crate::ci::{
1717 CiArtifact, CiJob, CiRun, CiRunner, FieldKind, JobState, MAX_RUNNER_CONCURRENCY,
18- MIN_RUNNER_CONCURRENCY, NewJob, RunState, RunnerReport, validate_runner_field,
18+ MIN_RUNNER_CONCURRENCY, NewJob, RestartMode, RunState, RunnerReport, RunnerRestart,
19+ validate_runner_field,
1920 };
2021 use crate::error::{Error, Result};
2122 use crate::secret;
@@ -30,7 +31,7 @@ const RUNNER_COLS: &str = "id, name, labels, created_at, last_seen_at, disabled,
3031 concurrency_override, reported_concurrency, reported_version, reported_cpus, \
3132 reported_memory_bytes, reported_config, config_overrides, \
3233 (SELECT COUNT(*) FROM ci_jobs WHERE ci_jobs.runner_id = ci_runners.id AND ci_jobs.state = 'running'), \
33- reported_build";
34+ reported_build, reported_boot_id, restart_mode, restart_requested_at, reported_capabilities";
3435 const ARTIFACT_COLS: &str = "id, job_id, name, size, sha256, created_at";
3536
3637 /// Longest runner name, in bytes.
@@ -78,6 +79,22 @@ fn map_runner(row: &Row) -> Result<CiRunner> {
7879 cpus: opt_u32(row, 9)?,
7980 memory_bytes: opt_int(row, 10)?.and_then(|n| u64::try_from(n).ok()),
8081 build: col_opt_text(row, 14)?,
82+ boot_id: col_opt_text(row, 15)?,
83+ capabilities: col_opt_text(row, 18)?
84+ .map(|t| {
85+ t.split(',')
86+ .filter(|c| !c.is_empty())
87+ .map(str::to_owned)
88+ .collect()
89+ })
90+ .unwrap_or_default(),
91+ },
92+ restart: match (col_opt_text(row, 16)?, col_opt_text(row, 17)?) {
93+ (Some(mode), Some(requested_at)) => mode
94+ .parse::<RestartMode>()
95+ .ok()
96+ .map(|mode| RunnerRestart { mode, requested_at }),
97+ _ => None,
8198 },
8299 running_jobs: opt_u32(row, 13)?.unwrap_or(0),
83100 reported_config: json_map(row, 11)?,
@@ -728,13 +745,30 @@ impl Store {
728745 cpus: report.cpus.or(current.reported.cpus),
729746 memory_bytes: report.memory_bytes.or(current.reported.memory_bytes),
730747 build: report.build.clone().or(current.reported.build.clone()),
748+ boot_id: report.boot_id.clone().or(current.reported.boot_id.clone()),
749+ capabilities: if report.capabilities.is_empty() {
750+ current.reported.capabilities.clone()
751+ } else {
752+ report.capabilities.clone()
753+ },
731754 };
732755 if merged == current.reported {
733756 return Ok(false);
734757 }
758+ // A new boot id while a restart is pending means the runner came back.
759+ if merged.boot_id != current.reported.boot_id && current.restart.is_some() {
760+ conn.execute(
761+ "UPDATE ci_runners SET restart_mode = NULL, restart_requested_at = NULL \
762+ WHERE id = ?1",
763+ (id.to_string(),),
764+ )
765+ .await
766+ .map_err(db_err)?;
767+ }
735768 conn.execute(
736769 "UPDATE ci_runners SET reported_concurrency = ?2, reported_version = ?3, \
737- reported_cpus = ?4, reported_memory_bytes = ?5, reported_build = ?6 WHERE id = ?1",
770+ reported_cpus = ?4, reported_memory_bytes = ?5, reported_build = ?6, \
771+ reported_boot_id = ?7, reported_capabilities = ?8 WHERE id = ?1",
738772 (
739773 id.to_string(),
740774 opt_int_value(merged.concurrency.map(i64::from)),
@@ -742,6 +776,8 @@ impl Store {
742776 opt_int_value(merged.cpus.map(i64::from)),
743777 opt_int_value(merged.memory_bytes.and_then(|n| i64::try_from(n).ok())),
744778 opt_text(merged.build.as_deref()),
779+ opt_text(merged.boot_id.as_deref()),
780+ merged.capabilities.join(","),
745781 ),
746782 )
747783 .await
@@ -749,6 +785,39 @@ impl Store {
749785 Ok(true)
750786 }
751787
788+ /// Asks a runner to restart itself. A second request replaces the first, so "drain" can be
789+ /// upgraded to "now". `Invalid` when the runner never reported a boot id (too old to obey),
790+ /// `NotFound` when it is gone.
791+ pub async fn request_runner_restart(&self, id: &str, mode: RestartMode) -> Result<()> {
792+ let conn = self.inner.conn.lock().await;
793+ let runner = load_runner(&conn, id).await?.ok_or(Error::NotFound)?;
794+ if !runner.supports_restart() {
795+ return Err(Error::Invalid(
796+ "this runner is too old to restart from the forge".into(),
797+ ));
798+ }
799+ conn.execute(
800+ "UPDATE ci_runners SET restart_mode = ?2, restart_requested_at = ?3 WHERE id = ?1",
801+ (id.to_string(), mode.as_str().to_string(), now_stamp()),
802+ )
803+ .await
804+ .map_err(db_err)?;
805+ Ok(())
806+ }
807+
808+ /// The restart pending for a runner, read fresh. `None` when none or the runner is gone.
809+ pub async fn runner_restart(&self, id: &str) -> Result<Option<RestartMode>> {
810+ let conn = self.read_conn().await;
811+ let found = fetch_opt(
812+ &conn,
813+ "SELECT restart_mode FROM ci_runners WHERE id = ?1",
814+ (id.to_string(),),
815+ |row| col_opt_text(row, 0),
816+ )
817+ .await?;
818+ Ok(found.flatten().and_then(|m| m.parse().ok()))
819+ }
820+
752821 /// Removes a runner. `NotFound` if it does not exist.
753822 pub async fn delete_runner(&self, id: &str) -> Result<()> {
754823 let conn = self.inner.conn.lock().await;
@@ -1700,6 +1769,7 @@ mod tests {
17001769 reported: RunnerReport::default(),
17011770 running_jobs: 0,
17021771 reported_config: BTreeMap::new(),
1772+ restart: None,
17031773 config_overrides: BTreeMap::new(),
17041774 }
17051775 }
@@ -1896,6 +1966,105 @@ mod tests {
18961966 ));
18971967 }
18981968
1969+ fn boot_report(boot: &str, caps: &[&str]) -> RunnerReport {
1970+ RunnerReport {
1971+ boot_id: Some(boot.into()),
1972+ capabilities: caps.iter().map(|c| c.to_string()).collect(),
1973+ ..RunnerReport::default()
1974+ }
1975+ }
1976+
1977+ #[tokio::test]
1978+ async fn restart_is_refused_for_a_runner_without_the_capability() {
1979+ let fx = fixture().await;
1980+ let (runner, _) = runner_with(&fx.store, &fx.tahinli.id, &["linux"]).await;
1981+ assert!(!runner.supports_restart());
1982+ assert!(matches!(
1983+ fx.store
1984+ .request_runner_restart(&runner.id, RestartMode::Drain)
1985+ .await,
1986+ Err(Error::Invalid(_))
1987+ ));
1988+ // A boot id alone is not enough, the version is the same for every build.
1989+ fx.store
1990+ .record_runner_report(&runner.id, &boot_report("b1", &[]))
1991+ .await
1992+ .unwrap();
1993+ assert!(matches!(
1994+ fx.store
1995+ .request_runner_restart(&runner.id, RestartMode::Now)
1996+ .await,
1997+ Err(Error::Invalid(_))
1998+ ));
1999+ assert!(matches!(
2000+ fx.store
2001+ .request_runner_restart("missing", RestartMode::Now)
2002+ .await,
2003+ Err(Error::NotFound)
2004+ ));
2005+ assert_eq!(fx.store.runner_restart(&runner.id).await.unwrap(), None);
2006+ }
2007+
2008+ #[tokio::test]
2009+ async fn restart_request_stays_until_a_new_boot_id_and_can_be_upgraded() {
2010+ let fx = fixture().await;
2011+ let (runner, _) = runner_with(&fx.store, &fx.tahinli.id, &["linux"]).await;
2012+ fx.store
2013+ .record_runner_report(&runner.id, &boot_report("b1", &["restart"]))
2014+ .await
2015+ .unwrap();
2016+ fx.store
2017+ .request_runner_restart(&runner.id, RestartMode::Drain)
2018+ .await
2019+ .unwrap();
2020+ assert_eq!(
2021+ fx.store.runner_restart(&runner.id).await.unwrap(),
2022+ Some(RestartMode::Drain)
2023+ );
2024+ let listed = fx.store.list_runners().await.unwrap().remove(0);
2025+ assert_eq!(listed.restart.as_ref().unwrap().mode, RestartMode::Drain);
2026+ assert!(listed.supports_restart());
2027+
2028+ // The same process reporting again changes nothing.
2029+ fx.store
2030+ .record_runner_report(&runner.id, &boot_report("b1", &["restart"]))
2031+ .await
2032+ .unwrap();
2033+ assert!(fx.store.runner_restart(&runner.id).await.unwrap().is_some());
2034+ // A heartbeat without a boot id changes nothing either.
2035+ let beat = RunnerReport {
2036+ concurrency: Some(2),
2037+ ..RunnerReport::default()
2038+ };
2039+ fx.store
2040+ .record_runner_report(&runner.id, &beat)
2041+ .await
2042+ .unwrap();
2043+ assert!(fx.store.runner_restart(&runner.id).await.unwrap().is_some());
2044+
2045+ // "Restart now" replaces the pending drain.
2046+ fx.store
2047+ .request_runner_restart(&runner.id, RestartMode::Now)
2048+ .await
2049+ .unwrap();
2050+ assert_eq!(
2051+ fx.store.runner_restart(&runner.id).await.unwrap(),
2052+ Some(RestartMode::Now)
2053+ );
2054+
2055+ // The runner comes back with a new boot id: the request is cleared, capability kept.
2056+ assert!(
2057+ fx.store
2058+ .record_runner_report(&runner.id, &boot_report("b2", &["restart"]))
2059+ .await
2060+ .unwrap()
2061+ );
2062+ assert_eq!(fx.store.runner_restart(&runner.id).await.unwrap(), None);
2063+ let listed = fx.store.list_runners().await.unwrap().remove(0);
2064+ assert!(listed.restart.is_none());
2065+ assert!(listed.supports_restart());
2066+ }
2067+
18992068 #[tokio::test]
19002069 async fn runner_report_round_trip_and_running_count() {
19012070 let fx = fixture().await;
@@ -1908,6 +2077,8 @@ mod tests {
19082077 cpus: Some(8),
19092078 memory_bytes: Some(16 << 30),
19102079 build: Some("0.1.0 (cf8e648, 2026-10-20)".into()),
2080+ boot_id: Some("boot-1".into()),
2081+ capabilities: vec!["restart".into()],
19112082 };
19122083 assert!(
19132084 fx.store
crates/forge-core/src/store/migrate.rsmodified+1 -0
@@ -96,6 +96,7 @@ pub const MIGRATIONS: &[(u32, &str)] = &[
9696 include_str!("../../migrations/0055_user_suspensions.sql"),
9797 ),
9898 (56, include_str!("../../migrations/0056_runner_build.sql")),
99+ (57, include_str!("../../migrations/0057_runner_restart.sql")),
99100 ];
100101
101102 /// The highest migration version this binary knows about.
crates/forge-runner/src/cli.rsmodified+2 -0
@@ -278,6 +278,8 @@ async fn run(cli: Cli) -> Result<ExitCode, Box<dyn std::error::Error>> {
278278 RunEnd::Stopped => Ok(ExitCode::SUCCESS),
279279 // systemd restarts the runner on this code, and it starts the new binary.
280280 RunEnd::Updated => Ok(ExitCode::from(update::RESTART_EXIT_CODE)),
281+ // An admin asked for a restart. The same exit code, the same systemd restart.
282+ RunEnd::Restart => Ok(ExitCode::from(update::RESTART_EXIT_CODE)),
281283 }
282284 }
283285 Command::Check {
crates/forge-runner/src/client.rsmodified+27 -2
@@ -7,8 +7,9 @@ use std::path::Path;
77 use std::time::Duration;
88
99 use forge_ci::proto::{
10- BUILD_HEADER, CONCURRENCY_HEADER, ClaimRequest, FinishRequest, HeartbeatResponse,
11- JobAssignment, RegisterRequest, RegisterResponse, RunnerConfigOverrides, RunnerConfigReport,
10+ BUILD_HEADER, CAP_RESTART, CONCURRENCY_HEADER, ClaimRequest, FinishRequest, HeartbeatResponse,
11+ JobAssignment, RESTART_HEADER, RegisterRequest, RegisterResponse, RestartMode,
12+ RunnerConfigOverrides, RunnerConfigReport,
1213 };
1314 use reqwest::StatusCode;
1415 use reqwest::header::{CONTENT_LENGTH, HeaderMap};
@@ -63,6 +64,8 @@ pub struct ClaimReply {
6364 pub binary_sha256: Option<String>,
6465 /// The concurrency an admin set in the web UI. `None` means no override.
6566 pub concurrency: Option<u32>,
67+ /// A restart an admin asked for, from the `Forge-Runner-Restart` header.
68+ pub restart: Option<RestartMode>,
6669 }
6770
6871 /// A client for one forge base URL.
@@ -126,6 +129,8 @@ impl ForgeClient {
126129 cpus: host.cpus,
127130 memory_bytes: host.memory_bytes,
128131 build: Some(forge_ci::build::display()),
132+ boot_id: Some(crate::restart::boot_id().to_owned()),
133+ capabilities: vec![CAP_RESTART.to_owned()],
129134 };
130135 let target = format!("{}-{}", std::env::consts::ARCH, std::env::consts::OS);
131136 let resp = self
@@ -139,16 +144,19 @@ impl ForgeClient {
139144 .await?;
140145 let binary_sha256 = advertised_sha256(resp.headers());
141146 let concurrency = advertised_concurrency(resp.headers());
147+ let restart = advertised_restart(resp.headers());
142148 match resp.status() {
143149 StatusCode::NO_CONTENT => Ok(ClaimReply {
144150 job: None,
145151 binary_sha256,
146152 concurrency,
153+ restart,
147154 }),
148155 status if status.is_success() => Ok(ClaimReply {
149156 job: Some(resp.json().await?),
150157 binary_sha256,
151158 concurrency,
159+ restart,
152160 }),
153161 _ => Err(status_error(resp).await),
154162 }
@@ -348,6 +356,11 @@ fn advertised_concurrency(headers: &HeaderMap) -> Option<u32> {
348356 .ok()
349357 }
350358
359+/// The `Forge-Runner-Restart` header, when it holds a mode this runner knows.
360+fn advertised_restart(headers: &HeaderMap) -> Option<RestartMode> {
361+ RestartMode::parse(headers.get(RESTART_HEADER)?.to_str().ok()?)
362+}
363+
351364 /// Cheap facts about the host that help an admin size the runner's concurrency.
352365 struct HostFacts {
353366 cpus: Option<u32>,
@@ -402,6 +415,18 @@ mod tests {
402415 assert_eq!(parse_mem_total("nothing"), None);
403416 }
404417
418+ #[test]
419+ fn restart_header_must_name_a_mode() {
420+ let mut headers = HeaderMap::new();
421+ assert_eq!(advertised_restart(&headers), None);
422+ headers.insert(RESTART_HEADER, "drain".parse().unwrap());
423+ assert_eq!(advertised_restart(&headers), Some(RestartMode::Drain));
424+ headers.insert(RESTART_HEADER, "now".parse().unwrap());
425+ assert_eq!(advertised_restart(&headers), Some(RestartMode::Now));
426+ headers.insert(RESTART_HEADER, "later".parse().unwrap());
427+ assert_eq!(advertised_restart(&headers), None);
428+ }
429+
405430 #[test]
406431 fn concurrency_header_must_be_a_number() {
407432 let mut headers = HeaderMap::new();
crates/forge-runner/src/lib.rsmodified+1 -0
@@ -14,6 +14,7 @@ pub mod executor;
1414 pub mod limiter;
1515 pub mod logs;
1616 pub mod oci;
17+pub mod restart;
1718 pub mod runner;
1819 pub mod sandbox;
1920 pub mod update;
crates/forge-runner/src/restart.rsadded+139 -0
@@ -0,0 +1,139 @@
1+//! Restart on request. An admin can ask a runner to restart from the forge's web UI. The request
2+//! arrives in a claim answer or a heartbeat answer. The runner then stops claiming, waits for or
3+//! cancels its jobs, and ends its loop with [`crate::runner::RunEnd::Restart`]. The caller exits
4+//! with [`crate::update::RESTART_EXIT_CODE`], the same way a self-update ends, so the supervisor
5+//! (systemd `Restart=on-failure`) starts the binary again. Nothing here polls.
6+
7+use std::sync::OnceLock;
8+use std::sync::atomic::{AtomicBool, Ordering};
9+use std::sync::{Mutex, PoisonError};
10+
11+use forge_ci::proto::RestartMode;
12+use tokio::sync::Notify;
13+
14+/// A restart request seen from the forge, shared by the claim loop and the job heartbeats.
15+#[derive(Default)]
16+pub struct RestartState {
17+ mode: Mutex<Option<RestartMode>>,
18+ wake: Notify,
19+ /// Set once the running jobs were cancelled for a `now` restart.
20+ cancelled: AtomicBool,
21+}
22+
23+impl RestartState {
24+ /// Records what the forge said. `None` changes nothing, because a request cannot be taken
25+ /// back from the runner's side. `drain` never replaces `now`. Wakes the loop on a change.
26+ pub fn observe(&self, said: Option<RestartMode>) {
27+ let Some(said) = said else { return };
28+ let mut mode = self.mode.lock().unwrap_or_else(PoisonError::into_inner);
29+ let next = match (*mode, said) {
30+ (Some(RestartMode::Now), _) => RestartMode::Now,
31+ (_, said) => said,
32+ };
33+ if *mode != Some(next) {
34+ *mode = Some(next);
35+ self.wake.notify_one();
36+ }
37+ }
38+
39+ pub fn pending(&self) -> Option<RestartMode> {
40+ *self.mode.lock().unwrap_or_else(PoisonError::into_inner)
41+ }
42+
43+ /// Resolves after the pending request changed.
44+ pub async fn changed(&self) {
45+ self.wake.notified().await;
46+ }
47+
48+ pub fn mark_cancelled(&self) {
49+ self.cancelled.store(true, Ordering::SeqCst);
50+ }
51+
52+ /// Whether running jobs were cancelled for a `now` restart.
53+ pub fn jobs_cancelled(&self) -> bool {
54+ self.cancelled.load(Ordering::SeqCst)
55+ }
56+}
57+
58+/// What the claim loop does next about a restart request.
59+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
60+pub enum Step {
61+ /// No request: claim as usual.
62+ Proceed,
63+ /// Cancel the running jobs, then wait for them.
64+ CancelJobs,
65+ /// Claim nothing and wait for a running job to end.
66+ WaitForJobs,
67+ /// Nothing is running: leave the loop so the process restarts.
68+ Restart,
69+}
70+
71+/// The drain-then-restart decision. `cancelled` says whether the jobs were already cancelled.
72+pub fn decide(pending: Option<RestartMode>, running: usize, cancelled: bool) -> Step {
73+ match pending {
74+ None => Step::Proceed,
75+ Some(_) if running == 0 => Step::Restart,
76+ Some(RestartMode::Now) if !cancelled => Step::CancelJobs,
77+ Some(_) => Step::WaitForJobs,
78+ }
79+}
80+
81+/// An id that is new for every process start. The forge sees a restart when it changes.
82+pub fn boot_id() -> &'static str {
83+ static ID: OnceLock<String> = OnceLock::new();
84+ ID.get_or_init(|| {
85+ let nanos = std::time::SystemTime::now()
86+ .duration_since(std::time::UNIX_EPOCH)
87+ .map_or(0, |d| d.as_nanos());
88+ format!("{:x}-{nanos:x}", std::process::id())
89+ })
90+}
91+
92+#[cfg(test)]
93+mod tests {
94+ use super::*;
95+
96+ #[test]
97+ fn no_request_means_claim_as_usual() {
98+ assert_eq!(decide(None, 3, false), Step::Proceed);
99+ }
100+
101+ #[test]
102+ fn drain_waits_for_running_jobs_then_restarts() {
103+ let drain = Some(RestartMode::Drain);
104+ assert_eq!(decide(drain, 2, false), Step::WaitForJobs);
105+ assert_eq!(decide(drain, 1, false), Step::WaitForJobs);
106+ assert_eq!(decide(drain, 0, false), Step::Restart);
107+ }
108+
109+ #[test]
110+ fn now_cancels_once_then_waits_then_restarts() {
111+ let now = Some(RestartMode::Now);
112+ assert_eq!(decide(now, 2, false), Step::CancelJobs);
113+ assert_eq!(decide(now, 2, true), Step::WaitForJobs);
114+ assert_eq!(decide(now, 0, true), Step::Restart);
115+ assert_eq!(decide(now, 0, false), Step::Restart);
116+ }
117+
118+ #[test]
119+ fn a_request_is_latched_and_now_beats_drain() {
120+ let state = RestartState::default();
121+ assert_eq!(state.pending(), None);
122+ state.observe(None);
123+ assert_eq!(state.pending(), None);
124+ state.observe(Some(RestartMode::Drain));
125+ assert_eq!(state.pending(), Some(RestartMode::Drain));
126+ state.observe(None);
127+ assert_eq!(state.pending(), Some(RestartMode::Drain));
128+ state.observe(Some(RestartMode::Now));
129+ assert_eq!(state.pending(), Some(RestartMode::Now));
130+ state.observe(Some(RestartMode::Drain));
131+ assert_eq!(state.pending(), Some(RestartMode::Now));
132+ }
133+
134+ #[test]
135+ fn the_boot_id_is_stable_within_a_process() {
136+ assert_eq!(boot_id(), boot_id());
137+ assert!(!boot_id().is_empty());
138+ }
139+}
crates/forge-runner/src/runner.rsmodified+51 -2
@@ -18,6 +18,7 @@ use crate::config::RunnerConfig;
1818 use crate::executor::{ExecRequest, ExecResult, Executor};
1919 use crate::limiter::Limiter;
2020 use crate::logs::{self, PumpConfig};
21+use crate::restart::{self, RestartState, Step};
2122 use crate::update::{self, Installed, UpdateState};
2223 use crate::workspace;
2324
@@ -56,6 +57,9 @@ pub enum RunEnd {
5657 Stopped,
5758 /// The binary was replaced. The caller exits with [`update::RESTART_EXIT_CODE`].
5859 Updated,
60+ /// An admin asked for a restart and the jobs are done. The caller exits with
61+ /// [`update::RESTART_EXIT_CODE`], like for an update.
62+ Restart,
5963 }
6064
6165 /// A runner bound to one forge and one executor.
@@ -69,6 +73,8 @@ pub struct Runner {
6973 cache: Option<Arc<CacheStore>>,
7074 /// The live job limit. Starts at `runner.toml` and follows the forge's override.
7175 limiter: Arc<Limiter>,
76+ /// A restart an admin asked for, see [`restart`].
77+ restart: Arc<RestartState>,
7278 }
7379
7480 impl Runner {
@@ -86,6 +92,7 @@ impl Runner {
8692 options,
8793 cache: None,
8894 limiter,
95+ restart: Arc::new(RestartState::default()),
8996 })
9097 }
9198
@@ -129,7 +136,38 @@ impl Runner {
129136 auto_update = updates.enabled(),
130137 "runner started"
131138 );
139+ // Parent of every job's token, so a `now` restart can cancel them all at once.
140+ let jobs_cancel = shutdown.child_token();
132141 let end = loop {
142+ match restart::decide(
143+ self.restart.pending(),
144+ jobs.len(),
145+ self.restart.jobs_cancelled(),
146+ ) {
147+ Step::Proceed => {}
148+ Step::Restart => {
149+ tracing::info!("restart requested by the forge, restarting");
150+ break RunEnd::Restart;
151+ }
152+ Step::CancelJobs => {
153+ tracing::info!("restart now requested, cancelling running jobs");
154+ self.restart.mark_cancelled();
155+ jobs_cancel.cancel();
156+ continue;
157+ }
158+ Step::WaitForJobs => {
159+ tokio::select! {
160+ _ = shutdown.cancelled() => break RunEnd::Stopped,
161+ Some(joined) = jobs.join_next() => {
162+ if let Err(e) = joined {
163+ tracing::error!(error = %e, "job task panicked");
164+ }
165+ }
166+ () = self.restart.changed() => {}
167+ }
168+ continue;
169+ }
170+ }
133171 if let Some((exe_path, _)) = &exe
134172 && let Some(sha) = updates.pending().map(str::to_owned)
135173 {
@@ -166,6 +204,7 @@ impl Runner {
166204
167205 let permit = tokio::select! {
168206 _ = shutdown.cancelled() => break RunEnd::Stopped,
207+ () = self.restart.changed() => continue,
169208 permit = self.limiter.acquire() => match permit {
170209 Ok(permit) => permit,
171210 Err(_) => break RunEnd::Stopped,
@@ -186,6 +225,7 @@ impl Runner {
186225 Ok(reply) => {
187226 // No header means no override: back to the runner.toml value.
188227 self.limiter.apply_logged(reply.concurrency);
228+ self.restart.observe(reply.restart);
189229 if updates.observe(reply.binary_sha256.as_deref())
190230 && let Some(sha) = updates.pending()
191231 {
@@ -200,7 +240,7 @@ impl Runner {
200240 "claimed job"
201241 );
202242 let runner = self.clone();
203- let cancel = shutdown.child_token();
243+ let cancel = jobs_cancel.child_token();
204244 jobs.spawn(async move {
205245 let _permit = permit;
206246 runner.process(job, cancel).await;
@@ -334,6 +374,10 @@ impl Runner {
334374 };
335375 }
336376
377+ if self.restart.jobs_cancelled() && result.outcome == Outcome::Cancelled {
378+ result.message = Some("cancelled because an admin restarted the runner".to_owned());
379+ }
380+
337381 // The save decides on the final outcome. It also clears the job's scratch dirs.
338382 if let (Some(cache), Some(dir)) = (&self.cache, workspace_dir.as_deref()) {
339383 for line in cache.save(&job, result.outcome, dir).await {
@@ -364,6 +408,7 @@ impl Runner {
364408 fn spawn_heartbeat(&self, job: &JobAssignment, cancel: CancellationToken) -> JoinHandle<()> {
365409 let client = self.client.clone();
366410 let limiter = self.limiter.clone();
411+ let restart = self.restart.clone();
367412 let job_id = job.job_id.clone();
368413 let token = job.job_token.clone();
369414 let every = self.options.heartbeat_every;
@@ -377,12 +422,16 @@ impl Runner {
377422 {
378423 Ok(beat) if beat.cancel => {
379424 limiter.apply_logged(beat.concurrency);
425+ restart.observe(beat.restart);
380426 tracing::info!(job_id = %job_id, "forge requested cancel");
381427 cancel.cancel();
382428 return;
383429 }
384430 // A runner at its limit does not claim, so the heartbeat carries changes too.
385- Ok(beat) => limiter.apply_logged(beat.concurrency),
431+ Ok(beat) => {
432+ limiter.apply_logged(beat.concurrency);
433+ restart.observe(beat.restart);
434+ }
386435 Err(e) => tracing::warn!(job_id = %job_id, error = %e, "heartbeat failed"),
387436 }
388437 }
crates/forge-runner/tests/flow.rsmodified+1 -0
@@ -130,6 +130,7 @@ fn route(
130130 Reply::json(&forge_ci::proto::HeartbeatResponse {
131131 cancel,
132132 concurrency: None,
133+ restart: None,
133134 })
134135 }
135136 ("PUT", ["artifacts", name]) => {
crates/forge-web/src/ci/api.rsmodified+36 -2
@@ -10,8 +10,8 @@ use forge_ci::config::JobSpec;
1010 use forge_ci::mask::Masker;
1111 use forge_ci::proto::{
1212 BUILD_HEADER, CONCURRENCY_HEADER, ClaimRequest, FinishRequest, HeartbeatResponse,
13- JobAssignment, Outcome, RegisterRequest, RegisterResponse, RunnerConfigOverrides,
14- RunnerConfigReport,
13+ JobAssignment, Outcome, RESTART_HEADER, RegisterRequest, RegisterResponse,
14+ RestartMode as WireRestart, RunnerConfigOverrides, RunnerConfigReport,
1515 };
1616 use forge_core::Error as CoreError;
1717 use forge_core::ci::{CiJob, CiRun, CiRunner, JobState, RunState, RunnerReport};
@@ -194,12 +194,20 @@ async fn claim(cx: &Cx, body: Body) -> topcoat::Result<Response> {
194194 cpus: request.cpus,
195195 memory_bytes: request.memory_bytes,
196196 build: request.build.filter(|v| v.len() <= 64),
197+ boot_id: request.boot_id.filter(|v| v.len() <= 64),
198+ capabilities: request
199+ .capabilities
200+ .into_iter()
201+ .filter(|c| !c.is_empty() && c.len() <= 32 && !c.contains(','))
202+ .take(16)
203+ .collect(),
197204 },
198205 )
199206 .await;
200207 let mut res = claim_work(state, &runner).await?;
201208 // The override can change during the long poll, so it is read at answer time.
202209 set_concurrency_header(state, &runner.id, &mut res).await;
210+ set_restart_header(state, &runner.id, &mut res).await;
203211 // Advertises the binary sha256 when self-update is on and the runner asked for this target.
204212 self_update::advertise(state, headers(cx), &mut res);
205213 Ok(res)
@@ -226,6 +234,24 @@ async fn set_concurrency_header(state: &AppState, runner_id: &str, res: &mut Res
226234 }
227235 }
228236
237+/// The restart an admin asked for, in the wire type. `None` when nothing is pending.
238+async fn pending_restart(state: &AppState, runner_id: &str) -> Option<WireRestart> {
239+ let mode = state.store.runner_restart(runner_id).await.ok().flatten()?;
240+ WireRestart::parse(mode.as_str())
241+}
242+
243+/// Adds the pending restart request to a claim answer. Sent on every answer until the runner
244+/// comes back with a new boot id. An older runner ignores the header.
245+async fn set_restart_header(state: &AppState, runner_id: &str, res: &mut Response) {
246+ if !matches!(res.status(), StatusCode::OK | StatusCode::NO_CONTENT) {
247+ return;
248+ }
249+ if let Some(mode) = pending_restart(state, runner_id).await {
250+ res.headers_mut()
251+ .insert(RESTART_HEADER, HeaderValue::from_static(mode.as_str()));
252+ }
253+}
254+
229255 /// `GET` and `PUT /api/v1/ci/runners/config`. The runner reads the admin's overrides when it
230256 /// starts, applies them to its in-memory config, then reports its effective config here.
231257 #[route(GET "/api/v1/ci/runners/config")]
@@ -285,6 +311,11 @@ async fn claim_work(state: &AppState, runner: &CiRunner) -> topcoat::Result<Resp
285311 let mut woken = std::pin::pin!(waker.notified());
286312 woken.as_mut().enable();
287313
314+ // A runner that is to restart gets no new job. It is answered at once, so it sees the
315+ // request without waiting out the long poll.
316+ if matches!(state.store.runner_restart(&runner.id).await, Ok(Some(_))) {
317+ return Ok(empty(StatusCode::NO_CONTENT));
318+ }
288319 match try_claim(state, runner).await {
289320 Ok(Some(assignment)) => return Ok(assignment_response(&assignment)),
290321 Ok(None) => {}
@@ -507,6 +538,7 @@ async fn heartbeat(cx: &Cx) -> topcoat::Result<Response> {
507538 // The runner says its live concurrency, and the answer carries the admin's override.
508539 // A runner at its limit does not claim, so this is how it learns about a change.
509540 let mut concurrency = None;
541+ let mut restart = None;
510542 if let Some(runner_id) = job.runner_id.as_deref() {
511543 let said = headers(cx)
512544 .get(CONCURRENCY_HEADER)
@@ -532,12 +564,14 @@ async fn heartbeat(cx: &Cx) -> topcoat::Result<Response> {
532564 .await
533565 .ok()
534566 .flatten();
567+ restart = pending_restart(state, runner_id).await;
535568 }
536569 Ok(api::json(
537570 StatusCode::OK,
538571 &serde_json::to_value(HeartbeatResponse {
539572 cancel,
540573 concurrency,
574+ restart,
541575 })
542576 .unwrap_or_default(),
543577 ))
crates/forge-web/src/ci/api_tests.rsmodified+74 -0
@@ -528,6 +528,80 @@ async fn claim_and_heartbeat_carry_the_concurrency_round_trip() {
528528 assert!(beat.json().get("concurrency").is_none());
529529 }
530530
531+async fn post_claim(router: &Router, secret: &str, boot: &str) -> Sent {
532+ let body = serde_json::json!({ "labels": [], "boot_id": boot, "capabilities": ["restart"] });
533+ send(
534+ router,
535+ "POST",
536+ "/api/v1/ci/runners/claim",
537+ &[bearer(secret)],
538+ json_body(&body),
539+ )
540+ .await
541+}
542+
543+#[tokio::test]
544+async fn a_restart_request_is_delivered_until_the_runner_comes_back_with_a_new_boot_id() {
545+ use forge_core::ci::RestartMode;
546+
547+ let env = bare(|_| {}).await;
548+ let (runner, secret) = runner(&env, &[]).await;
549+ make_run(&env, "push", None, COMMIT, &[job("a", spec(&[], &[]))]).await;
550+ // A runner without the capability cannot be asked.
551+ assert!(
552+ env.store
553+ .request_runner_restart(&runner.id, RestartMode::Drain)
554+ .await
555+ .is_err()
556+ );
557+
558+ // The first claim reports the capability and takes the job. No restart header yet.
559+ let sent = post_claim(&env.router, &secret, "boot-1").await;
560+ assert_eq!(sent.status, 200);
561+ assert!(sent.headers.get("Forge-Runner-Restart").is_none());
562+ let assignment = sent.json();
563+ let uri = format!(
564+ "/api/v1/ci/jobs/{}/heartbeat",
565+ assignment["job_id"].as_str().unwrap()
566+ );
567+ let token = assignment["job_token"].as_str().unwrap();
568+
569+ env.store
570+ .request_runner_restart(&runner.id, RestartMode::Drain)
571+ .await
572+ .unwrap();
573+ make_run(&env, "push", None, COMMIT, &[job("b", spec(&[], &[]))]).await;
574+
575+ // Delivered on the heartbeat, and the claim answers at once with no new job.
576+ let beat = send(&env.router, "POST", &uri, &[bearer(token)], Vec::new()).await;
577+ assert_eq!(beat.json()["restart"], "drain");
578+ let sent = post_claim(&env.router, &secret, "boot-1").await;
579+ assert_eq!(
580+ sent.status, 204,
581+ "a runner that is to restart gets no new job"
582+ );
583+ assert_eq!(sent.headers.get("Forge-Runner-Restart").unwrap(), "drain");
584+ // Still delivered while the same process keeps asking.
585+ let sent = post_claim(&env.router, &secret, "boot-1").await;
586+ assert_eq!(sent.headers.get("Forge-Runner-Restart").unwrap(), "drain");
587+
588+ // "Now" replaces "drain".
589+ env.store
590+ .request_runner_restart(&runner.id, RestartMode::Now)
591+ .await
592+ .unwrap();
593+ let beat = send(&env.router, "POST", &uri, &[bearer(token)], Vec::new()).await;
594+ assert_eq!(beat.json()["restart"], "now");
595+
596+ // A new boot id clears it: no header, no field, and jobs flow again.
597+ let sent = post_claim(&env.router, &secret, "boot-2").await;
598+ assert_eq!(sent.status, 200);
599+ assert!(sent.headers.get("Forge-Runner-Restart").is_none());
600+ assert_eq!(env.store.runner_restart(&runner.id).await.unwrap(), None);
601+ let beat = send(&env.router, "POST", &uri, &[bearer(token)], Vec::new()).await;
602+ assert!(beat.json().get("restart").is_none());
603+}
604+
531605 #[tokio::test]
532606 async fn runner_config_report_and_overrides_round_trip() {
533607 let env = bare(|_| {}).await;
crates/forge-web/src/pages/admin_runners.rsmodified+237 -2
@@ -8,7 +8,7 @@
88
99 use forge_ci::build::{self, Freshness};
1010 use forge_core::AuditAction;
11-use forge_core::ci::{CiRunner, FieldKind, RUNNER_FIELDS, runner_field};
11+use forge_core::ci::{CiRunner, FieldKind, RUNNER_FIELDS, RestartMode, runner_field};
1212 use serde::Deserialize;
1313 use time::OffsetDateTime;
1414 use time::format_description::well_known::Rfc3339;
@@ -42,7 +42,7 @@ fn s(lang: Lang, en: &'static str, tr: &'static str) -> &'static str {
4242 }
4343
4444 /// Extra notice words: (word, English, Turkish, is an error).
45-const EXTRA_NOTICES: [(&str, &str, &str, bool); 6] = [
45+const EXTRA_NOTICES: [(&str, &str, &str, bool); 8] = [
4646 (
4747 "saved",
4848 "Saved. The runner picks it up on its next check-in.",
@@ -67,6 +67,18 @@ const EXTRA_NOTICES: [(&str, &str, &str, bool); 6] = [
6767 "Hiçbir şey değişmedi.",
6868 false,
6969 ),
70+ (
71+ "restart-requested",
72+ "Restart requested. The runner restarts as soon as it sees the request.",
73+ "Yeniden başlatma istendi. Çalıştırıcı isteği görür görmez yeniden başlar.",
74+ false,
75+ ),
76+ (
77+ "restart-unsupported",
78+ "This runner is too old to restart from the forge. Update it first.",
79+ "Bu çalıştırıcı forge üzerinden yeniden başlatılamayacak kadar eski. Önce güncelleyin.",
80+ true,
81+ ),
7082 (
7183 "invalid",
7284 "That value is not valid for this field. Nothing was changed.",
@@ -136,6 +148,11 @@ struct RunnerRow {
136148 delete_action: String,
137149 detail_href: String,
138150 config_action: String,
151+ restart_action: String,
152+ /// The runner reports a boot id, so it understands a restart request.
153+ can_restart: bool,
154+ /// A restart that was asked for and has not happened yet.
155+ restart_pending: Option<RestartMode>,
139156 /// The concurrency shown in the input: the admin's override, else what the runner reports.
140157 concurrency: String,
141158 /// "UI", "runner.toml" or empty when the runner has not reported.
@@ -206,6 +223,9 @@ fn runner_row(runner: &CiRunner, tz: &str, lang: Lang, now: i64) -> RunnerRow {
206223 delete_action: format!("/admin/runners/{}/delete", enc(&runner.id)),
207224 detail_href: format!("/admin/runners/{}", enc(&runner.id)),
208225 config_action: format!("/admin/runners/{}/config", enc(&runner.id)),
226+ restart_action: format!("/admin/runners/{}/restart", enc(&runner.id)),
227+ can_restart: runner.supports_restart(),
228+ restart_pending: runner.restart.as_ref().map(|r| r.mode),
209229 concurrency,
210230 concurrency_source,
211231 has_override: runner.concurrency_override.is_some(),
@@ -316,6 +336,9 @@ async fn runners_view(
316336 } else {
317337 <span class="ci-state ci-success">(g::t(lang, K::Enabled))</span>
318338 }
339+ if row.restart_pending.is_some() {
340+ <span class="ci-state runner-disabled">(s(lang, "restart pending", "yeniden başlatma bekliyor"))</span>
341+ }
319342 </td>
320343 <td class="runner-actions">
321344 <div class="runner-action-row">
@@ -324,6 +347,7 @@ async fn runners_view(
324347 <input type="hidden" name="disabled" value=(if row.disabled { "0" } else { "1" })>
325348 <button type="submit">(if row.disabled { g::t(lang, K::Enable) } else { g::t(lang, K::Disable) })</button>
326349 </form>
350+ restart_control(lang: lang, csrf: csrf.as_str(), action: row.restart_action.as_str(), back: "list", can_restart: row.can_restart, pending: row.restart_pending)
327351 <form method="post" action=(row.delete_action.as_str()) class="inline-form">
328352 <input type="hidden" name="csrf" value=(csrf.as_str())>
329353 <button type="submit" class="danger">(i18n::t(lang, Key::Delete))</button>
@@ -349,6 +373,42 @@ async fn runners_view(
349373 })
350374 }
351375
376+/// The restart control of a runner: a confirm popover with the two ways to restart. A runner that
377+/// reports no boot id is too old to obey, so the control is off with a hint. While a restart is
378+/// pending the control shows that instead, and the runner clears it by coming back with a new id.
379+#[component]
380+async fn restart_control(
381+ lang: Lang,
382+ csrf: &str,
383+ action: &str,
384+ back: &'static str,
385+ can_restart: bool,
386+ pending: Option<RestartMode>,
387+) -> Result<impl View> {
388+ Ok(view! {
389+ if pending.is_some() {
390+ <span class="muted small">(if pending == Some(RestartMode::Now) { s(lang, "Restarting now...", "Şimdi yeniden başlatılıyor...") } else { s(lang, "Restarting after the current jobs...", "Mevcut işlerden sonra yeniden başlatılıyor...") })</span>
391+ } else if can_restart {
392+ <details class="confirm-inline">
393+ <summary class="button">(s(lang, "Restart", "Yeniden başlat"))</summary>
394+ <div class="confirm-pop">
395+ <p>(s(lang, "Restart this runner? It stops taking jobs first.", "Bu çalıştırıcı yeniden başlatılsın mı? Önce iş almayı bırakır."))</p>
396+ <form method="post" action=(action)>
397+ <input type="hidden" name="csrf" value=(csrf)>
398+ <input type="hidden" name="back" value=(back)>
399+ <button type="submit" name="mode" value="drain" class="primary">(s(lang, "Restart after current jobs", "Mevcut işlerden sonra yeniden başlat"))</button>
400+ <button type="submit" name="mode" value="now" class="danger">(s(lang, "Restart now", "Şimdi yeniden başlat"))</button>
401+ <button type="button" data-close-details="">(s(lang, "Cancel", "Vazgeç"))</button>
402+ </form>
403+ <p class="muted small">(s(lang, "Restart now cancels the running jobs. They end as cancelled and can be run again.", "Şimdi yeniden başlat çalışan işleri iptal eder. İşler iptal edilmiş olarak biter ve yeniden çalıştırılabilir."))</p>
404+ </div>
405+ </details>
406+ } else {
407+ <button type="button" disabled="disabled" title=(s(lang, "Runner too old, update it first", "Çalıştırıcı çok eski, önce güncelleyin"))>(s(lang, "Restart", "Yeniden başlat"))</button>
408+ }
409+ })
410+}
411+
352412 /// The inline number form for concurrency: input, Save, and a reset button while an override is set.
353413 #[component]
354414 async fn concurrency_form(
@@ -947,8 +1007,12 @@ async fn runner_detail_view(
9471007 } else {
9481008 <span class="ci-state ci-success">(g::t(lang, K::Enabled))</span>
9491009 }
1010+ if row.restart_pending.is_some() {
1011+ <span class="ci-state runner-disabled">(s(lang, "restart pending", "yeniden başlatma bekliyor"))</span>
1012+ }
9501013 </div>
9511014 <div class="runner-head-actions">
1015+ restart_control(lang: lang, csrf: csrf.as_str(), action: row.restart_action.as_str(), back: "detail", can_restart: row.can_restart, pending: row.restart_pending)
9521016 <a href="/admin/runners">(g::t(lang, K::BackToRunners))</a>
9531017 </div>
9541018 </section>
@@ -1229,6 +1293,69 @@ async fn runner_set_config(cx: &Cx, Form(form): Form<ConfigForm>) -> Result<SeeO
12291293 }))
12301294 }
12311295
1296+#[derive(Deserialize)]
1297+struct RestartForm {
1298+ #[serde(default)]
1299+ csrf: String,
1300+ /// `drain` (after the current jobs, the default) or `now`.
1301+ #[serde(default)]
1302+ mode: String,
1303+ #[serde(default)]
1304+ back: String,
1305+}
1306+
1307+/// Asks a runner to restart. It stops claiming, finishes or cancels its jobs and restarts, and the
1308+/// request clears when the runner reports a new boot id. A runner that never reported one is too
1309+/// old to obey, so the request is refused rather than left pending forever.
1310+#[route(POST "/admin/runners/{runner_id}/restart")]
1311+async fn runner_restart(cx: &Cx, Form(form): Form<RestartForm>) -> Result<SeeOther> {
1312+ let viewer = admin_only(cx).await?;
1313+ if !check_csrf(&viewer.1, &form.csrf) {
1314+ return Err(forbidden().into());
1315+ }
1316+ let id = path_param::<RunnerId>(cx);
1317+ let state = app_context::<AppState>(cx);
1318+ let back = |notice: &str| {
1319+ if form.back == "detail" {
1320+ see_other(format!("/admin/runners/{}?notice={}", enc(id), enc(notice)))
1321+ } else {
1322+ back_to_list(notice)
1323+ }
1324+ };
1325+ let Some(runner) = runner_named(state, id).await? else {
1326+ return Ok(back_to_list("missing"));
1327+ };
1328+ let mode = if form.mode == "now" {
1329+ RestartMode::Now
1330+ } else {
1331+ RestartMode::Drain
1332+ };
1333+ match state.store.request_runner_restart(id, mode).await {
1334+ Ok(()) => {}
1335+ Err(forge_core::Error::Invalid(_)) => return Ok(back("restart-unsupported")),
1336+ Err(forge_core::Error::NotFound) => return Ok(back_to_list("missing")),
1337+ Err(e) => return Err(e.into()),
1338+ }
1339+ // Wakes a runner that is waiting on a claim, and the live runners pages.
1340+ state.ci_waker.notify_waiters();
1341+ state.ci_live.bump_runners();
1342+ tracing::info!(actor_id = %viewer.0.id, runner_id = %id, mode = mode.as_str(), "ci runner restart requested");
1343+ audit::record(
1344+ &state.store,
1345+ Some(cx),
1346+ Actor::User(&viewer.0),
1347+ AuditAction::CiRunnerRestartRequested,
1348+ Target {
1349+ kind: "ci_runner",
1350+ id: &runner.id,
1351+ name: &runner.name,
1352+ },
1353+ serde_json::json!({ "runner_id": runner.id, "mode": mode.as_str() }),
1354+ )
1355+ .await;
1356+ Ok(back("restart-requested"))
1357+}
1358+
12321359 #[cfg(test)]
12331360 mod tests {
12341361 use super::*;
@@ -1438,6 +1565,114 @@ mod tests {
14381565 assert!(page.contains(r#"<span class="ci-state runner-disabled">disabled</span>"#));
14391566 }
14401567
1568+ #[tokio::test]
1569+ async fn restart_needs_the_capability_and_shows_pending_until_the_runner_returns() {
1570+ let dir = tempfile::tempdir().expect("tempdir");
1571+ let (store, router) = fixture(dir.path()).await;
1572+ let (_, created) = send(
1573+ &router,
1574+ "POST",
1575+ "/admin/runners/tokens",
1576+ Some(ADMIN_TOKEN),
1577+ csrf_form(""),
1578+ )
1579+ .await;
1580+ let token = created
1581+ .split("--token ")
1582+ .nth(1)
1583+ .and_then(|rest| rest.split(' ').next())
1584+ .expect("token")
1585+ .to_owned();
1586+ store
1587+ .register_runner(&token, "box-1", &["linux".to_owned()])
1588+ .await
1589+ .expect("register");
1590+ let runner = store.list_runners().await.expect("list").remove(0);
1591+ let restart = format!("/admin/runners/{}/restart", runner.id);
1592+
1593+ // Not logged in as an admin, or a bad token, changes nothing.
1594+ let (status, _) = send(&router, "POST", &restart, Some(USER_TOKEN), csrf_form("")).await;
1595+ assert_eq!(status, 404);
1596+ let (status, _) = send(
1597+ &router,
1598+ "POST",
1599+ &restart,
1600+ Some(ADMIN_TOKEN),
1601+ Some("csrf=wrong&mode=now".to_owned()),
1602+ )
1603+ .await;
1604+ assert_eq!(status, 403);
1605+
1606+ // A runner that never advertised the capability: the button is off and the post refused.
1607+ let (_, list) = send(&router, "GET", "/admin/runners", Some(ADMIN_TOKEN), None).await;
1608+ assert!(list.contains("Runner too old, update it first"), "{list}");
1609+ let (status, _) = send(
1610+ &router,
1611+ "POST",
1612+ &restart,
1613+ Some(ADMIN_TOKEN),
1614+ csrf_form("&mode=now"),
1615+ )
1616+ .await;
1617+ assert_eq!(status, 303);
1618+ assert_eq!(store.runner_restart(&runner.id).await.unwrap(), None);
1619+
1620+ // With the capability the page offers both choices, and the post is stored and audited.
1621+ store
1622+ .record_runner_report(
1623+ &runner.id,
1624+ &forge_core::ci::RunnerReport {
1625+ boot_id: Some("b1".into()),
1626+ capabilities: vec!["restart".into()],
1627+ ..Default::default()
1628+ },
1629+ )
1630+ .await
1631+ .unwrap();
1632+ let (_, list) = send(&router, "GET", "/admin/runners", Some(ADMIN_TOKEN), None).await;
1633+ assert!(list.contains("Restart after current jobs"));
1634+ assert!(list.contains("Restart now"));
1635+ let (status, _) = send(
1636+ &router,
1637+ "POST",
1638+ &restart,
1639+ Some(ADMIN_TOKEN),
1640+ csrf_form("&mode=drain"),
1641+ )
1642+ .await;
1643+ assert_eq!(status, 303);
1644+ assert_eq!(
1645+ store.runner_restart(&runner.id).await.unwrap(),
1646+ Some(RestartMode::Drain)
1647+ );
1648+ let (_, list) = send(&router, "GET", "/admin/runners", Some(ADMIN_TOKEN), None).await;
1649+ assert!(list.contains("restart pending"));
1650+ let entries = store
1651+ .list_audit(&Default::default(), None, 50)
1652+ .await
1653+ .unwrap();
1654+ assert!(
1655+ entries
1656+ .iter()
1657+ .any(|e| e.action == AuditAction::CiRunnerRestartRequested
1658+ && e.data.contains("drain"))
1659+ );
1660+
1661+ // The runner comes back with a new boot id and the pending state goes away.
1662+ store
1663+ .record_runner_report(
1664+ &runner.id,
1665+ &forge_core::ci::RunnerReport {
1666+ boot_id: Some("b2".into()),
1667+ ..Default::default()
1668+ },
1669+ )
1670+ .await
1671+ .unwrap();
1672+ let (_, list) = send(&router, "GET", "/admin/runners", Some(ADMIN_TOKEN), None).await;
1673+ assert!(!list.contains("restart pending"));
1674+ }
1675+
14411676 #[tokio::test]
14421677 async fn disable_enable_and_delete_a_runner() {
14431678 let dir = tempfile::tempdir().expect("tempdir");