Restart a runner from the admin pages, after its jobs or now
Browse files at this commit767f2d06c7c0c4ba7a09b3edd0495adcfa43bbf8Parent: c80f705- feat
- restart a runner from the admin pages, after its jobs or now
15 changed files +865 -13
- crates/forge-ci/src/proto.rs +53 -0
- crates/forge-core/migrations/0057_runner_restart.sql +8 -0
- crates/forge-core/src/audit.rs +8 -2
- crates/forge-core/src/ci.rs +53 -0
- crates/forge-core/src/store/ci.rs +174 -3
- crates/forge-core/src/store/migrate.rs +1 -0
- crates/forge-runner/src/cli.rs +2 -0
- crates/forge-runner/src/client.rs +27 -2
- crates/forge-runner/src/lib.rs +1 -0
- crates/forge-runner/src/restart.rs +139 -0
- crates/forge-runner/src/runner.rs +51 -2
- crates/forge-runner/tests/flow.rs +1 -0
- crates/forge-web/src/ci/api.rs +36 -2
- crates/forge-web/src/ci/api_tests.rs +74 -0
- crates/forge-web/src/pages/admin_runners.rs +237 -2
crates/forge-ci/src/proto.rsmodified+53 -0
| @@ -64,6 +64,50 @@ pub struct ClaimRequest { | |||
| 64 | /// The runner's build identity (`0.1.0 (cf8e648, 2026-10-20)`). Absent from an older runner. | 64 | /// The runner's build identity (`0.1.0 (cf8e648, 2026-10-20)`). Absent from an older runner. |
| 65 | #[serde(default, skip_serializing_if = "Option::is_none")] | 65 | #[serde(default, skip_serializing_if = "Option::is_none")] |
| 66 | pub build: Option<String>, | 66 | 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 | + } | ||
| 67 | } | 111 | } |
| 68 | 112 | ||
| 69 | /// Request header on a heartbeat: the runner's build identity, same value as `ClaimRequest::build`. | 113 | /// Request header on a heartbeat: the runner's build identity, same value as `ClaimRequest::build`. |
| @@ -158,6 +202,9 @@ pub struct HeartbeatResponse { | |||
| 158 | /// A runner at its limit does not claim, so it learns about a change from its heartbeats. | 202 | /// A runner at its limit does not claim, so it learns about a change from its heartbeats. |
| 159 | #[serde(default, skip_serializing_if = "Option::is_none")] | 203 | #[serde(default, skip_serializing_if = "Option::is_none")] |
| 160 | pub concurrency: Option<u32>, | 204 | 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>, | ||
| 161 | } | 208 | } |
| 162 | 209 | ||
| 163 | /// `POST /api/v1/ci/jobs/{id}/finish`. | 210 | /// `POST /api/v1/ci/jobs/{id}/finish`. |
| @@ -197,6 +244,8 @@ mod tests { | |||
| 197 | concurrency: Some(2), | 244 | concurrency: Some(2), |
| 198 | version: Some("1.0.0".into()), | 245 | version: Some("1.0.0".into()), |
| 199 | cpus: Some(8), | 246 | cpus: Some(8), |
| 247 | + boot_id: Some("abc".into()), | ||
| 248 | + capabilities: vec![CAP_RESTART.into()], | ||
| 200 | memory_bytes: Some(1 << 33), | 249 | memory_bytes: Some(1 << 33), |
| 201 | build: Some("0.1.0 (cf8e648, 2026-10-20)".into()), | 250 | build: Some("0.1.0 (cf8e648, 2026-10-20)".into()), |
| 202 | }; | 251 | }; |
| @@ -207,6 +256,10 @@ mod tests { | |||
| 207 | assert_eq!(beat.concurrency, None); | 256 | assert_eq!(beat.concurrency, None); |
| 208 | let json = serde_json::to_string(&beat).unwrap(); | 257 | let json = serde_json::to_string(&beat).unwrap(); |
| 209 | assert_eq!(json, r#"{"cancel":false}"#); | 258 | 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)); | ||
| 210 | } | 263 | } |
| 211 | 264 | ||
| 212 | #[test] | 265 | #[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 { | |||
| 60 | CiSecretDeleted, | 60 | CiSecretDeleted, |
| 61 | CiRunnerRegistered, | 61 | CiRunnerRegistered, |
| 62 | CiRunnerDeleted, | 62 | CiRunnerDeleted, |
| 63 | + CiRunnerRestartRequested, | ||
| 63 | CiRunnerConfigChanged, | 64 | CiRunnerConfigChanged, |
| 64 | CiRegistrationTokenCreated, | 65 | CiRegistrationTokenCreated, |
| 65 | AdvisoryAlertDismissed, | 66 | AdvisoryAlertDismissed, |
| @@ -79,6 +80,7 @@ pub enum AuditAction { | |||
| 79 | MailSettingsUpdated, | 80 | MailSettingsUpdated, |
| 80 | MailTestQueued, | 81 | MailTestQueued, |
| 81 | ServerSettingsUpdated, | 82 | ServerSettingsUpdated, |
| 83 | + ServerRestarted, | ||
| 82 | SnippetCreated, | 84 | SnippetCreated, |
| 83 | SnippetUpdated, | 85 | SnippetUpdated, |
| 84 | SnippetDeleted, | 86 | SnippetDeleted, |
| @@ -164,6 +166,7 @@ impl AuditAction { | |||
| 164 | AuditAction::CiSecretDeleted, | 166 | AuditAction::CiSecretDeleted, |
| 165 | AuditAction::CiRunnerRegistered, | 167 | AuditAction::CiRunnerRegistered, |
| 166 | AuditAction::CiRunnerDeleted, | 168 | AuditAction::CiRunnerDeleted, |
| 169 | + AuditAction::CiRunnerRestartRequested, | ||
| 167 | AuditAction::CiRunnerConfigChanged, | 170 | AuditAction::CiRunnerConfigChanged, |
| 168 | AuditAction::CiRegistrationTokenCreated, | 171 | AuditAction::CiRegistrationTokenCreated, |
| 169 | AuditAction::AdvisoryAlertDismissed, | 172 | AuditAction::AdvisoryAlertDismissed, |
| @@ -183,6 +186,7 @@ impl AuditAction { | |||
| 183 | AuditAction::MailSettingsUpdated, | 186 | AuditAction::MailSettingsUpdated, |
| 184 | AuditAction::MailTestQueued, | 187 | AuditAction::MailTestQueued, |
| 185 | AuditAction::ServerSettingsUpdated, | 188 | AuditAction::ServerSettingsUpdated, |
| 189 | + AuditAction::ServerRestarted, | ||
| 186 | AuditAction::SnippetCreated, | 190 | AuditAction::SnippetCreated, |
| 187 | AuditAction::SnippetUpdated, | 191 | AuditAction::SnippetUpdated, |
| 188 | AuditAction::SnippetDeleted, | 192 | AuditAction::SnippetDeleted, |
| @@ -267,6 +271,7 @@ impl AuditAction { | |||
| 267 | AuditAction::CiSecretDeleted => "ci_secret_deleted", | 271 | AuditAction::CiSecretDeleted => "ci_secret_deleted", |
| 268 | AuditAction::CiRunnerRegistered => "ci_runner_registered", | 272 | AuditAction::CiRunnerRegistered => "ci_runner_registered", |
| 269 | AuditAction::CiRunnerDeleted => "ci_runner_deleted", | 273 | AuditAction::CiRunnerDeleted => "ci_runner_deleted", |
| 274 | + AuditAction::CiRunnerRestartRequested => "ci_runner_restart_requested", | ||
| 270 | AuditAction::CiRunnerConfigChanged => "ci_runner_config_changed", | 275 | AuditAction::CiRunnerConfigChanged => "ci_runner_config_changed", |
| 271 | AuditAction::CiRegistrationTokenCreated => "ci_registration_token_created", | 276 | AuditAction::CiRegistrationTokenCreated => "ci_registration_token_created", |
| 272 | AuditAction::AdvisoryAlertDismissed => "advisory_alert_dismissed", | 277 | AuditAction::AdvisoryAlertDismissed => "advisory_alert_dismissed", |
| @@ -286,6 +291,7 @@ impl AuditAction { | |||
| 286 | AuditAction::MailSettingsUpdated => "mail_settings_updated", | 291 | AuditAction::MailSettingsUpdated => "mail_settings_updated", |
| 287 | AuditAction::MailTestQueued => "mail_test_queued", | 292 | AuditAction::MailTestQueued => "mail_test_queued", |
| 288 | AuditAction::ServerSettingsUpdated => "server_settings_updated", | 293 | AuditAction::ServerSettingsUpdated => "server_settings_updated", |
| 294 | + AuditAction::ServerRestarted => "server_restarted", | ||
| 289 | AuditAction::SnippetCreated => "snippet_created", | 295 | AuditAction::SnippetCreated => "snippet_created", |
| 290 | AuditAction::SnippetUpdated => "snippet_updated", | 296 | AuditAction::SnippetUpdated => "snippet_updated", |
| 291 | AuditAction::SnippetDeleted => "snippet_deleted", | 297 | AuditAction::SnippetDeleted => "snippet_deleted", |
| @@ -411,13 +417,13 @@ mod tests { | |||
| 411 | #[test] | 417 | #[test] |
| 412 | fn names_are_unique_and_round_trip() { | 418 | fn names_are_unique_and_round_trip() { |
| 413 | let mut names: Vec<&str> = AuditAction::ALL.iter().map(|a| a.as_str()).collect(); | 419 | 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); |
| 415 | for action in AuditAction::ALL { | 421 | for action in AuditAction::ALL { |
| 416 | assert_eq!(AuditAction::parse(action.as_str()), Some(*action)); | 422 | assert_eq!(AuditAction::parse(action.as_str()), Some(*action)); |
| 417 | } | 423 | } |
| 418 | names.sort(); | 424 | names.sort(); |
| 419 | names.dedup(); | 425 | names.dedup(); |
| 420 | - assert_eq!(names.len(), 99); | 426 | + assert_eq!(names.len(), 101); |
| 421 | assert_eq!(AuditAction::parse("nope"), None); | 427 | assert_eq!(AuditAction::parse("nope"), None); |
| 422 | } | 428 | } |
| 423 | 429 | ||
crates/forge-core/src/ci.rsmodified+53 -0
| @@ -136,10 +136,48 @@ pub struct CiRunner { | |||
| 136 | pub running_jobs: u32, | 136 | pub running_jobs: u32, |
| 137 | /// The runner's effective config as it last reported it, by field key. Secrets are redacted. | 137 | /// The runner's effective config as it last reported it, by field key. Secrets are redacted. |
| 138 | pub reported_config: BTreeMap<String, serde_json::Value>, | 138 | 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>, | ||
| 139 | /// Admin-set values by field key. A key here beats the runner's own runner.toml. | 141 | /// Admin-set values by field key. A key here beats the runner's own runner.toml. |
| 140 | pub config_overrides: BTreeMap<String, serde_json::Value>, | 142 | pub config_overrides: BTreeMap<String, serde_json::Value>, |
| 141 | } | 143 | } |
| 142 | 144 | ||
| 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 | + | ||
| 143 | /// How a runner config field can be changed from the web UI. | 181 | /// How a runner config field can be changed from the web UI. |
| 144 | #[derive(Debug, Clone, Copy, PartialEq, Eq)] | 182 | #[derive(Debug, Clone, Copy, PartialEq, Eq)] |
| 145 | pub enum FieldKind { | 183 | pub enum FieldKind { |
| @@ -342,6 +380,21 @@ pub struct RunnerReport { | |||
| 342 | pub memory_bytes: Option<u64>, | 380 | pub memory_bytes: Option<u64>, |
| 343 | /// The runner's build identity, like `0.1.0 (cf8e648, 2026-10-20)`. | 381 | /// The runner's build identity, like `0.1.0 (cf8e648, 2026-10-20)`. |
| 344 | pub build: Option<String>, | 382 | 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 | + } | ||
| 345 | } | 398 | } |
| 346 | 399 | ||
| 347 | /// The smallest and largest concurrency an admin may set. | 400 | /// The smallest and largest concurrency an admin may set. |
crates/forge-core/src/store/ci.rsmodified+174 -3
| @@ -15,7 +15,8 @@ use super::{ | |||
| 15 | }; | 15 | }; |
| 16 | use crate::ci::{ | 16 | use crate::ci::{ |
| 17 | CiArtifact, CiJob, CiRun, CiRunner, FieldKind, JobState, MAX_RUNNER_CONCURRENCY, | 17 | 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, | ||
| 19 | }; | 20 | }; |
| 20 | use crate::error::{Error, Result}; | 21 | use crate::error::{Error, Result}; |
| 21 | use crate::secret; | 22 | use crate::secret; |
| @@ -30,7 +31,7 @@ const RUNNER_COLS: &str = "id, name, labels, created_at, last_seen_at, disabled, | |||
| 30 | concurrency_override, reported_concurrency, reported_version, reported_cpus, \ | 31 | concurrency_override, reported_concurrency, reported_version, reported_cpus, \ |
| 31 | reported_memory_bytes, reported_config, config_overrides, \ | 32 | reported_memory_bytes, reported_config, config_overrides, \ |
| 32 | (SELECT COUNT(*) FROM ci_jobs WHERE ci_jobs.runner_id = ci_runners.id AND ci_jobs.state = 'running'), \ | 33 | (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"; |
| 34 | const ARTIFACT_COLS: &str = "id, job_id, name, size, sha256, created_at"; | 35 | const ARTIFACT_COLS: &str = "id, job_id, name, size, sha256, created_at"; |
| 35 | 36 | ||
| 36 | /// Longest runner name, in bytes. | 37 | /// Longest runner name, in bytes. |
| @@ -78,6 +79,22 @@ fn map_runner(row: &Row) -> Result<CiRunner> { | |||
| 78 | cpus: opt_u32(row, 9)?, | 79 | cpus: opt_u32(row, 9)?, |
| 79 | memory_bytes: opt_int(row, 10)?.and_then(|n| u64::try_from(n).ok()), | 80 | memory_bytes: opt_int(row, 10)?.and_then(|n| u64::try_from(n).ok()), |
| 80 | build: col_opt_text(row, 14)?, | 81 | 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, | ||
| 81 | }, | 98 | }, |
| 82 | running_jobs: opt_u32(row, 13)?.unwrap_or(0), | 99 | running_jobs: opt_u32(row, 13)?.unwrap_or(0), |
| 83 | reported_config: json_map(row, 11)?, | 100 | reported_config: json_map(row, 11)?, |
| @@ -728,13 +745,30 @@ impl Store { | |||
| 728 | cpus: report.cpus.or(current.reported.cpus), | 745 | cpus: report.cpus.or(current.reported.cpus), |
| 729 | memory_bytes: report.memory_bytes.or(current.reported.memory_bytes), | 746 | memory_bytes: report.memory_bytes.or(current.reported.memory_bytes), |
| 730 | build: report.build.clone().or(current.reported.build.clone()), | 747 | 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 | + }, | ||
| 731 | }; | 754 | }; |
| 732 | if merged == current.reported { | 755 | if merged == current.reported { |
| 733 | return Ok(false); | 756 | return Ok(false); |
| 734 | } | 757 | } |
| 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 | + } | ||
| 735 | conn.execute( | 768 | conn.execute( |
| 736 | "UPDATE ci_runners SET reported_concurrency = ?2, reported_version = ?3, \ | 769 | "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", | ||
| 738 | ( | 772 | ( |
| 739 | id.to_string(), | 773 | id.to_string(), |
| 740 | opt_int_value(merged.concurrency.map(i64::from)), | 774 | opt_int_value(merged.concurrency.map(i64::from)), |
| @@ -742,6 +776,8 @@ impl Store { | |||
| 742 | opt_int_value(merged.cpus.map(i64::from)), | 776 | opt_int_value(merged.cpus.map(i64::from)), |
| 743 | opt_int_value(merged.memory_bytes.and_then(|n| i64::try_from(n).ok())), | 777 | opt_int_value(merged.memory_bytes.and_then(|n| i64::try_from(n).ok())), |
| 744 | opt_text(merged.build.as_deref()), | 778 | opt_text(merged.build.as_deref()), |
| 779 | + opt_text(merged.boot_id.as_deref()), | ||
| 780 | + merged.capabilities.join(","), | ||
| 745 | ), | 781 | ), |
| 746 | ) | 782 | ) |
| 747 | .await | 783 | .await |
| @@ -749,6 +785,39 @@ impl Store { | |||
| 749 | Ok(true) | 785 | Ok(true) |
| 750 | } | 786 | } |
| 751 | 787 | ||
| 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 | + | ||
| 752 | /// Removes a runner. `NotFound` if it does not exist. | 821 | /// Removes a runner. `NotFound` if it does not exist. |
| 753 | pub async fn delete_runner(&self, id: &str) -> Result<()> { | 822 | pub async fn delete_runner(&self, id: &str) -> Result<()> { |
| 754 | let conn = self.inner.conn.lock().await; | 823 | let conn = self.inner.conn.lock().await; |
| @@ -1700,6 +1769,7 @@ mod tests { | |||
| 1700 | reported: RunnerReport::default(), | 1769 | reported: RunnerReport::default(), |
| 1701 | running_jobs: 0, | 1770 | running_jobs: 0, |
| 1702 | reported_config: BTreeMap::new(), | 1771 | reported_config: BTreeMap::new(), |
| 1772 | + restart: None, | ||
| 1703 | config_overrides: BTreeMap::new(), | 1773 | config_overrides: BTreeMap::new(), |
| 1704 | } | 1774 | } |
| 1705 | } | 1775 | } |
| @@ -1896,6 +1966,105 @@ mod tests { | |||
| 1896 | )); | 1966 | )); |
| 1897 | } | 1967 | } |
| 1898 | 1968 | ||
| 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 | + | ||
| 1899 | #[tokio::test] | 2068 | #[tokio::test] |
| 1900 | async fn runner_report_round_trip_and_running_count() { | 2069 | async fn runner_report_round_trip_and_running_count() { |
| 1901 | let fx = fixture().await; | 2070 | let fx = fixture().await; |
| @@ -1908,6 +2077,8 @@ mod tests { | |||
| 1908 | cpus: Some(8), | 2077 | cpus: Some(8), |
| 1909 | memory_bytes: Some(16 << 30), | 2078 | memory_bytes: Some(16 << 30), |
| 1910 | build: Some("0.1.0 (cf8e648, 2026-10-20)".into()), | 2079 | build: Some("0.1.0 (cf8e648, 2026-10-20)".into()), |
| 2080 | + boot_id: Some("boot-1".into()), | ||
| 2081 | + capabilities: vec!["restart".into()], | ||
| 1911 | }; | 2082 | }; |
| 1912 | assert!( | 2083 | assert!( |
| 1913 | fx.store | 2084 | fx.store |
crates/forge-core/src/store/migrate.rsmodified+1 -0
| @@ -96,6 +96,7 @@ pub const MIGRATIONS: &[(u32, &str)] = &[ | |||
| 96 | include_str!("../../migrations/0055_user_suspensions.sql"), | 96 | include_str!("../../migrations/0055_user_suspensions.sql"), |
| 97 | ), | 97 | ), |
| 98 | (56, include_str!("../../migrations/0056_runner_build.sql")), | 98 | (56, include_str!("../../migrations/0056_runner_build.sql")), |
| 99 | + (57, include_str!("../../migrations/0057_runner_restart.sql")), | ||
| 99 | ]; | 100 | ]; |
| 100 | 101 | ||
| 101 | /// The highest migration version this binary knows about. | 102 | /// 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>> { | |||
| 278 | RunEnd::Stopped => Ok(ExitCode::SUCCESS), | 278 | RunEnd::Stopped => Ok(ExitCode::SUCCESS), |
| 279 | // systemd restarts the runner on this code, and it starts the new binary. | 279 | // systemd restarts the runner on this code, and it starts the new binary. |
| 280 | RunEnd::Updated => Ok(ExitCode::from(update::RESTART_EXIT_CODE)), | 280 | 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)), | ||
| 281 | } | 283 | } |
| 282 | } | 284 | } |
| 283 | Command::Check { | 285 | Command::Check { |
crates/forge-runner/src/client.rsmodified+27 -2
| @@ -7,8 +7,9 @@ use std::path::Path; | |||
| 7 | use std::time::Duration; | 7 | use std::time::Duration; |
| 8 | 8 | ||
| 9 | use forge_ci::proto::{ | 9 | use forge_ci::proto::{ |
| 10 | - BUILD_HEADER, CONCURRENCY_HEADER, ClaimRequest, FinishRequest, HeartbeatResponse, | 10 | + BUILD_HEADER, CAP_RESTART, CONCURRENCY_HEADER, ClaimRequest, FinishRequest, HeartbeatResponse, |
| 11 | - JobAssignment, RegisterRequest, RegisterResponse, RunnerConfigOverrides, RunnerConfigReport, | 11 | + JobAssignment, RESTART_HEADER, RegisterRequest, RegisterResponse, RestartMode, |
| 12 | + RunnerConfigOverrides, RunnerConfigReport, | ||
| 12 | }; | 13 | }; |
| 13 | use reqwest::StatusCode; | 14 | use reqwest::StatusCode; |
| 14 | use reqwest::header::{CONTENT_LENGTH, HeaderMap}; | 15 | use reqwest::header::{CONTENT_LENGTH, HeaderMap}; |
| @@ -63,6 +64,8 @@ pub struct ClaimReply { | |||
| 63 | pub binary_sha256: Option<String>, | 64 | pub binary_sha256: Option<String>, |
| 64 | /// The concurrency an admin set in the web UI. `None` means no override. | 65 | /// The concurrency an admin set in the web UI. `None` means no override. |
| 65 | pub concurrency: Option<u32>, | 66 | pub concurrency: Option<u32>, |
| 67 | + /// A restart an admin asked for, from the `Forge-Runner-Restart` header. | ||
| 68 | + pub restart: Option<RestartMode>, | ||
| 66 | } | 69 | } |
| 67 | 70 | ||
| 68 | /// A client for one forge base URL. | 71 | /// A client for one forge base URL. |
| @@ -126,6 +129,8 @@ impl ForgeClient { | |||
| 126 | cpus: host.cpus, | 129 | cpus: host.cpus, |
| 127 | memory_bytes: host.memory_bytes, | 130 | memory_bytes: host.memory_bytes, |
| 128 | build: Some(forge_ci::build::display()), | 131 | build: Some(forge_ci::build::display()), |
| 132 | + boot_id: Some(crate::restart::boot_id().to_owned()), | ||
| 133 | + capabilities: vec![CAP_RESTART.to_owned()], | ||
| 129 | }; | 134 | }; |
| 130 | let target = format!("{}-{}", std::env::consts::ARCH, std::env::consts::OS); | 135 | let target = format!("{}-{}", std::env::consts::ARCH, std::env::consts::OS); |
| 131 | let resp = self | 136 | let resp = self |
| @@ -139,16 +144,19 @@ impl ForgeClient { | |||
| 139 | .await?; | 144 | .await?; |
| 140 | let binary_sha256 = advertised_sha256(resp.headers()); | 145 | let binary_sha256 = advertised_sha256(resp.headers()); |
| 141 | let concurrency = advertised_concurrency(resp.headers()); | 146 | let concurrency = advertised_concurrency(resp.headers()); |
| 147 | + let restart = advertised_restart(resp.headers()); | ||
| 142 | match resp.status() { | 148 | match resp.status() { |
| 143 | StatusCode::NO_CONTENT => Ok(ClaimReply { | 149 | StatusCode::NO_CONTENT => Ok(ClaimReply { |
| 144 | job: None, | 150 | job: None, |
| 145 | binary_sha256, | 151 | binary_sha256, |
| 146 | concurrency, | 152 | concurrency, |
| 153 | + restart, | ||
| 147 | }), | 154 | }), |
| 148 | status if status.is_success() => Ok(ClaimReply { | 155 | status if status.is_success() => Ok(ClaimReply { |
| 149 | job: Some(resp.json().await?), | 156 | job: Some(resp.json().await?), |
| 150 | binary_sha256, | 157 | binary_sha256, |
| 151 | concurrency, | 158 | concurrency, |
| 159 | + restart, | ||
| 152 | }), | 160 | }), |
| 153 | _ => Err(status_error(resp).await), | 161 | _ => Err(status_error(resp).await), |
| 154 | } | 162 | } |
| @@ -348,6 +356,11 @@ fn advertised_concurrency(headers: &HeaderMap) -> Option<u32> { | |||
| 348 | .ok() | 356 | .ok() |
| 349 | } | 357 | } |
| 350 | 358 | ||
| 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 | + | ||
| 351 | /// Cheap facts about the host that help an admin size the runner's concurrency. | 364 | /// Cheap facts about the host that help an admin size the runner's concurrency. |
| 352 | struct HostFacts { | 365 | struct HostFacts { |
| 353 | cpus: Option<u32>, | 366 | cpus: Option<u32>, |
| @@ -402,6 +415,18 @@ mod tests { | |||
| 402 | assert_eq!(parse_mem_total("nothing"), None); | 415 | assert_eq!(parse_mem_total("nothing"), None); |
| 403 | } | 416 | } |
| 404 | 417 | ||
| 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 | + | ||
| 405 | #[test] | 430 | #[test] |
| 406 | fn concurrency_header_must_be_a_number() { | 431 | fn concurrency_header_must_be_a_number() { |
| 407 | let mut headers = HeaderMap::new(); | 432 | let mut headers = HeaderMap::new(); |
crates/forge-runner/src/lib.rsmodified+1 -0
| @@ -14,6 +14,7 @@ pub mod executor; | |||
| 14 | pub mod limiter; | 14 | pub mod limiter; |
| 15 | pub mod logs; | 15 | pub mod logs; |
| 16 | pub mod oci; | 16 | pub mod oci; |
| 17 | +pub mod restart; | ||
| 17 | pub mod runner; | 18 | pub mod runner; |
| 18 | pub mod sandbox; | 19 | pub mod sandbox; |
| 19 | pub mod update; | 20 | 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; | |||
| 18 | use crate::executor::{ExecRequest, ExecResult, Executor}; | 18 | use crate::executor::{ExecRequest, ExecResult, Executor}; |
| 19 | use crate::limiter::Limiter; | 19 | use crate::limiter::Limiter; |
| 20 | use crate::logs::{self, PumpConfig}; | 20 | use crate::logs::{self, PumpConfig}; |
| 21 | +use crate::restart::{self, RestartState, Step}; | ||
| 21 | use crate::update::{self, Installed, UpdateState}; | 22 | use crate::update::{self, Installed, UpdateState}; |
| 22 | use crate::workspace; | 23 | use crate::workspace; |
| 23 | 24 | ||
| @@ -56,6 +57,9 @@ pub enum RunEnd { | |||
| 56 | Stopped, | 57 | Stopped, |
| 57 | /// The binary was replaced. The caller exits with [`update::RESTART_EXIT_CODE`]. | 58 | /// The binary was replaced. The caller exits with [`update::RESTART_EXIT_CODE`]. |
| 58 | Updated, | 59 | 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, | ||
| 59 | } | 63 | } |
| 60 | 64 | ||
| 61 | /// A runner bound to one forge and one executor. | 65 | /// A runner bound to one forge and one executor. |
| @@ -69,6 +73,8 @@ pub struct Runner { | |||
| 69 | cache: Option<Arc<CacheStore>>, | 73 | cache: Option<Arc<CacheStore>>, |
| 70 | /// The live job limit. Starts at `runner.toml` and follows the forge's override. | 74 | /// The live job limit. Starts at `runner.toml` and follows the forge's override. |
| 71 | limiter: Arc<Limiter>, | 75 | limiter: Arc<Limiter>, |
| 76 | + /// A restart an admin asked for, see [`restart`]. | ||
| 77 | + restart: Arc<RestartState>, | ||
| 72 | } | 78 | } |
| 73 | 79 | ||
| 74 | impl Runner { | 80 | impl Runner { |
| @@ -86,6 +92,7 @@ impl Runner { | |||
| 86 | options, | 92 | options, |
| 87 | cache: None, | 93 | cache: None, |
| 88 | limiter, | 94 | limiter, |
| 95 | + restart: Arc::new(RestartState::default()), | ||
| 89 | }) | 96 | }) |
| 90 | } | 97 | } |
| 91 | 98 | ||
| @@ -129,7 +136,38 @@ impl Runner { | |||
| 129 | auto_update = updates.enabled(), | 136 | auto_update = updates.enabled(), |
| 130 | "runner started" | 137 | "runner started" |
| 131 | ); | 138 | ); |
| 139 | + // Parent of every job's token, so a `now` restart can cancel them all at once. | ||
| 140 | + let jobs_cancel = shutdown.child_token(); | ||
| 132 | let end = loop { | 141 | 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 | + } | ||
| 133 | if let Some((exe_path, _)) = &exe | 171 | if let Some((exe_path, _)) = &exe |
| 134 | && let Some(sha) = updates.pending().map(str::to_owned) | 172 | && let Some(sha) = updates.pending().map(str::to_owned) |
| 135 | { | 173 | { |
| @@ -166,6 +204,7 @@ impl Runner { | |||
| 166 | 204 | ||
| 167 | let permit = tokio::select! { | 205 | let permit = tokio::select! { |
| 168 | _ = shutdown.cancelled() => break RunEnd::Stopped, | 206 | _ = shutdown.cancelled() => break RunEnd::Stopped, |
| 207 | + () = self.restart.changed() => continue, | ||
| 169 | permit = self.limiter.acquire() => match permit { | 208 | permit = self.limiter.acquire() => match permit { |
| 170 | Ok(permit) => permit, | 209 | Ok(permit) => permit, |
| 171 | Err(_) => break RunEnd::Stopped, | 210 | Err(_) => break RunEnd::Stopped, |
| @@ -186,6 +225,7 @@ impl Runner { | |||
| 186 | Ok(reply) => { | 225 | Ok(reply) => { |
| 187 | // No header means no override: back to the runner.toml value. | 226 | // No header means no override: back to the runner.toml value. |
| 188 | self.limiter.apply_logged(reply.concurrency); | 227 | self.limiter.apply_logged(reply.concurrency); |
| 228 | + self.restart.observe(reply.restart); | ||
| 189 | if updates.observe(reply.binary_sha256.as_deref()) | 229 | if updates.observe(reply.binary_sha256.as_deref()) |
| 190 | && let Some(sha) = updates.pending() | 230 | && let Some(sha) = updates.pending() |
| 191 | { | 231 | { |
| @@ -200,7 +240,7 @@ impl Runner { | |||
| 200 | "claimed job" | 240 | "claimed job" |
| 201 | ); | 241 | ); |
| 202 | let runner = self.clone(); | 242 | let runner = self.clone(); |
| 203 | - let cancel = shutdown.child_token(); | 243 | + let cancel = jobs_cancel.child_token(); |
| 204 | jobs.spawn(async move { | 244 | jobs.spawn(async move { |
| 205 | let _permit = permit; | 245 | let _permit = permit; |
| 206 | runner.process(job, cancel).await; | 246 | runner.process(job, cancel).await; |
| @@ -334,6 +374,10 @@ impl Runner { | |||
| 334 | }; | 374 | }; |
| 335 | } | 375 | } |
| 336 | 376 | ||
| 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 | + | ||
| 337 | // The save decides on the final outcome. It also clears the job's scratch dirs. | 381 | // The save decides on the final outcome. It also clears the job's scratch dirs. |
| 338 | if let (Some(cache), Some(dir)) = (&self.cache, workspace_dir.as_deref()) { | 382 | if let (Some(cache), Some(dir)) = (&self.cache, workspace_dir.as_deref()) { |
| 339 | for line in cache.save(&job, result.outcome, dir).await { | 383 | for line in cache.save(&job, result.outcome, dir).await { |
| @@ -364,6 +408,7 @@ impl Runner { | |||
| 364 | fn spawn_heartbeat(&self, job: &JobAssignment, cancel: CancellationToken) -> JoinHandle<()> { | 408 | fn spawn_heartbeat(&self, job: &JobAssignment, cancel: CancellationToken) -> JoinHandle<()> { |
| 365 | let client = self.client.clone(); | 409 | let client = self.client.clone(); |
| 366 | let limiter = self.limiter.clone(); | 410 | let limiter = self.limiter.clone(); |
| 411 | + let restart = self.restart.clone(); | ||
| 367 | let job_id = job.job_id.clone(); | 412 | let job_id = job.job_id.clone(); |
| 368 | let token = job.job_token.clone(); | 413 | let token = job.job_token.clone(); |
| 369 | let every = self.options.heartbeat_every; | 414 | let every = self.options.heartbeat_every; |
| @@ -377,12 +422,16 @@ impl Runner { | |||
| 377 | { | 422 | { |
| 378 | Ok(beat) if beat.cancel => { | 423 | Ok(beat) if beat.cancel => { |
| 379 | limiter.apply_logged(beat.concurrency); | 424 | limiter.apply_logged(beat.concurrency); |
| 425 | + restart.observe(beat.restart); | ||
| 380 | tracing::info!(job_id = %job_id, "forge requested cancel"); | 426 | tracing::info!(job_id = %job_id, "forge requested cancel"); |
| 381 | cancel.cancel(); | 427 | cancel.cancel(); |
| 382 | return; | 428 | return; |
| 383 | } | 429 | } |
| 384 | // A runner at its limit does not claim, so the heartbeat carries changes too. | 430 | // 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 | + } | ||
| 386 | Err(e) => tracing::warn!(job_id = %job_id, error = %e, "heartbeat failed"), | 435 | Err(e) => tracing::warn!(job_id = %job_id, error = %e, "heartbeat failed"), |
| 387 | } | 436 | } |
| 388 | } | 437 | } |
crates/forge-runner/tests/flow.rsmodified+1 -0
| @@ -130,6 +130,7 @@ fn route( | |||
| 130 | Reply::json(&forge_ci::proto::HeartbeatResponse { | 130 | Reply::json(&forge_ci::proto::HeartbeatResponse { |
| 131 | cancel, | 131 | cancel, |
| 132 | concurrency: None, | 132 | concurrency: None, |
| 133 | + restart: None, | ||
| 133 | }) | 134 | }) |
| 134 | } | 135 | } |
| 135 | ("PUT", ["artifacts", name]) => { | 136 | ("PUT", ["artifacts", name]) => { |
crates/forge-web/src/ci/api.rsmodified+36 -2
| @@ -10,8 +10,8 @@ use forge_ci::config::JobSpec; | |||
| 10 | use forge_ci::mask::Masker; | 10 | use forge_ci::mask::Masker; |
| 11 | use forge_ci::proto::{ | 11 | use forge_ci::proto::{ |
| 12 | BUILD_HEADER, CONCURRENCY_HEADER, ClaimRequest, FinishRequest, HeartbeatResponse, | 12 | BUILD_HEADER, CONCURRENCY_HEADER, ClaimRequest, FinishRequest, HeartbeatResponse, |
| 13 | - JobAssignment, Outcome, RegisterRequest, RegisterResponse, RunnerConfigOverrides, | 13 | + JobAssignment, Outcome, RESTART_HEADER, RegisterRequest, RegisterResponse, |
| 14 | - RunnerConfigReport, | 14 | + RestartMode as WireRestart, RunnerConfigOverrides, RunnerConfigReport, |
| 15 | }; | 15 | }; |
| 16 | use forge_core::Error as CoreError; | 16 | use forge_core::Error as CoreError; |
| 17 | use forge_core::ci::{CiJob, CiRun, CiRunner, JobState, RunState, RunnerReport}; | 17 | use forge_core::ci::{CiJob, CiRun, CiRunner, JobState, RunState, RunnerReport}; |
| @@ -194,12 +194,20 @@ async fn claim(cx: &Cx, body: Body) -> topcoat::Result<Response> { | |||
| 194 | cpus: request.cpus, | 194 | cpus: request.cpus, |
| 195 | memory_bytes: request.memory_bytes, | 195 | memory_bytes: request.memory_bytes, |
| 196 | build: request.build.filter(|v| v.len() <= 64), | 196 | 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(), | ||
| 197 | }, | 204 | }, |
| 198 | ) | 205 | ) |
| 199 | .await; | 206 | .await; |
| 200 | let mut res = claim_work(state, &runner).await?; | 207 | let mut res = claim_work(state, &runner).await?; |
| 201 | // The override can change during the long poll, so it is read at answer time. | 208 | // The override can change during the long poll, so it is read at answer time. |
| 202 | set_concurrency_header(state, &runner.id, &mut res).await; | 209 | set_concurrency_header(state, &runner.id, &mut res).await; |
| 210 | + set_restart_header(state, &runner.id, &mut res).await; | ||
| 203 | // Advertises the binary sha256 when self-update is on and the runner asked for this target. | 211 | // Advertises the binary sha256 when self-update is on and the runner asked for this target. |
| 204 | self_update::advertise(state, headers(cx), &mut res); | 212 | self_update::advertise(state, headers(cx), &mut res); |
| 205 | Ok(res) | 213 | Ok(res) |
| @@ -226,6 +234,24 @@ async fn set_concurrency_header(state: &AppState, runner_id: &str, res: &mut Res | |||
| 226 | } | 234 | } |
| 227 | } | 235 | } |
| 228 | 236 | ||
| 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 | + | ||
| 229 | /// `GET` and `PUT /api/v1/ci/runners/config`. The runner reads the admin's overrides when it | 255 | /// `GET` and `PUT /api/v1/ci/runners/config`. The runner reads the admin's overrides when it |
| 230 | /// starts, applies them to its in-memory config, then reports its effective config here. | 256 | /// starts, applies them to its in-memory config, then reports its effective config here. |
| 231 | #[route(GET "/api/v1/ci/runners/config")] | 257 | #[route(GET "/api/v1/ci/runners/config")] |
| @@ -285,6 +311,11 @@ async fn claim_work(state: &AppState, runner: &CiRunner) -> topcoat::Result<Resp | |||
| 285 | let mut woken = std::pin::pin!(waker.notified()); | 311 | let mut woken = std::pin::pin!(waker.notified()); |
| 286 | woken.as_mut().enable(); | 312 | woken.as_mut().enable(); |
| 287 | 313 | ||
| 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 | + } | ||
| 288 | match try_claim(state, runner).await { | 319 | match try_claim(state, runner).await { |
| 289 | Ok(Some(assignment)) => return Ok(assignment_response(&assignment)), | 320 | Ok(Some(assignment)) => return Ok(assignment_response(&assignment)), |
| 290 | Ok(None) => {} | 321 | Ok(None) => {} |
| @@ -507,6 +538,7 @@ async fn heartbeat(cx: &Cx) -> topcoat::Result<Response> { | |||
| 507 | // The runner says its live concurrency, and the answer carries the admin's override. | 538 | // The runner says its live concurrency, and the answer carries the admin's override. |
| 508 | // A runner at its limit does not claim, so this is how it learns about a change. | 539 | // A runner at its limit does not claim, so this is how it learns about a change. |
| 509 | let mut concurrency = None; | 540 | let mut concurrency = None; |
| 541 | + let mut restart = None; | ||
| 510 | if let Some(runner_id) = job.runner_id.as_deref() { | 542 | if let Some(runner_id) = job.runner_id.as_deref() { |
| 511 | let said = headers(cx) | 543 | let said = headers(cx) |
| 512 | .get(CONCURRENCY_HEADER) | 544 | .get(CONCURRENCY_HEADER) |
| @@ -532,12 +564,14 @@ async fn heartbeat(cx: &Cx) -> topcoat::Result<Response> { | |||
| 532 | .await | 564 | .await |
| 533 | .ok() | 565 | .ok() |
| 534 | .flatten(); | 566 | .flatten(); |
| 567 | + restart = pending_restart(state, runner_id).await; | ||
| 535 | } | 568 | } |
| 536 | Ok(api::json( | 569 | Ok(api::json( |
| 537 | StatusCode::OK, | 570 | StatusCode::OK, |
| 538 | &serde_json::to_value(HeartbeatResponse { | 571 | &serde_json::to_value(HeartbeatResponse { |
| 539 | cancel, | 572 | cancel, |
| 540 | concurrency, | 573 | concurrency, |
| 574 | + restart, | ||
| 541 | }) | 575 | }) |
| 542 | .unwrap_or_default(), | 576 | .unwrap_or_default(), |
| 543 | )) | 577 | )) |
crates/forge-web/src/ci/api_tests.rsmodified+74 -0
| @@ -528,6 +528,80 @@ async fn claim_and_heartbeat_carry_the_concurrency_round_trip() { | |||
| 528 | assert!(beat.json().get("concurrency").is_none()); | 528 | assert!(beat.json().get("concurrency").is_none()); |
| 529 | } | 529 | } |
| 530 | 530 | ||
| 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 | + | ||
| 531 | #[tokio::test] | 605 | #[tokio::test] |
| 532 | async fn runner_config_report_and_overrides_round_trip() { | 606 | async fn runner_config_report_and_overrides_round_trip() { |
| 533 | let env = bare(|_| {}).await; | 607 | let env = bare(|_| {}).await; |
crates/forge-web/src/pages/admin_runners.rsmodified+237 -2
| @@ -8,7 +8,7 @@ | |||
| 8 | 8 | ||
| 9 | use forge_ci::build::{self, Freshness}; | 9 | use forge_ci::build::{self, Freshness}; |
| 10 | use forge_core::AuditAction; | 10 | 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}; |
| 12 | use serde::Deserialize; | 12 | use serde::Deserialize; |
| 13 | use time::OffsetDateTime; | 13 | use time::OffsetDateTime; |
| 14 | use time::format_description::well_known::Rfc3339; | 14 | use time::format_description::well_known::Rfc3339; |
| @@ -42,7 +42,7 @@ fn s(lang: Lang, en: &'static str, tr: &'static str) -> &'static str { | |||
| 42 | } | 42 | } |
| 43 | 43 | ||
| 44 | /// Extra notice words: (word, English, Turkish, is an error). | 44 | /// 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] = [ |
| 46 | ( | 46 | ( |
| 47 | "saved", | 47 | "saved", |
| 48 | "Saved. The runner picks it up on its next check-in.", | 48 | "Saved. The runner picks it up on its next check-in.", |
| @@ -67,6 +67,18 @@ const EXTRA_NOTICES: [(&str, &str, &str, bool); 6] = [ | |||
| 67 | "Hiçbir şey değişmedi.", | 67 | "Hiçbir şey değişmedi.", |
| 68 | false, | 68 | false, |
| 69 | ), | 69 | ), |
| 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 | + ), | ||
| 70 | ( | 82 | ( |
| 71 | "invalid", | 83 | "invalid", |
| 72 | "That value is not valid for this field. Nothing was changed.", | 84 | "That value is not valid for this field. Nothing was changed.", |
| @@ -136,6 +148,11 @@ struct RunnerRow { | |||
| 136 | delete_action: String, | 148 | delete_action: String, |
| 137 | detail_href: String, | 149 | detail_href: String, |
| 138 | config_action: String, | 150 | 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>, | ||
| 139 | /// The concurrency shown in the input: the admin's override, else what the runner reports. | 156 | /// The concurrency shown in the input: the admin's override, else what the runner reports. |
| 140 | concurrency: String, | 157 | concurrency: String, |
| 141 | /// "UI", "runner.toml" or empty when the runner has not reported. | 158 | /// "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 { | |||
| 206 | delete_action: format!("/admin/runners/{}/delete", enc(&runner.id)), | 223 | delete_action: format!("/admin/runners/{}/delete", enc(&runner.id)), |
| 207 | detail_href: format!("/admin/runners/{}", enc(&runner.id)), | 224 | detail_href: format!("/admin/runners/{}", enc(&runner.id)), |
| 208 | config_action: format!("/admin/runners/{}/config", enc(&runner.id)), | 225 | 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), | ||
| 209 | concurrency, | 229 | concurrency, |
| 210 | concurrency_source, | 230 | concurrency_source, |
| 211 | has_override: runner.concurrency_override.is_some(), | 231 | has_override: runner.concurrency_override.is_some(), |
| @@ -316,6 +336,9 @@ async fn runners_view( | |||
| 316 | } else { | 336 | } else { |
| 317 | <span class="ci-state ci-success">(g::t(lang, K::Enabled))</span> | 337 | <span class="ci-state ci-success">(g::t(lang, K::Enabled))</span> |
| 318 | } | 338 | } |
| 339 | + if row.restart_pending.is_some() { | ||
| 340 | + <span class="ci-state runner-disabled">(s(lang, "restart pending", "yeniden başlatma bekliyor"))</span> | ||
| 341 | + } | ||
| 319 | </td> | 342 | </td> |
| 320 | <td class="runner-actions"> | 343 | <td class="runner-actions"> |
| 321 | <div class="runner-action-row"> | 344 | <div class="runner-action-row"> |
| @@ -324,6 +347,7 @@ async fn runners_view( | |||
| 324 | <input type="hidden" name="disabled" value=(if row.disabled { "0" } else { "1" })> | 347 | <input type="hidden" name="disabled" value=(if row.disabled { "0" } else { "1" })> |
| 325 | <button type="submit">(if row.disabled { g::t(lang, K::Enable) } else { g::t(lang, K::Disable) })</button> | 348 | <button type="submit">(if row.disabled { g::t(lang, K::Enable) } else { g::t(lang, K::Disable) })</button> |
| 326 | </form> | 349 | </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) | ||
| 327 | <form method="post" action=(row.delete_action.as_str()) class="inline-form"> | 351 | <form method="post" action=(row.delete_action.as_str()) class="inline-form"> |
| 328 | <input type="hidden" name="csrf" value=(csrf.as_str())> | 352 | <input type="hidden" name="csrf" value=(csrf.as_str())> |
| 329 | <button type="submit" class="danger">(i18n::t(lang, Key::Delete))</button> | 353 | <button type="submit" class="danger">(i18n::t(lang, Key::Delete))</button> |
| @@ -349,6 +373,42 @@ async fn runners_view( | |||
| 349 | }) | 373 | }) |
| 350 | } | 374 | } |
| 351 | 375 | ||
| 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 | + | ||
| 352 | /// The inline number form for concurrency: input, Save, and a reset button while an override is set. | 412 | /// The inline number form for concurrency: input, Save, and a reset button while an override is set. |
| 353 | #[component] | 413 | #[component] |
| 354 | async fn concurrency_form( | 414 | async fn concurrency_form( |
| @@ -947,8 +1007,12 @@ async fn runner_detail_view( | |||
| 947 | } else { | 1007 | } else { |
| 948 | <span class="ci-state ci-success">(g::t(lang, K::Enabled))</span> | 1008 | <span class="ci-state ci-success">(g::t(lang, K::Enabled))</span> |
| 949 | } | 1009 | } |
| 1010 | + if row.restart_pending.is_some() { | ||
| 1011 | + <span class="ci-state runner-disabled">(s(lang, "restart pending", "yeniden başlatma bekliyor"))</span> | ||
| 1012 | + } | ||
| 950 | </div> | 1013 | </div> |
| 951 | <div class="runner-head-actions"> | 1014 | <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) | ||
| 952 | <a href="/admin/runners">(g::t(lang, K::BackToRunners))</a> | 1016 | <a href="/admin/runners">(g::t(lang, K::BackToRunners))</a> |
| 953 | </div> | 1017 | </div> |
| 954 | </section> | 1018 | </section> |
| @@ -1229,6 +1293,69 @@ async fn runner_set_config(cx: &Cx, Form(form): Form<ConfigForm>) -> Result<SeeO | |||
| 1229 | })) | 1293 | })) |
| 1230 | } | 1294 | } |
| 1231 | 1295 | ||
| 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 | + | ||
| 1232 | #[cfg(test)] | 1359 | #[cfg(test)] |
| 1233 | mod tests { | 1360 | mod tests { |
| 1234 | use super::*; | 1361 | use super::*; |
| @@ -1438,6 +1565,114 @@ mod tests { | |||
| 1438 | assert!(page.contains(r#"<span class="ci-state runner-disabled">disabled</span>"#)); | 1565 | assert!(page.contains(r#"<span class="ci-state runner-disabled">disabled</span>"#)); |
| 1439 | } | 1566 | } |
| 1440 | 1567 | ||
| 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 | + | ||
| 1441 | #[tokio::test] | 1676 | #[tokio::test] |
| 1442 | async fn disable_enable_and_delete_a_runner() { | 1677 | async fn disable_enable_and_delete_a_runner() { |
| 1443 | let dir = tempfile::tempdir().expect("tempdir"); | 1678 | let dir = tempfile::tempdir().expect("tempdir"); |