diff --git a/crates/forge-ci/src/proto.rs b/crates/forge-ci/src/proto.rs index a5c00f2..85b5bcb 100644 --- a/crates/forge-ci/src/proto.rs +++ b/crates/forge-ci/src/proto.rs @@ -64,6 +64,50 @@ pub struct ClaimRequest { /// The runner's build identity (`0.1.0 (cf8e648, 2026-10-20)`). Absent from an older runner. #[serde(default, skip_serializing_if = "Option::is_none")] pub build: Option, + /// Random per process start. The forge sees a restart when it changes. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub boot_id: Option, + /// Features this runner has, such as [`CAP_RESTART`]. The crate version is the same for every + /// build, so the forge gates features on this list. Absent from an older runner. + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub capabilities: Vec, +} + +/// The capability of a runner that obeys [`RESTART_HEADER`]. +pub const CAP_RESTART: &str = "restart"; + +/// Response header on a claim: an admin asked this runner to restart. The value is `drain` (finish +/// the running jobs first) or `now` (cancel them). Absent means no request. The runner stops +/// claiming, restarts the way a self-update does (exit 75), and the forge clears +/// the request when it sees a new boot id. +pub const RESTART_HEADER: &str = "Forge-Runner-Restart"; + +/// How a runner restarts when an admin asks. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "lowercase")] +pub enum RestartMode { + /// Stop claiming, let the running jobs finish, then restart. + Drain, + /// Cancel the running jobs, then restart. + Now, +} + +impl RestartMode { + pub fn as_str(self) -> &'static str { + match self { + Self::Drain => "drain", + Self::Now => "now", + } + } + + /// Parses a header value. Anything else counts as no request. + pub fn parse(text: &str) -> Option { + match text.trim() { + "drain" => Some(Self::Drain), + "now" => Some(Self::Now), + _ => None, + } + } } /// Request header on a heartbeat: the runner's build identity, same value as `ClaimRequest::build`. @@ -158,6 +202,9 @@ pub struct HeartbeatResponse { /// A runner at its limit does not claim, so it learns about a change from its heartbeats. #[serde(default, skip_serializing_if = "Option::is_none")] pub concurrency: Option, + /// A restart an admin asked for. Absent from a forge that does not know the feature. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub restart: Option, } /// `POST /api/v1/ci/jobs/{id}/finish`. @@ -197,6 +244,8 @@ mod tests { concurrency: Some(2), version: Some("1.0.0".into()), cpus: Some(8), + boot_id: Some("abc".into()), + capabilities: vec![CAP_RESTART.into()], memory_bytes: Some(1 << 33), build: Some("0.1.0 (cf8e648, 2026-10-20)".into()), }; @@ -207,6 +256,10 @@ mod tests { assert_eq!(beat.concurrency, None); let json = serde_json::to_string(&beat).unwrap(); assert_eq!(json, r#"{"cancel":false}"#); + assert_eq!(beat.restart, None); + let beat: HeartbeatResponse = + serde_json::from_str(r#"{"cancel":false,"restart":"drain"}"#).unwrap(); + assert_eq!(beat.restart, Some(RestartMode::Drain)); } #[test] diff --git a/crates/forge-core/migrations/0057_runner_restart.sql b/crates/forge-core/migrations/0057_runner_restart.sql new file mode 100644 index 0000000..ce4827d --- /dev/null +++ b/crates/forge-core/migrations/0057_runner_restart.sql @@ -0,0 +1,8 @@ +-- An admin can ask a runner to restart itself. The request stays until the runner reports a boot +-- id different from the one it had when asked. Applied by store/migrate.rs. + +ALTER TABLE ci_runners ADD COLUMN reported_boot_id TEXT NULL; +-- Comma separated features the runner says it has, such as "restart". +ALTER TABLE ci_runners ADD COLUMN reported_capabilities TEXT NULL; +ALTER TABLE ci_runners ADD COLUMN restart_mode TEXT NULL; +ALTER TABLE ci_runners ADD COLUMN restart_requested_at TEXT NULL; diff --git a/crates/forge-core/src/audit.rs b/crates/forge-core/src/audit.rs index fa84a4f..52fc8cf 100644 --- a/crates/forge-core/src/audit.rs +++ b/crates/forge-core/src/audit.rs @@ -60,6 +60,7 @@ pub enum AuditAction { CiSecretDeleted, CiRunnerRegistered, CiRunnerDeleted, + CiRunnerRestartRequested, CiRunnerConfigChanged, CiRegistrationTokenCreated, AdvisoryAlertDismissed, @@ -79,6 +80,7 @@ pub enum AuditAction { MailSettingsUpdated, MailTestQueued, ServerSettingsUpdated, + ServerRestarted, SnippetCreated, SnippetUpdated, SnippetDeleted, @@ -164,6 +166,7 @@ impl AuditAction { AuditAction::CiSecretDeleted, AuditAction::CiRunnerRegistered, AuditAction::CiRunnerDeleted, + AuditAction::CiRunnerRestartRequested, AuditAction::CiRunnerConfigChanged, AuditAction::CiRegistrationTokenCreated, AuditAction::AdvisoryAlertDismissed, @@ -183,6 +186,7 @@ impl AuditAction { AuditAction::MailSettingsUpdated, AuditAction::MailTestQueued, AuditAction::ServerSettingsUpdated, + AuditAction::ServerRestarted, AuditAction::SnippetCreated, AuditAction::SnippetUpdated, AuditAction::SnippetDeleted, @@ -267,6 +271,7 @@ impl AuditAction { AuditAction::CiSecretDeleted => "ci_secret_deleted", AuditAction::CiRunnerRegistered => "ci_runner_registered", AuditAction::CiRunnerDeleted => "ci_runner_deleted", + AuditAction::CiRunnerRestartRequested => "ci_runner_restart_requested", AuditAction::CiRunnerConfigChanged => "ci_runner_config_changed", AuditAction::CiRegistrationTokenCreated => "ci_registration_token_created", AuditAction::AdvisoryAlertDismissed => "advisory_alert_dismissed", @@ -286,6 +291,7 @@ impl AuditAction { AuditAction::MailSettingsUpdated => "mail_settings_updated", AuditAction::MailTestQueued => "mail_test_queued", AuditAction::ServerSettingsUpdated => "server_settings_updated", + AuditAction::ServerRestarted => "server_restarted", AuditAction::SnippetCreated => "snippet_created", AuditAction::SnippetUpdated => "snippet_updated", AuditAction::SnippetDeleted => "snippet_deleted", @@ -411,13 +417,13 @@ mod tests { #[test] fn names_are_unique_and_round_trip() { let mut names: Vec<&str> = AuditAction::ALL.iter().map(|a| a.as_str()).collect(); - assert_eq!(names.len(), 99); + assert_eq!(names.len(), 101); for action in AuditAction::ALL { assert_eq!(AuditAction::parse(action.as_str()), Some(*action)); } names.sort(); names.dedup(); - assert_eq!(names.len(), 99); + assert_eq!(names.len(), 101); assert_eq!(AuditAction::parse("nope"), None); } diff --git a/crates/forge-core/src/ci.rs b/crates/forge-core/src/ci.rs index da24fce..9ee3085 100644 --- a/crates/forge-core/src/ci.rs +++ b/crates/forge-core/src/ci.rs @@ -136,10 +136,48 @@ pub struct CiRunner { pub running_jobs: u32, /// The runner's effective config as it last reported it, by field key. Secrets are redacted. pub reported_config: BTreeMap, + /// A restart an admin asked for that the runner has not yet carried out. + pub restart: Option, /// Admin-set values by field key. A key here beats the runner's own runner.toml. pub config_overrides: BTreeMap, } +/// How a runner restarts when an admin asks. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum RestartMode { + /// Stop claiming, let the running jobs finish, then restart. + Drain, + /// Cancel the running jobs and restart at once. + Now, +} + +impl RestartMode { + pub fn as_str(self) -> &'static str { + match self { + Self::Drain => "drain", + Self::Now => "now", + } + } +} + +impl std::str::FromStr for RestartMode { + type Err = (); + fn from_str(s: &str) -> std::result::Result { + match s { + "drain" => Ok(Self::Drain), + "now" => Ok(Self::Now), + _ => Err(()), + } + } +} + +/// A pending runner restart: asked for, not yet seen to happen. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct RunnerRestart { + pub mode: RestartMode, + pub requested_at: String, +} + /// How a runner config field can be changed from the web UI. #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum FieldKind { @@ -342,6 +380,21 @@ pub struct RunnerReport { pub memory_bytes: Option, /// The runner's build identity, like `0.1.0 (cf8e648, 2026-10-20)`. pub build: Option, + /// Random per process start. A change means the runner restarted. + pub boot_id: Option, + /// Features the runner says it has. The crate version never changes between builds, so the + /// forge gates features on these and not on the version. + pub capabilities: Vec, +} + +/// The capability of a runner that restarts when the forge asks. +pub const CAP_RESTART: &str = "restart"; + +impl CiRunner { + /// True when the runner advertises that it honours a restart request. + pub fn supports_restart(&self) -> bool { + self.reported.capabilities.iter().any(|c| c == CAP_RESTART) + } } /// The smallest and largest concurrency an admin may set. diff --git a/crates/forge-core/src/store/ci.rs b/crates/forge-core/src/store/ci.rs index 6ca3ff5..0eae2d9 100644 --- a/crates/forge-core/src/store/ci.rs +++ b/crates/forge-core/src/store/ci.rs @@ -15,7 +15,8 @@ use super::{ }; use crate::ci::{ CiArtifact, CiJob, CiRun, CiRunner, FieldKind, JobState, MAX_RUNNER_CONCURRENCY, - MIN_RUNNER_CONCURRENCY, NewJob, RunState, RunnerReport, validate_runner_field, + MIN_RUNNER_CONCURRENCY, NewJob, RestartMode, RunState, RunnerReport, RunnerRestart, + validate_runner_field, }; use crate::error::{Error, Result}; use crate::secret; @@ -30,7 +31,7 @@ const RUNNER_COLS: &str = "id, name, labels, created_at, last_seen_at, disabled, concurrency_override, reported_concurrency, reported_version, reported_cpus, \ 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_build, reported_boot_id, restart_mode, restart_requested_at, reported_capabilities"; const ARTIFACT_COLS: &str = "id, job_id, name, size, sha256, created_at"; /// Longest runner name, in bytes. @@ -78,6 +79,22 @@ fn map_runner(row: &Row) -> Result { cpus: opt_u32(row, 9)?, memory_bytes: opt_int(row, 10)?.and_then(|n| u64::try_from(n).ok()), build: col_opt_text(row, 14)?, + boot_id: col_opt_text(row, 15)?, + capabilities: col_opt_text(row, 18)? + .map(|t| { + t.split(',') + .filter(|c| !c.is_empty()) + .map(str::to_owned) + .collect() + }) + .unwrap_or_default(), + }, + restart: match (col_opt_text(row, 16)?, col_opt_text(row, 17)?) { + (Some(mode), Some(requested_at)) => mode + .parse::() + .ok() + .map(|mode| RunnerRestart { mode, requested_at }), + _ => None, }, running_jobs: opt_u32(row, 13)?.unwrap_or(0), reported_config: json_map(row, 11)?, @@ -728,13 +745,30 @@ impl Store { cpus: report.cpus.or(current.reported.cpus), memory_bytes: report.memory_bytes.or(current.reported.memory_bytes), build: report.build.clone().or(current.reported.build.clone()), + boot_id: report.boot_id.clone().or(current.reported.boot_id.clone()), + capabilities: if report.capabilities.is_empty() { + current.reported.capabilities.clone() + } else { + report.capabilities.clone() + }, }; if merged == current.reported { return Ok(false); } + // A new boot id while a restart is pending means the runner came back. + if merged.boot_id != current.reported.boot_id && current.restart.is_some() { + conn.execute( + "UPDATE ci_runners SET restart_mode = NULL, restart_requested_at = NULL \ + WHERE id = ?1", + (id.to_string(),), + ) + .await + .map_err(db_err)?; + } conn.execute( "UPDATE ci_runners SET reported_concurrency = ?2, reported_version = ?3, \ - reported_cpus = ?4, reported_memory_bytes = ?5, reported_build = ?6 WHERE id = ?1", + reported_cpus = ?4, reported_memory_bytes = ?5, reported_build = ?6, \ + reported_boot_id = ?7, reported_capabilities = ?8 WHERE id = ?1", ( id.to_string(), opt_int_value(merged.concurrency.map(i64::from)), @@ -742,6 +776,8 @@ impl Store { opt_int_value(merged.cpus.map(i64::from)), opt_int_value(merged.memory_bytes.and_then(|n| i64::try_from(n).ok())), opt_text(merged.build.as_deref()), + opt_text(merged.boot_id.as_deref()), + merged.capabilities.join(","), ), ) .await @@ -749,6 +785,39 @@ impl Store { Ok(true) } + /// Asks a runner to restart itself. A second request replaces the first, so "drain" can be + /// upgraded to "now". `Invalid` when the runner never reported a boot id (too old to obey), + /// `NotFound` when it is gone. + pub async fn request_runner_restart(&self, id: &str, mode: RestartMode) -> Result<()> { + let conn = self.inner.conn.lock().await; + let runner = load_runner(&conn, id).await?.ok_or(Error::NotFound)?; + if !runner.supports_restart() { + return Err(Error::Invalid( + "this runner is too old to restart from the forge".into(), + )); + } + conn.execute( + "UPDATE ci_runners SET restart_mode = ?2, restart_requested_at = ?3 WHERE id = ?1", + (id.to_string(), mode.as_str().to_string(), now_stamp()), + ) + .await + .map_err(db_err)?; + Ok(()) + } + + /// The restart pending for a runner, read fresh. `None` when none or the runner is gone. + pub async fn runner_restart(&self, id: &str) -> Result> { + let conn = self.read_conn().await; + let found = fetch_opt( + &conn, + "SELECT restart_mode FROM ci_runners WHERE id = ?1", + (id.to_string(),), + |row| col_opt_text(row, 0), + ) + .await?; + Ok(found.flatten().and_then(|m| m.parse().ok())) + } + /// Removes a runner. `NotFound` if it does not exist. pub async fn delete_runner(&self, id: &str) -> Result<()> { let conn = self.inner.conn.lock().await; @@ -1700,6 +1769,7 @@ mod tests { reported: RunnerReport::default(), running_jobs: 0, reported_config: BTreeMap::new(), + restart: None, config_overrides: BTreeMap::new(), } } @@ -1896,6 +1966,105 @@ mod tests { )); } + fn boot_report(boot: &str, caps: &[&str]) -> RunnerReport { + RunnerReport { + boot_id: Some(boot.into()), + capabilities: caps.iter().map(|c| c.to_string()).collect(), + ..RunnerReport::default() + } + } + + #[tokio::test] + async fn restart_is_refused_for_a_runner_without_the_capability() { + let fx = fixture().await; + let (runner, _) = runner_with(&fx.store, &fx.tahinli.id, &["linux"]).await; + assert!(!runner.supports_restart()); + assert!(matches!( + fx.store + .request_runner_restart(&runner.id, RestartMode::Drain) + .await, + Err(Error::Invalid(_)) + )); + // A boot id alone is not enough, the version is the same for every build. + fx.store + .record_runner_report(&runner.id, &boot_report("b1", &[])) + .await + .unwrap(); + assert!(matches!( + fx.store + .request_runner_restart(&runner.id, RestartMode::Now) + .await, + Err(Error::Invalid(_)) + )); + assert!(matches!( + fx.store + .request_runner_restart("missing", RestartMode::Now) + .await, + Err(Error::NotFound) + )); + assert_eq!(fx.store.runner_restart(&runner.id).await.unwrap(), None); + } + + #[tokio::test] + async fn restart_request_stays_until_a_new_boot_id_and_can_be_upgraded() { + let fx = fixture().await; + let (runner, _) = runner_with(&fx.store, &fx.tahinli.id, &["linux"]).await; + fx.store + .record_runner_report(&runner.id, &boot_report("b1", &["restart"])) + .await + .unwrap(); + fx.store + .request_runner_restart(&runner.id, RestartMode::Drain) + .await + .unwrap(); + assert_eq!( + fx.store.runner_restart(&runner.id).await.unwrap(), + Some(RestartMode::Drain) + ); + let listed = fx.store.list_runners().await.unwrap().remove(0); + assert_eq!(listed.restart.as_ref().unwrap().mode, RestartMode::Drain); + assert!(listed.supports_restart()); + + // The same process reporting again changes nothing. + fx.store + .record_runner_report(&runner.id, &boot_report("b1", &["restart"])) + .await + .unwrap(); + assert!(fx.store.runner_restart(&runner.id).await.unwrap().is_some()); + // A heartbeat without a boot id changes nothing either. + let beat = RunnerReport { + concurrency: Some(2), + ..RunnerReport::default() + }; + fx.store + .record_runner_report(&runner.id, &beat) + .await + .unwrap(); + assert!(fx.store.runner_restart(&runner.id).await.unwrap().is_some()); + + // "Restart now" replaces the pending drain. + fx.store + .request_runner_restart(&runner.id, RestartMode::Now) + .await + .unwrap(); + assert_eq!( + fx.store.runner_restart(&runner.id).await.unwrap(), + Some(RestartMode::Now) + ); + + // The runner comes back with a new boot id: the request is cleared, capability kept. + assert!( + fx.store + .record_runner_report(&runner.id, &boot_report("b2", &["restart"])) + .await + .unwrap() + ); + assert_eq!(fx.store.runner_restart(&runner.id).await.unwrap(), None); + let listed = fx.store.list_runners().await.unwrap().remove(0); + assert!(listed.restart.is_none()); + assert!(listed.supports_restart()); + } + #[tokio::test] async fn runner_report_round_trip_and_running_count() { let fx = fixture().await; @@ -1908,6 +2077,8 @@ mod tests { cpus: Some(8), memory_bytes: Some(16 << 30), build: Some("0.1.0 (cf8e648, 2026-10-20)".into()), + boot_id: Some("boot-1".into()), + capabilities: vec!["restart".into()], }; assert!( fx.store diff --git a/crates/forge-core/src/store/migrate.rs b/crates/forge-core/src/store/migrate.rs index 2ced58e..93580fc 100644 --- a/crates/forge-core/src/store/migrate.rs +++ b/crates/forge-core/src/store/migrate.rs @@ -96,6 +96,7 @@ pub const MIGRATIONS: &[(u32, &str)] = &[ include_str!("../../migrations/0055_user_suspensions.sql"), ), (56, include_str!("../../migrations/0056_runner_build.sql")), + (57, include_str!("../../migrations/0057_runner_restart.sql")), ]; /// The highest migration version this binary knows about. diff --git a/crates/forge-runner/src/cli.rs b/crates/forge-runner/src/cli.rs index 9386d24..6c1084f 100644 --- a/crates/forge-runner/src/cli.rs +++ b/crates/forge-runner/src/cli.rs @@ -278,6 +278,8 @@ async fn run(cli: Cli) -> Result> { RunEnd::Stopped => Ok(ExitCode::SUCCESS), // systemd restarts the runner on this code, and it starts the new binary. RunEnd::Updated => Ok(ExitCode::from(update::RESTART_EXIT_CODE)), + // An admin asked for a restart. The same exit code, the same systemd restart. + RunEnd::Restart => Ok(ExitCode::from(update::RESTART_EXIT_CODE)), } } Command::Check { diff --git a/crates/forge-runner/src/client.rs b/crates/forge-runner/src/client.rs index 96d8ddb..094566a 100644 --- a/crates/forge-runner/src/client.rs +++ b/crates/forge-runner/src/client.rs @@ -7,8 +7,9 @@ use std::path::Path; use std::time::Duration; use forge_ci::proto::{ - BUILD_HEADER, CONCURRENCY_HEADER, ClaimRequest, FinishRequest, HeartbeatResponse, - JobAssignment, RegisterRequest, RegisterResponse, RunnerConfigOverrides, RunnerConfigReport, + BUILD_HEADER, CAP_RESTART, CONCURRENCY_HEADER, ClaimRequest, FinishRequest, HeartbeatResponse, + JobAssignment, RESTART_HEADER, RegisterRequest, RegisterResponse, RestartMode, + RunnerConfigOverrides, RunnerConfigReport, }; use reqwest::StatusCode; use reqwest::header::{CONTENT_LENGTH, HeaderMap}; @@ -63,6 +64,8 @@ pub struct ClaimReply { pub binary_sha256: Option, /// The concurrency an admin set in the web UI. `None` means no override. pub concurrency: Option, + /// A restart an admin asked for, from the `Forge-Runner-Restart` header. + pub restart: Option, } /// A client for one forge base URL. @@ -126,6 +129,8 @@ impl ForgeClient { cpus: host.cpus, memory_bytes: host.memory_bytes, build: Some(forge_ci::build::display()), + boot_id: Some(crate::restart::boot_id().to_owned()), + capabilities: vec![CAP_RESTART.to_owned()], }; let target = format!("{}-{}", std::env::consts::ARCH, std::env::consts::OS); let resp = self @@ -139,16 +144,19 @@ impl ForgeClient { .await?; let binary_sha256 = advertised_sha256(resp.headers()); let concurrency = advertised_concurrency(resp.headers()); + let restart = advertised_restart(resp.headers()); match resp.status() { StatusCode::NO_CONTENT => Ok(ClaimReply { job: None, binary_sha256, concurrency, + restart, }), status if status.is_success() => Ok(ClaimReply { job: Some(resp.json().await?), binary_sha256, concurrency, + restart, }), _ => Err(status_error(resp).await), } @@ -348,6 +356,11 @@ fn advertised_concurrency(headers: &HeaderMap) -> Option { .ok() } +/// The `Forge-Runner-Restart` header, when it holds a mode this runner knows. +fn advertised_restart(headers: &HeaderMap) -> Option { + RestartMode::parse(headers.get(RESTART_HEADER)?.to_str().ok()?) +} + /// Cheap facts about the host that help an admin size the runner's concurrency. struct HostFacts { cpus: Option, @@ -402,6 +415,18 @@ mod tests { assert_eq!(parse_mem_total("nothing"), None); } + #[test] + fn restart_header_must_name_a_mode() { + let mut headers = HeaderMap::new(); + assert_eq!(advertised_restart(&headers), None); + headers.insert(RESTART_HEADER, "drain".parse().unwrap()); + assert_eq!(advertised_restart(&headers), Some(RestartMode::Drain)); + headers.insert(RESTART_HEADER, "now".parse().unwrap()); + assert_eq!(advertised_restart(&headers), Some(RestartMode::Now)); + headers.insert(RESTART_HEADER, "later".parse().unwrap()); + assert_eq!(advertised_restart(&headers), None); + } + #[test] fn concurrency_header_must_be_a_number() { let mut headers = HeaderMap::new(); diff --git a/crates/forge-runner/src/lib.rs b/crates/forge-runner/src/lib.rs index 9bf74d2..4861901 100644 --- a/crates/forge-runner/src/lib.rs +++ b/crates/forge-runner/src/lib.rs @@ -14,6 +14,7 @@ pub mod executor; pub mod limiter; pub mod logs; pub mod oci; +pub mod restart; pub mod runner; pub mod sandbox; pub mod update; diff --git a/crates/forge-runner/src/restart.rs b/crates/forge-runner/src/restart.rs new file mode 100644 index 0000000..3b740d2 --- /dev/null +++ b/crates/forge-runner/src/restart.rs @@ -0,0 +1,139 @@ +//! Restart on request. An admin can ask a runner to restart from the forge's web UI. The request +//! arrives in a claim answer or a heartbeat answer. The runner then stops claiming, waits for or +//! cancels its jobs, and ends its loop with [`crate::runner::RunEnd::Restart`]. The caller exits +//! with [`crate::update::RESTART_EXIT_CODE`], the same way a self-update ends, so the supervisor +//! (systemd `Restart=on-failure`) starts the binary again. Nothing here polls. + +use std::sync::OnceLock; +use std::sync::atomic::{AtomicBool, Ordering}; +use std::sync::{Mutex, PoisonError}; + +use forge_ci::proto::RestartMode; +use tokio::sync::Notify; + +/// A restart request seen from the forge, shared by the claim loop and the job heartbeats. +#[derive(Default)] +pub struct RestartState { + mode: Mutex>, + wake: Notify, + /// Set once the running jobs were cancelled for a `now` restart. + cancelled: AtomicBool, +} + +impl RestartState { + /// Records what the forge said. `None` changes nothing, because a request cannot be taken + /// back from the runner's side. `drain` never replaces `now`. Wakes the loop on a change. + pub fn observe(&self, said: Option) { + let Some(said) = said else { return }; + let mut mode = self.mode.lock().unwrap_or_else(PoisonError::into_inner); + let next = match (*mode, said) { + (Some(RestartMode::Now), _) => RestartMode::Now, + (_, said) => said, + }; + if *mode != Some(next) { + *mode = Some(next); + self.wake.notify_one(); + } + } + + pub fn pending(&self) -> Option { + *self.mode.lock().unwrap_or_else(PoisonError::into_inner) + } + + /// Resolves after the pending request changed. + pub async fn changed(&self) { + self.wake.notified().await; + } + + pub fn mark_cancelled(&self) { + self.cancelled.store(true, Ordering::SeqCst); + } + + /// Whether running jobs were cancelled for a `now` restart. + pub fn jobs_cancelled(&self) -> bool { + self.cancelled.load(Ordering::SeqCst) + } +} + +/// What the claim loop does next about a restart request. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Step { + /// No request: claim as usual. + Proceed, + /// Cancel the running jobs, then wait for them. + CancelJobs, + /// Claim nothing and wait for a running job to end. + WaitForJobs, + /// Nothing is running: leave the loop so the process restarts. + Restart, +} + +/// The drain-then-restart decision. `cancelled` says whether the jobs were already cancelled. +pub fn decide(pending: Option, running: usize, cancelled: bool) -> Step { + match pending { + None => Step::Proceed, + Some(_) if running == 0 => Step::Restart, + Some(RestartMode::Now) if !cancelled => Step::CancelJobs, + Some(_) => Step::WaitForJobs, + } +} + +/// An id that is new for every process start. The forge sees a restart when it changes. +pub fn boot_id() -> &'static str { + static ID: OnceLock = OnceLock::new(); + ID.get_or_init(|| { + let nanos = std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .map_or(0, |d| d.as_nanos()); + format!("{:x}-{nanos:x}", std::process::id()) + }) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn no_request_means_claim_as_usual() { + assert_eq!(decide(None, 3, false), Step::Proceed); + } + + #[test] + fn drain_waits_for_running_jobs_then_restarts() { + let drain = Some(RestartMode::Drain); + assert_eq!(decide(drain, 2, false), Step::WaitForJobs); + assert_eq!(decide(drain, 1, false), Step::WaitForJobs); + assert_eq!(decide(drain, 0, false), Step::Restart); + } + + #[test] + fn now_cancels_once_then_waits_then_restarts() { + let now = Some(RestartMode::Now); + assert_eq!(decide(now, 2, false), Step::CancelJobs); + assert_eq!(decide(now, 2, true), Step::WaitForJobs); + assert_eq!(decide(now, 0, true), Step::Restart); + assert_eq!(decide(now, 0, false), Step::Restart); + } + + #[test] + fn a_request_is_latched_and_now_beats_drain() { + let state = RestartState::default(); + assert_eq!(state.pending(), None); + state.observe(None); + assert_eq!(state.pending(), None); + state.observe(Some(RestartMode::Drain)); + assert_eq!(state.pending(), Some(RestartMode::Drain)); + state.observe(None); + assert_eq!(state.pending(), Some(RestartMode::Drain)); + state.observe(Some(RestartMode::Now)); + assert_eq!(state.pending(), Some(RestartMode::Now)); + state.observe(Some(RestartMode::Drain)); + assert_eq!(state.pending(), Some(RestartMode::Now)); + } + + #[test] + fn the_boot_id_is_stable_within_a_process() { + assert_eq!(boot_id(), boot_id()); + assert!(!boot_id().is_empty()); + } +} diff --git a/crates/forge-runner/src/runner.rs b/crates/forge-runner/src/runner.rs index 6e21544..c0d595c 100644 --- a/crates/forge-runner/src/runner.rs +++ b/crates/forge-runner/src/runner.rs @@ -18,6 +18,7 @@ use crate::config::RunnerConfig; use crate::executor::{ExecRequest, ExecResult, Executor}; use crate::limiter::Limiter; use crate::logs::{self, PumpConfig}; +use crate::restart::{self, RestartState, Step}; use crate::update::{self, Installed, UpdateState}; use crate::workspace; @@ -56,6 +57,9 @@ pub enum RunEnd { Stopped, /// The binary was replaced. The caller exits with [`update::RESTART_EXIT_CODE`]. Updated, + /// An admin asked for a restart and the jobs are done. The caller exits with + /// [`update::RESTART_EXIT_CODE`], like for an update. + Restart, } /// A runner bound to one forge and one executor. @@ -69,6 +73,8 @@ pub struct Runner { cache: Option>, /// The live job limit. Starts at `runner.toml` and follows the forge's override. limiter: Arc, + /// A restart an admin asked for, see [`restart`]. + restart: Arc, } impl Runner { @@ -86,6 +92,7 @@ impl Runner { options, cache: None, limiter, + restart: Arc::new(RestartState::default()), }) } @@ -129,7 +136,38 @@ impl Runner { auto_update = updates.enabled(), "runner started" ); + // Parent of every job's token, so a `now` restart can cancel them all at once. + let jobs_cancel = shutdown.child_token(); let end = loop { + match restart::decide( + self.restart.pending(), + jobs.len(), + self.restart.jobs_cancelled(), + ) { + Step::Proceed => {} + Step::Restart => { + tracing::info!("restart requested by the forge, restarting"); + break RunEnd::Restart; + } + Step::CancelJobs => { + tracing::info!("restart now requested, cancelling running jobs"); + self.restart.mark_cancelled(); + jobs_cancel.cancel(); + continue; + } + Step::WaitForJobs => { + tokio::select! { + _ = shutdown.cancelled() => break RunEnd::Stopped, + Some(joined) = jobs.join_next() => { + if let Err(e) = joined { + tracing::error!(error = %e, "job task panicked"); + } + } + () = self.restart.changed() => {} + } + continue; + } + } if let Some((exe_path, _)) = &exe && let Some(sha) = updates.pending().map(str::to_owned) { @@ -166,6 +204,7 @@ impl Runner { let permit = tokio::select! { _ = shutdown.cancelled() => break RunEnd::Stopped, + () = self.restart.changed() => continue, permit = self.limiter.acquire() => match permit { Ok(permit) => permit, Err(_) => break RunEnd::Stopped, @@ -186,6 +225,7 @@ impl Runner { Ok(reply) => { // No header means no override: back to the runner.toml value. self.limiter.apply_logged(reply.concurrency); + self.restart.observe(reply.restart); if updates.observe(reply.binary_sha256.as_deref()) && let Some(sha) = updates.pending() { @@ -200,7 +240,7 @@ impl Runner { "claimed job" ); let runner = self.clone(); - let cancel = shutdown.child_token(); + let cancel = jobs_cancel.child_token(); jobs.spawn(async move { let _permit = permit; runner.process(job, cancel).await; @@ -334,6 +374,10 @@ impl Runner { }; } + if self.restart.jobs_cancelled() && result.outcome == Outcome::Cancelled { + result.message = Some("cancelled because an admin restarted the runner".to_owned()); + } + // The save decides on the final outcome. It also clears the job's scratch dirs. if let (Some(cache), Some(dir)) = (&self.cache, workspace_dir.as_deref()) { for line in cache.save(&job, result.outcome, dir).await { @@ -364,6 +408,7 @@ impl Runner { fn spawn_heartbeat(&self, job: &JobAssignment, cancel: CancellationToken) -> JoinHandle<()> { let client = self.client.clone(); let limiter = self.limiter.clone(); + let restart = self.restart.clone(); let job_id = job.job_id.clone(); let token = job.job_token.clone(); let every = self.options.heartbeat_every; @@ -377,12 +422,16 @@ impl Runner { { Ok(beat) if beat.cancel => { limiter.apply_logged(beat.concurrency); + restart.observe(beat.restart); tracing::info!(job_id = %job_id, "forge requested cancel"); cancel.cancel(); return; } // A runner at its limit does not claim, so the heartbeat carries changes too. - Ok(beat) => limiter.apply_logged(beat.concurrency), + Ok(beat) => { + limiter.apply_logged(beat.concurrency); + restart.observe(beat.restart); + } Err(e) => tracing::warn!(job_id = %job_id, error = %e, "heartbeat failed"), } } diff --git a/crates/forge-runner/tests/flow.rs b/crates/forge-runner/tests/flow.rs index 768fe53..accb4e6 100644 --- a/crates/forge-runner/tests/flow.rs +++ b/crates/forge-runner/tests/flow.rs @@ -130,6 +130,7 @@ fn route( Reply::json(&forge_ci::proto::HeartbeatResponse { cancel, concurrency: None, + restart: None, }) } ("PUT", ["artifacts", name]) => { diff --git a/crates/forge-web/src/ci/api.rs b/crates/forge-web/src/ci/api.rs index 5649b4e..38d89af 100644 --- a/crates/forge-web/src/ci/api.rs +++ b/crates/forge-web/src/ci/api.rs @@ -10,8 +10,8 @@ use forge_ci::config::JobSpec; use forge_ci::mask::Masker; use forge_ci::proto::{ BUILD_HEADER, CONCURRENCY_HEADER, ClaimRequest, FinishRequest, HeartbeatResponse, - JobAssignment, Outcome, RegisterRequest, RegisterResponse, RunnerConfigOverrides, - RunnerConfigReport, + JobAssignment, Outcome, RESTART_HEADER, RegisterRequest, RegisterResponse, + RestartMode as WireRestart, RunnerConfigOverrides, RunnerConfigReport, }; use forge_core::Error as CoreError; use forge_core::ci::{CiJob, CiRun, CiRunner, JobState, RunState, RunnerReport}; @@ -194,12 +194,20 @@ async fn claim(cx: &Cx, body: Body) -> topcoat::Result { cpus: request.cpus, memory_bytes: request.memory_bytes, build: request.build.filter(|v| v.len() <= 64), + boot_id: request.boot_id.filter(|v| v.len() <= 64), + capabilities: request + .capabilities + .into_iter() + .filter(|c| !c.is_empty() && c.len() <= 32 && !c.contains(',')) + .take(16) + .collect(), }, ) .await; let mut res = claim_work(state, &runner).await?; // The override can change during the long poll, so it is read at answer time. set_concurrency_header(state, &runner.id, &mut res).await; + set_restart_header(state, &runner.id, &mut res).await; // Advertises the binary sha256 when self-update is on and the runner asked for this target. self_update::advertise(state, headers(cx), &mut res); Ok(res) @@ -226,6 +234,24 @@ async fn set_concurrency_header(state: &AppState, runner_id: &str, res: &mut Res } } +/// The restart an admin asked for, in the wire type. `None` when nothing is pending. +async fn pending_restart(state: &AppState, runner_id: &str) -> Option { + let mode = state.store.runner_restart(runner_id).await.ok().flatten()?; + WireRestart::parse(mode.as_str()) +} + +/// Adds the pending restart request to a claim answer. Sent on every answer until the runner +/// comes back with a new boot id. An older runner ignores the header. +async fn set_restart_header(state: &AppState, runner_id: &str, res: &mut Response) { + if !matches!(res.status(), StatusCode::OK | StatusCode::NO_CONTENT) { + return; + } + if let Some(mode) = pending_restart(state, runner_id).await { + res.headers_mut() + .insert(RESTART_HEADER, HeaderValue::from_static(mode.as_str())); + } +} + /// `GET` and `PUT /api/v1/ci/runners/config`. The runner reads the admin's overrides when it /// starts, applies them to its in-memory config, then reports its effective config here. #[route(GET "/api/v1/ci/runners/config")] @@ -285,6 +311,11 @@ async fn claim_work(state: &AppState, runner: &CiRunner) -> topcoat::Result return Ok(assignment_response(&assignment)), Ok(None) => {} @@ -507,6 +538,7 @@ async fn heartbeat(cx: &Cx) -> topcoat::Result { // The runner says its live concurrency, and the answer carries the admin's override. // A runner at its limit does not claim, so this is how it learns about a change. let mut concurrency = None; + let mut restart = None; if let Some(runner_id) = job.runner_id.as_deref() { let said = headers(cx) .get(CONCURRENCY_HEADER) @@ -532,12 +564,14 @@ async fn heartbeat(cx: &Cx) -> topcoat::Result { .await .ok() .flatten(); + restart = pending_restart(state, runner_id).await; } Ok(api::json( StatusCode::OK, &serde_json::to_value(HeartbeatResponse { cancel, concurrency, + restart, }) .unwrap_or_default(), )) diff --git a/crates/forge-web/src/ci/api_tests.rs b/crates/forge-web/src/ci/api_tests.rs index 23b22c3..74745cf 100644 --- a/crates/forge-web/src/ci/api_tests.rs +++ b/crates/forge-web/src/ci/api_tests.rs @@ -528,6 +528,80 @@ async fn claim_and_heartbeat_carry_the_concurrency_round_trip() { assert!(beat.json().get("concurrency").is_none()); } +async fn post_claim(router: &Router, secret: &str, boot: &str) -> Sent { + let body = serde_json::json!({ "labels": [], "boot_id": boot, "capabilities": ["restart"] }); + send( + router, + "POST", + "/api/v1/ci/runners/claim", + &[bearer(secret)], + json_body(&body), + ) + .await +} + +#[tokio::test] +async fn a_restart_request_is_delivered_until_the_runner_comes_back_with_a_new_boot_id() { + use forge_core::ci::RestartMode; + + let env = bare(|_| {}).await; + let (runner, secret) = runner(&env, &[]).await; + make_run(&env, "push", None, COMMIT, &[job("a", spec(&[], &[]))]).await; + // A runner without the capability cannot be asked. + assert!( + env.store + .request_runner_restart(&runner.id, RestartMode::Drain) + .await + .is_err() + ); + + // The first claim reports the capability and takes the job. No restart header yet. + let sent = post_claim(&env.router, &secret, "boot-1").await; + assert_eq!(sent.status, 200); + assert!(sent.headers.get("Forge-Runner-Restart").is_none()); + let assignment = sent.json(); + let uri = format!( + "/api/v1/ci/jobs/{}/heartbeat", + assignment["job_id"].as_str().unwrap() + ); + let token = assignment["job_token"].as_str().unwrap(); + + env.store + .request_runner_restart(&runner.id, RestartMode::Drain) + .await + .unwrap(); + make_run(&env, "push", None, COMMIT, &[job("b", spec(&[], &[]))]).await; + + // Delivered on the heartbeat, and the claim answers at once with no new job. + let beat = send(&env.router, "POST", &uri, &[bearer(token)], Vec::new()).await; + assert_eq!(beat.json()["restart"], "drain"); + let sent = post_claim(&env.router, &secret, "boot-1").await; + assert_eq!( + sent.status, 204, + "a runner that is to restart gets no new job" + ); + assert_eq!(sent.headers.get("Forge-Runner-Restart").unwrap(), "drain"); + // Still delivered while the same process keeps asking. + let sent = post_claim(&env.router, &secret, "boot-1").await; + assert_eq!(sent.headers.get("Forge-Runner-Restart").unwrap(), "drain"); + + // "Now" replaces "drain". + env.store + .request_runner_restart(&runner.id, RestartMode::Now) + .await + .unwrap(); + let beat = send(&env.router, "POST", &uri, &[bearer(token)], Vec::new()).await; + assert_eq!(beat.json()["restart"], "now"); + + // A new boot id clears it: no header, no field, and jobs flow again. + let sent = post_claim(&env.router, &secret, "boot-2").await; + assert_eq!(sent.status, 200); + assert!(sent.headers.get("Forge-Runner-Restart").is_none()); + assert_eq!(env.store.runner_restart(&runner.id).await.unwrap(), None); + let beat = send(&env.router, "POST", &uri, &[bearer(token)], Vec::new()).await; + assert!(beat.json().get("restart").is_none()); +} + #[tokio::test] async fn runner_config_report_and_overrides_round_trip() { let env = bare(|_| {}).await; diff --git a/crates/forge-web/src/pages/admin_runners.rs b/crates/forge-web/src/pages/admin_runners.rs index 8631fbd..3852369 100644 --- a/crates/forge-web/src/pages/admin_runners.rs +++ b/crates/forge-web/src/pages/admin_runners.rs @@ -8,7 +8,7 @@ use forge_ci::build::{self, Freshness}; use forge_core::AuditAction; -use forge_core::ci::{CiRunner, FieldKind, RUNNER_FIELDS, runner_field}; +use forge_core::ci::{CiRunner, FieldKind, RUNNER_FIELDS, RestartMode, runner_field}; use serde::Deserialize; use time::OffsetDateTime; use time::format_description::well_known::Rfc3339; @@ -42,7 +42,7 @@ fn s(lang: Lang, en: &'static str, tr: &'static str) -> &'static str { } /// Extra notice words: (word, English, Turkish, is an error). -const EXTRA_NOTICES: [(&str, &str, &str, bool); 6] = [ +const EXTRA_NOTICES: [(&str, &str, &str, bool); 8] = [ ( "saved", "Saved. The runner picks it up on its next check-in.", @@ -67,6 +67,18 @@ const EXTRA_NOTICES: [(&str, &str, &str, bool); 6] = [ "Hiçbir şey değişmedi.", false, ), + ( + "restart-requested", + "Restart requested. The runner restarts as soon as it sees the request.", + "Yeniden başlatma istendi. Çalıştırıcı isteği görür görmez yeniden başlar.", + false, + ), + ( + "restart-unsupported", + "This runner is too old to restart from the forge. Update it first.", + "Bu çalıştırıcı forge üzerinden yeniden başlatılamayacak kadar eski. Önce güncelleyin.", + true, + ), ( "invalid", "That value is not valid for this field. Nothing was changed.", @@ -136,6 +148,11 @@ struct RunnerRow { delete_action: String, detail_href: String, config_action: String, + restart_action: String, + /// The runner reports a boot id, so it understands a restart request. + can_restart: bool, + /// A restart that was asked for and has not happened yet. + restart_pending: Option, /// The concurrency shown in the input: the admin's override, else what the runner reports. concurrency: String, /// "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 { delete_action: format!("/admin/runners/{}/delete", enc(&runner.id)), detail_href: format!("/admin/runners/{}", enc(&runner.id)), config_action: format!("/admin/runners/{}/config", enc(&runner.id)), + restart_action: format!("/admin/runners/{}/restart", enc(&runner.id)), + can_restart: runner.supports_restart(), + restart_pending: runner.restart.as_ref().map(|r| r.mode), concurrency, concurrency_source, has_override: runner.concurrency_override.is_some(), @@ -316,6 +336,9 @@ async fn runners_view( } else { (g::t(lang, K::Enabled)) } + if row.restart_pending.is_some() { + (s(lang, "restart pending", "yeniden başlatma bekliyor")) + }
@@ -324,6 +347,7 @@ async fn runners_view( + 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)
@@ -349,6 +373,42 @@ async fn runners_view( }) } +/// The restart control of a runner: a confirm popover with the two ways to restart. A runner that +/// reports no boot id is too old to obey, so the control is off with a hint. While a restart is +/// pending the control shows that instead, and the runner clears it by coming back with a new id. +#[component] +async fn restart_control( + lang: Lang, + csrf: &str, + action: &str, + back: &'static str, + can_restart: bool, + pending: Option, +) -> Result { + Ok(view! { + if pending.is_some() { + (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...") }) + } else if can_restart { +
+ (s(lang, "Restart", "Yeniden başlat")) +
+

(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."))

+ + + + + + + +

(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."))

+
+
+ } else { + + } + }) +} + /// The inline number form for concurrency: input, Save, and a reset button while an override is set. #[component] async fn concurrency_form( @@ -947,8 +1007,12 @@ async fn runner_detail_view( } else { (g::t(lang, K::Enabled)) } + if row.restart_pending.is_some() { + (s(lang, "restart pending", "yeniden başlatma bekliyor")) + }
+ 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) (g::t(lang, K::BackToRunners))
@@ -1229,6 +1293,69 @@ async fn runner_set_config(cx: &Cx, Form(form): Form) -> Result) -> Result { + let viewer = admin_only(cx).await?; + if !check_csrf(&viewer.1, &form.csrf) { + return Err(forbidden().into()); + } + let id = path_param::(cx); + let state = app_context::(cx); + let back = |notice: &str| { + if form.back == "detail" { + see_other(format!("/admin/runners/{}?notice={}", enc(id), enc(notice))) + } else { + back_to_list(notice) + } + }; + let Some(runner) = runner_named(state, id).await? else { + return Ok(back_to_list("missing")); + }; + let mode = if form.mode == "now" { + RestartMode::Now + } else { + RestartMode::Drain + }; + match state.store.request_runner_restart(id, mode).await { + Ok(()) => {} + Err(forge_core::Error::Invalid(_)) => return Ok(back("restart-unsupported")), + Err(forge_core::Error::NotFound) => return Ok(back_to_list("missing")), + Err(e) => return Err(e.into()), + } + // Wakes a runner that is waiting on a claim, and the live runners pages. + state.ci_waker.notify_waiters(); + state.ci_live.bump_runners(); + tracing::info!(actor_id = %viewer.0.id, runner_id = %id, mode = mode.as_str(), "ci runner restart requested"); + audit::record( + &state.store, + Some(cx), + Actor::User(&viewer.0), + AuditAction::CiRunnerRestartRequested, + Target { + kind: "ci_runner", + id: &runner.id, + name: &runner.name, + }, + serde_json::json!({ "runner_id": runner.id, "mode": mode.as_str() }), + ) + .await; + Ok(back("restart-requested")) +} + #[cfg(test)] mod tests { use super::*; @@ -1438,6 +1565,114 @@ mod tests { assert!(page.contains(r#"disabled"#)); } + #[tokio::test] + async fn restart_needs_the_capability_and_shows_pending_until_the_runner_returns() { + let dir = tempfile::tempdir().expect("tempdir"); + let (store, router) = fixture(dir.path()).await; + let (_, created) = send( + &router, + "POST", + "/admin/runners/tokens", + Some(ADMIN_TOKEN), + csrf_form(""), + ) + .await; + let token = created + .split("--token ") + .nth(1) + .and_then(|rest| rest.split(' ').next()) + .expect("token") + .to_owned(); + store + .register_runner(&token, "box-1", &["linux".to_owned()]) + .await + .expect("register"); + let runner = store.list_runners().await.expect("list").remove(0); + let restart = format!("/admin/runners/{}/restart", runner.id); + + // Not logged in as an admin, or a bad token, changes nothing. + let (status, _) = send(&router, "POST", &restart, Some(USER_TOKEN), csrf_form("")).await; + assert_eq!(status, 404); + let (status, _) = send( + &router, + "POST", + &restart, + Some(ADMIN_TOKEN), + Some("csrf=wrong&mode=now".to_owned()), + ) + .await; + assert_eq!(status, 403); + + // A runner that never advertised the capability: the button is off and the post refused. + let (_, list) = send(&router, "GET", "/admin/runners", Some(ADMIN_TOKEN), None).await; + assert!(list.contains("Runner too old, update it first"), "{list}"); + let (status, _) = send( + &router, + "POST", + &restart, + Some(ADMIN_TOKEN), + csrf_form("&mode=now"), + ) + .await; + assert_eq!(status, 303); + assert_eq!(store.runner_restart(&runner.id).await.unwrap(), None); + + // With the capability the page offers both choices, and the post is stored and audited. + store + .record_runner_report( + &runner.id, + &forge_core::ci::RunnerReport { + boot_id: Some("b1".into()), + capabilities: vec!["restart".into()], + ..Default::default() + }, + ) + .await + .unwrap(); + let (_, list) = send(&router, "GET", "/admin/runners", Some(ADMIN_TOKEN), None).await; + assert!(list.contains("Restart after current jobs")); + assert!(list.contains("Restart now")); + let (status, _) = send( + &router, + "POST", + &restart, + Some(ADMIN_TOKEN), + csrf_form("&mode=drain"), + ) + .await; + assert_eq!(status, 303); + assert_eq!( + store.runner_restart(&runner.id).await.unwrap(), + Some(RestartMode::Drain) + ); + let (_, list) = send(&router, "GET", "/admin/runners", Some(ADMIN_TOKEN), None).await; + assert!(list.contains("restart pending")); + let entries = store + .list_audit(&Default::default(), None, 50) + .await + .unwrap(); + assert!( + entries + .iter() + .any(|e| e.action == AuditAction::CiRunnerRestartRequested + && e.data.contains("drain")) + ); + + // The runner comes back with a new boot id and the pending state goes away. + store + .record_runner_report( + &runner.id, + &forge_core::ci::RunnerReport { + boot_id: Some("b2".into()), + ..Default::default() + }, + ) + .await + .unwrap(); + let (_, list) = send(&router, "GET", "/admin/runners", Some(ADMIN_TOKEN), None).await; + assert!(!list.contains("restart pending")); + } + #[tokio::test] async fn disable_enable_and_delete_a_runner() { let dir = tempfile::tempdir().expect("tempdir");