forge
Explore
Log in

Don't you dare go Hollow

forge

Clone
★ 0

0 watching0 forksRustAGPL-3.07.1 MiB490f099Tahinli7 hours ago322 commits

self_update.rs641 lines, 21.8 KiBHistoryRawDownload
1//! Self-update: a green CI run of the forge's own repo replaces the running binary and restarts.
2//!
3//! Event-driven. `maybe_deploy` runs from the runner finish path when a job finishes. Nothing
4//! polls. After the swap the process exits with `RESTART_EXIT_CODE`, and the systemd unit
5//! (`Restart=on-failure`) starts the new binary.
6//!
7//! Runners update the same way. The claim route advertises the running binary's sha256 to a runner
8//! of the same target, and `GET /api/v1/ci/runners/binary` serves the bytes.
9
10use std::path::{Path, PathBuf};
11use std::sync::OnceLock;
12use std::sync::atomic::{AtomicBool, Ordering};
13use std::time::Duration;
14
15use forge_core::ci::{CiRun, RunState};
16use forge_core::config::SelfUpdateConfig;
17use futures_util::StreamExt;
18use futures_util::stream::BoxStream;
19use http::header::{CONTENT_LENGTH, CONTENT_TYPE, HeaderValue};
20use http_body_util::StreamBody;
21use sha2::{Digest, Sha256};
22use tokio::io::AsyncWriteExt;
23use tokio_util::io::ReaderStream;
24use topcoat::router::{Body, HeaderMap, StatusCode, response::Response};
25
26use crate::state::AppState;
27
28/// Exit code after a swap. systemd `Restart=on-failure` restarts the unit on any non-zero exit.
29pub const RESTART_EXIT_CODE: u8 = 75;
30/// Response header carrying the sha256 of the running binary, lowercase hex.
31pub const SHA_HEADER: &str = "Forge-Binary-Sha256";
32/// Request header a runner sends with its `<arch>-<os>` target.
33pub const TARGET_HEADER: &str = "Forge-Runner-Target";
34/// How long the staged binary may take to answer `--version`.
35const SANITY_TIMEOUT: Duration = Duration::from_secs(10);
36
37/// Serialises deploys. A deploy that finds another one running is skipped.
38static DEPLOY_LOCK: tokio::sync::Mutex<()> = tokio::sync::Mutex::const_new(());
39/// Wakes the server so it stops after a swap.
40static RESTART: tokio::sync::Notify = tokio::sync::Notify::const_new();
41static RESTART_REQUESTED: AtomicBool = AtomicBool::new(false);
42
43/// The running binary, hashed once at startup.
44pub struct Running {
45 /// The executable path, used to place the sibling `.prev`, `.bad` and staging files.
46 pub path: PathBuf,
47 pub sha256: String,
48}
49
50static RUNNING: OnceLock<Option<Running>> = OnceLock::new();
51
52/// The running binary, hashed on first use. `None` if it cannot be read, which disables
53/// advertising and serving, and deploys.
54pub fn running() -> Option<&'static Running> {
55 RUNNING
56 .get_or_init(|| match load_running() {
57 Ok(running) => {
58 tracing::info!(sha256 = %running.sha256, "self-update: running binary hashed");
59 Some(running)
60 }
61 Err(e) => {
62 tracing::error!(error = %e, "self-update: cannot hash the running binary");
63 None
64 }
65 })
66 .as_ref()
67}
68
69fn load_running() -> std::io::Result<Running> {
70 let path = std::env::current_exe()?;
71 let sha256 = sha256_reader(std::fs::File::open(image_path())?)?;
72 Ok(Running { path, sha256 })
73}
74
75/// The file that holds the running image. On Linux that is `/proc/self/exe`, which still names the
76/// old inode after a rename over the executable. Elsewhere it is the executable path.
77fn image_path() -> PathBuf {
78 let proc_exe = PathBuf::from("/proc/self/exe");
79 if proc_exe.exists() {
80 proc_exe
81 } else {
82 std::env::current_exe().unwrap_or(proc_exe)
83 }
84}
85
86/// Resolves once a swap has asked the server to stop.
87pub async fn restart_requested() {
88 RESTART.notified().await;
89}
90
91/// Asks the server to stop gracefully and exit with `RESTART_EXIT_CODE`, so the supervisor starts
92/// the binary again. The same path a self-update swap takes, without a swap. Used by the admin
93/// "Restart server" button.
94pub fn request_restart() {
95 RESTART_REQUESTED.store(true, Ordering::SeqCst);
96 RESTART.notify_one();
97}
98
99/// An id that is new for every process start. A page that sees it change knows the server
100/// restarted.
101pub fn boot_id() -> &'static str {
102 static ID: OnceLock<String> = OnceLock::new();
103 ID.get_or_init(|| {
104 let nanos = std::time::SystemTime::now()
105 .duration_since(std::time::UNIX_EPOCH)
106 .map_or(0, |d| d.as_nanos());
107 format!("{:x}{nanos:x}", std::process::id())
108 })
109}
110
111/// Whether a swap asked the process to exit with `RESTART_EXIT_CODE`.
112pub fn restart_pending() -> bool {
113 RESTART_REQUESTED.load(Ordering::SeqCst)
114}
115
116/// `<arch>-<os>` for this build, as a runner reports it in `Forge-Runner-Target`.
117pub fn target() -> String {
118 format!("{}-{}", std::env::consts::ARCH, std::env::consts::OS)
119}
120
121/// Whether a runner's requested target is this build's target.
122fn target_matches(requested: Option<&str>) -> bool {
123 requested == Some(target().as_str())
124}
125
126/// Whether a finished run should deploy. Pure, so the rules can be tested. A run deploys only when
127/// it is a successful push to the configured branch of the configured repo, and it is still the
128/// newest run on that branch. Pull request runs (including fork runs) never deploy.
129pub fn should_deploy(
130 cfg: &SelfUpdateConfig,
131 repo_full_name: &str,
132 run: &CiRun,
133 newest_on_ref: Option<&str>,
134) -> bool {
135 cfg.enabled
136 && matches!(run.state, RunState::Success)
137 && run.trigger == "push"
138 && run.pull_number.is_none()
139 && repo_full_name.eq_ignore_ascii_case(&cfg.repo)
140 && run.git_ref == format!("refs/heads/{}", cfg.branch)
141 && newest_on_ref == Some(run.id.as_str())
142}
143
144/// Why a candidate binary must not be installed, or `None` to install it. `bad_list` is the text
145/// of `<exe>.bad`: one hex sha256 per line, `#` starts a comment.
146pub fn skip_reason(candidate_sha: &str, running_sha: &str, bad_list: &str) -> Option<&'static str> {
147 if candidate_sha.eq_ignore_ascii_case(running_sha) {
148 return Some("same as the running binary");
149 }
150 let listed = bad_list
151 .lines()
152 .map(str::trim)
153 .filter(|line| !line.is_empty() && !line.starts_with('#'))
154 .any(|line| line.eq_ignore_ascii_case(candidate_sha));
155 listed.then_some("listed in the bad list")
156}
157
158/// `<name>.<suffix>` next to `exe`, for example `forge.prev`.
159fn sibling(exe: &Path, suffix: &str) -> PathBuf {
160 let name = exe
161 .file_name()
162 .map(|name| name.to_string_lossy().into_owned())
163 .unwrap_or_default();
164 exe.with_file_name(format!("{name}.{suffix}"))
165}
166
167/// Called when a job finishes. Starts a deploy in the background when the run qualifies.
168pub async fn maybe_deploy(state: &AppState, run: &CiRun) {
169 let cfg = &state.config.self_update;
170 if !cfg.enabled || !matches!(run.state, RunState::Success) {
171 return;
172 }
173 let repo = match state.store.repo_by_id(&run.repo_id).await {
174 Ok(Some(repo)) => repo,
175 Ok(None) => return,
176 Err(e) => {
177 tracing::error!(error = %e, "self-update: loading the repo failed");
178 return;
179 }
180 };
181 let full_name = format!("{}/{}", repo.owner_name, repo.name);
182 let newest = match state
183 .store
184 .latest_run_on_ref(&run.repo_id, &run.git_ref)
185 .await
186 {
187 Ok(newest) => newest,
188 Err(e) => {
189 tracing::error!(error = %e, "self-update: loading the newest run failed");
190 return;
191 }
192 };
193 if !should_deploy(cfg, &full_name, run, newest.as_ref().map(|r| r.id.as_str())) {
194 return;
195 }
196 tracing::info!(run_id = %run.id, "self-update: green push run on the deploy branch");
197 let state = state.clone();
198 let run = run.clone();
199 tokio::spawn(async move { deploy(state, run).await });
200}
201
202/// Installs the run's artifact over the running binary and asks the server to restart. Logs and
203/// returns on any failure, leaving the running binary in place.
204pub async fn deploy(state: AppState, run: CiRun) {
205 let Ok(_guard) = DEPLOY_LOCK.try_lock() else {
206 tracing::info!(run_id = %run.id, "self-update: a deploy is already running, skipping");
207 return;
208 };
209 if let Err(e) = deploy_inner(&state, &run).await {
210 tracing::error!(run_id = %run.id, error = %e, "self-update: deploy failed");
211 crate::alerts::self_update_failed(&state, &run.id, &e).await;
212 }
213}
214
215async fn deploy_inner(state: &AppState, run: &CiRun) -> Result<(), String> {
216 let cfg = &state.config.self_update;
217 let running = running().ok_or("the running binary was not hashed at startup")?;
218
219 let jobs = state
220 .store
221 .jobs_for_run(&run.id)
222 .await
223 .map_err(|e| e.to_string())?;
224 let Some(job) = jobs.iter().find(|job| job.name == cfg.job) else {
225 tracing::info!(run_id = %run.id, job = %cfg.job, "self-update: no such job in the run, skipping");
226 return Ok(());
227 };
228 // "dist_forge" was the old default; CI no longer uploads it, so it means the arch-named binary.
229 let configured = match cfg.artifact.as_str() {
230 "dist_forge" => "forge-{target}",
231 other => other,
232 };
233 let artifact_name = configured.replace("{target}", &target());
234 let artifact = state
235 .store
236 .artifact(&job.id, &artifact_name)
237 .await
238 .map_err(|e| e.to_string())?;
239 let Some(artifact) = artifact else {
240 tracing::info!(run_id = %run.id, artifact = %artifact_name, "self-update: no such artifact, skipping");
241 return Ok(());
242 };
243 let read = state
244 .blobs
245 .read(&crate::ci::artifact_key(&artifact.id))
246 .await
247 .map_err(|e| e.to_string())?
248 .ok_or("the artifact bytes are missing")?;
249
250 // Stage next to the executable, so the final rename stays on one filesystem.
251 let staged = sibling(&running.path, "new");
252 let sha = match write_staged(read.stream, &staged).await {
253 Ok(sha) => sha,
254 Err(e) => {
255 let _ = std::fs::remove_file(&staged);
256 return Err(e);
257 }
258 };
259 if !sha.eq_ignore_ascii_case(&artifact.sha256) {
260 let _ = std::fs::remove_file(&staged);
261 return Err(format!(
262 "artifact sha256 {sha} does not match the recorded {}",
263 artifact.sha256
264 ));
265 }
266 let bad = std::fs::read_to_string(sibling(&running.path, "bad")).unwrap_or_default();
267 if let Some(reason) = skip_reason(&sha, &running.sha256, &bad) {
268 let _ = std::fs::remove_file(&staged);
269 tracing::info!(sha256 = %sha, reason, "self-update: skipped");
270 return Ok(());
271 }
272 if let Err(e) = sanity_check(&staged).await {
273 let _ = std::fs::remove_file(&staged);
274 return Err(e);
275 }
276 if let Err(e) = swap(&running.path, &staged) {
277 let _ = std::fs::remove_file(&staged);
278 return Err(e);
279 }
280 tracing::info!(
281 old_sha256 = %running.sha256,
282 new_sha256 = %sha,
283 exe = %running.path.display(),
284 "self-update: binary replaced, restarting"
285 );
286 crate::alerts::self_update_deployed(state, &sha.chars().take(12).collect::<String>()).await;
287 RESTART_REQUESTED.store(true, Ordering::SeqCst);
288 RESTART.notify_one();
289 Ok(())
290}
291
292/// Streams the artifact to `path`, hashing as it goes. The file is executable and synced before
293/// this returns. Returns the sha256 in lowercase hex.
294async fn write_staged(
295 mut stream: BoxStream<'static, std::io::Result<bytes::Bytes>>,
296 path: &Path,
297) -> Result<String, String> {
298 use std::os::unix::fs::PermissionsExt;
299
300 let mut file = tokio::fs::File::create(path)
301 .await
302 .map_err(|e| format!("cannot create {}: {e}", path.display()))?;
303 let mut hasher = Sha256::new();
304 while let Some(chunk) = stream.next().await {
305 let chunk = chunk.map_err(|e| e.to_string())?;
306 hasher.update(&chunk);
307 file.write_all(&chunk).await.map_err(|e| e.to_string())?;
308 }
309 file.flush().await.map_err(|e| e.to_string())?;
310 file.sync_all().await.map_err(|e| e.to_string())?;
311 drop(file);
312 std::fs::set_permissions(path, std::fs::Permissions::from_mode(0o755))
313 .map_err(|e| e.to_string())?;
314 Ok(hex::encode(hasher.finalize()))
315}
316
317/// Runs `<staged> --version` with a timeout. Only exit 0 passes.
318async fn sanity_check(path: &Path) -> Result<(), String> {
319 use std::process::Stdio;
320
321 let mut child = tokio::process::Command::new(path)
322 .arg("--version")
323 .stdin(Stdio::null())
324 .stdout(Stdio::null())
325 .stderr(Stdio::null())
326 .kill_on_drop(true)
327 .spawn()
328 .map_err(|e| format!("the new binary does not run: {e}"))?;
329 match tokio::time::timeout(SANITY_TIMEOUT, child.wait()).await {
330 Ok(Ok(status)) if status.success() => Ok(()),
331 Ok(Ok(status)) => Err(format!("the new binary exited with {status} for --version")),
332 Ok(Err(e)) => Err(format!("waiting for the new binary failed: {e}")),
333 Err(_) => Err("the new binary did not answer --version within 10 seconds".into()),
334 }
335}
336
337/// Keeps the current binary as `<exe>.prev` (a hard link when possible), then renames `staged`
338/// over `exe`.
339fn swap(exe: &Path, staged: &Path) -> Result<(), String> {
340 let prev = sibling(exe, "prev");
341 if prev.exists() {
342 std::fs::remove_file(&prev).map_err(|e| format!("cannot remove the old prev: {e}"))?;
343 }
344 if std::fs::hard_link(exe, &prev).is_err() {
345 std::fs::copy(exe, &prev).map_err(|e| format!("cannot keep the previous binary: {e}"))?;
346 }
347 std::fs::rename(staged, exe).map_err(|e| format!("cannot replace the binary: {e}"))
348}
349
350/// Whether a claim response should advertise the binary: self-update is on and the runner asked
351/// for this target. Adds `Forge-Binary-Sha256` to a 200 or 204 response.
352pub fn advertise(state: &AppState, request: &HeaderMap, res: &mut Response) {
353 if !state.config.self_update.enabled {
354 return;
355 }
356 if !matches!(res.status(), StatusCode::OK | StatusCode::NO_CONTENT) {
357 return;
358 }
359 let requested = request.get(TARGET_HEADER).and_then(|v| v.to_str().ok());
360 if !target_matches(requested) {
361 return;
362 }
363 let Some(running) = running() else {
364 return;
365 };
366 if let Ok(value) = HeaderValue::from_str(&running.sha256) {
367 res.headers_mut().insert(SHA_HEADER, value);
368 }
369}
370
371/// The running binary as a streamed response, with its sha256. The caller checks auth and that
372/// self-update is enabled. `Err` when the binary cannot be read.
373pub async fn binary_response() -> Result<Response, String> {
374 let running = running().ok_or("the running binary was not hashed at startup")?;
375 let file = tokio::fs::File::open(image_path())
376 .await
377 .map_err(|e| e.to_string())?;
378 let len = file.metadata().await.map_err(|e| e.to_string())?.len();
379 // 64 KiB frames, not ReaderStream's 4 KiB default: the binary is ~1 GB, and 4 KiB frames mean
380 // ~250k body frames to push through hyper for every download.
381 let frames =
382 ReaderStream::with_capacity(file, 64 * 1024).map(|chunk| chunk.map(http_body::Frame::data));
383 let mut res = Response::new(Body::new(StreamBody::new(frames)));
384 let headers = res.headers_mut();
385 headers.insert(
386 CONTENT_TYPE,
387 HeaderValue::from_static("application/octet-stream"),
388 );
389 headers.insert(CONTENT_LENGTH, HeaderValue::from(len));
390 if let Ok(value) = HeaderValue::from_str(&running.sha256) {
391 headers.insert(SHA_HEADER, value);
392 }
393 Ok(res)
394}
395
396fn sha256_reader(mut reader: impl std::io::Read) -> std::io::Result<String> {
397 let mut hasher = Sha256::new();
398 let mut buf = vec![0u8; 64 * 1024];
399 loop {
400 let n = reader.read(&mut buf)?;
401 if n == 0 {
402 break;
403 }
404 hasher.update(&buf[..n]);
405 }
406 Ok(hex::encode(hasher.finalize()))
407}
408
409#[cfg(test)]
410mod tests {
411 use super::*;
412 use forge_core::ci::CiRun;
413
414 fn cfg() -> SelfUpdateConfig {
415 SelfUpdateConfig {
416 enabled: true,
417 repo: "Tahinli/forge".into(),
418 branch: "main".into(),
419 job: "build".into(),
420 artifact: "forge-{target}".into(),
421 }
422 }
423
424 fn run(trigger: &str, git_ref: &str, state: RunState, pull_number: Option<i64>) -> CiRun {
425 CiRun {
426 id: "run-7".into(),
427 repo_id: "repo-1".into(),
428 number: 7,
429 trigger: trigger.into(),
430 git_ref: git_ref.into(),
431 commit_oid: "a".repeat(40),
432 pull_number,
433 actor_id: "user-1".into(),
434 state,
435 config_error: None,
436 created_at: "now".into(),
437 finished_at: None,
438 }
439 }
440
441 /// A push run of the deploy branch that is still the newest run.
442 fn good() -> CiRun {
443 run("push", "refs/heads/main", RunState::Success, None)
444 }
445
446 #[test]
447 fn only_the_newest_successful_push_to_the_deploy_branch_deploys() {
448 let on = cfg();
449 let mut off = cfg();
450 off.enabled = false;
451 let failed = |state| run("push", "refs/heads/main", state, None);
452 // (case, config, repo, run, latest run id, want deploy)
453 let cases = vec![
454 (
455 "good push",
456 &on,
457 "Tahinli/forge",
458 good(),
459 Some("run-7"),
460 true,
461 ),
462 (
463 "repo name case",
464 &on,
465 "tahinli/FORGE",
466 good(),
467 Some("run-7"),
468 true,
469 ),
470 (
471 "other repo",
472 &on,
473 "Tahinli/other",
474 good(),
475 Some("run-7"),
476 false,
477 ),
478 (
479 "disabled",
480 &off,
481 "Tahinli/forge",
482 good(),
483 Some("run-7"),
484 false,
485 ),
486 (
487 "older run",
488 &on,
489 "Tahinli/forge",
490 good(),
491 Some("run-9"),
492 false,
493 ),
494 ("no latest run", &on, "Tahinli/forge", good(), None, false),
495 (
496 "pull request run",
497 &on,
498 "Tahinli/forge",
499 run(
500 "pull_request",
501 "refs/pull/3/head",
502 RunState::Success,
503 Some(3),
504 ),
505 Some("run-7"),
506 false,
507 ),
508 // Even if a PR run were stored on the branch ref, the trigger and pull number exclude it.
509 (
510 "pull request on branch ref",
511 &on,
512 "Tahinli/forge",
513 run(
514 "pull_request",
515 "refs/heads/main",
516 RunState::Success,
517 Some(3),
518 ),
519 Some("run-7"),
520 false,
521 ),
522 (
523 "push with a pull number",
524 &on,
525 "Tahinli/forge",
526 run("push", "refs/heads/main", RunState::Success, Some(3)),
527 Some("run-7"),
528 false,
529 ),
530 (
531 "feature branch",
532 &on,
533 "Tahinli/forge",
534 run("push", "refs/heads/feature", RunState::Success, None),
535 Some("run-7"),
536 false,
537 ),
538 (
539 "tag",
540 &on,
541 "Tahinli/forge",
542 run("tag", "refs/tags/v1", RunState::Success, None),
543 Some("run-7"),
544 false,
545 ),
546 (
547 "manual",
548 &on,
549 "Tahinli/forge",
550 run("manual", "refs/heads/main", RunState::Success, None),
551 Some("run-7"),
552 false,
553 ),
554 (
555 "failure",
556 &on,
557 "Tahinli/forge",
558 failed(RunState::Failure),
559 Some("run-7"),
560 false,
561 ),
562 (
563 "cancelled",
564 &on,
565 "Tahinli/forge",
566 failed(RunState::Cancelled),
567 Some("run-7"),
568 false,
569 ),
570 (
571 "error",
572 &on,
573 "Tahinli/forge",
574 failed(RunState::Error),
575 Some("run-7"),
576 false,
577 ),
578 (
579 "running",
580 &on,
581 "Tahinli/forge",
582 failed(RunState::Running),
583 Some("run-7"),
584 false,
585 ),
586 ];
587 for (case, config, repo, run, latest, want) in cases {
588 assert_eq!(
589 should_deploy(config, repo, &run, latest),
590 want,
591 "case {case}"
592 );
593 }
594 }
595
596 #[test]
597 fn same_sha_as_running_is_skipped() {
598 let sha = "ab12";
599 assert_eq!(
600 skip_reason(sha, sha, ""),
601 Some("same as the running binary")
602 );
603 assert_eq!(
604 skip_reason("AB12", sha, ""),
605 Some("same as the running binary")
606 );
607 assert_eq!(skip_reason("cd34", sha, ""), None);
608 }
609
610 #[test]
611 fn bad_list_entries_are_skipped() {
612 let bad = "# rolled back 2026-10-01\n1111\n 2222 \n\n";
613 assert_eq!(
614 skip_reason("2222", "ffff", bad),
615 Some("listed in the bad list")
616 );
617 assert_eq!(
618 skip_reason("1111", "ffff", bad),
619 Some("listed in the bad list")
620 );
621 // A comment line is not a sha.
622 assert_eq!(skip_reason("rolled", "ffff", bad), None);
623 assert_eq!(skip_reason("3333", "ffff", bad), None);
624 }
625
626 #[test]
627 fn target_must_match_this_build() {
628 assert!(target_matches(Some(&target())));
629 assert!(!target_matches(None));
630 assert!(!target_matches(Some("riscv64-plan9")));
631 }
632
633 #[test]
634 fn sha256_of_known_bytes() {
635 let digest = sha256_reader(&b"abc"[..]).unwrap();
636 assert_eq!(
637 digest,
638 "ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad"
639 );
640 }
641}