forge
Explore
Log in

Don't you dare go Hollow

forge

Clone
★ 0

0 watching0 forksRustAGPL-3.09.3 MiBbcaef90Tahinli1 month ago164 commits

self_update.rs635 lines, 21.5 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 let artifact = state
229 .store
230 .artifact(&job.id, &cfg.artifact)
231 .await
232 .map_err(|e| e.to_string())?;
233 let Some(artifact) = artifact else {
234 tracing::info!(run_id = %run.id, artifact = %cfg.artifact, "self-update: no such artifact, skipping");
235 return Ok(());
236 };
237 let read = state
238 .blobs
239 .read(&crate::ci::artifact_key(&artifact.id))
240 .await
241 .map_err(|e| e.to_string())?
242 .ok_or("the artifact bytes are missing")?;
243
244 // Stage next to the executable, so the final rename stays on one filesystem.
245 let staged = sibling(&running.path, "new");
246 let sha = match write_staged(read.stream, &staged).await {
247 Ok(sha) => sha,
248 Err(e) => {
249 let _ = std::fs::remove_file(&staged);
250 return Err(e);
251 }
252 };
253 if !sha.eq_ignore_ascii_case(&artifact.sha256) {
254 let _ = std::fs::remove_file(&staged);
255 return Err(format!(
256 "artifact sha256 {sha} does not match the recorded {}",
257 artifact.sha256
258 ));
259 }
260 let bad = std::fs::read_to_string(sibling(&running.path, "bad")).unwrap_or_default();
261 if let Some(reason) = skip_reason(&sha, &running.sha256, &bad) {
262 let _ = std::fs::remove_file(&staged);
263 tracing::info!(sha256 = %sha, reason, "self-update: skipped");
264 return Ok(());
265 }
266 if let Err(e) = sanity_check(&staged).await {
267 let _ = std::fs::remove_file(&staged);
268 return Err(e);
269 }
270 if let Err(e) = swap(&running.path, &staged) {
271 let _ = std::fs::remove_file(&staged);
272 return Err(e);
273 }
274 tracing::info!(
275 old_sha256 = %running.sha256,
276 new_sha256 = %sha,
277 exe = %running.path.display(),
278 "self-update: binary replaced, restarting"
279 );
280 crate::alerts::self_update_deployed(state, &sha.chars().take(12).collect::<String>()).await;
281 RESTART_REQUESTED.store(true, Ordering::SeqCst);
282 RESTART.notify_one();
283 Ok(())
284}
285
286/// Streams the artifact to `path`, hashing as it goes. The file is executable and synced before
287/// this returns. Returns the sha256 in lowercase hex.
288async fn write_staged(
289 mut stream: BoxStream<'static, std::io::Result<bytes::Bytes>>,
290 path: &Path,
291) -> Result<String, String> {
292 use std::os::unix::fs::PermissionsExt;
293
294 let mut file = tokio::fs::File::create(path)
295 .await
296 .map_err(|e| format!("cannot create {}: {e}", path.display()))?;
297 let mut hasher = Sha256::new();
298 while let Some(chunk) = stream.next().await {
299 let chunk = chunk.map_err(|e| e.to_string())?;
300 hasher.update(&chunk);
301 file.write_all(&chunk).await.map_err(|e| e.to_string())?;
302 }
303 file.flush().await.map_err(|e| e.to_string())?;
304 file.sync_all().await.map_err(|e| e.to_string())?;
305 drop(file);
306 std::fs::set_permissions(path, std::fs::Permissions::from_mode(0o755))
307 .map_err(|e| e.to_string())?;
308 Ok(hex::encode(hasher.finalize()))
309}
310
311/// Runs `<staged> --version` with a timeout. Only exit 0 passes.
312async fn sanity_check(path: &Path) -> Result<(), String> {
313 use std::process::Stdio;
314
315 let mut child = tokio::process::Command::new(path)
316 .arg("--version")
317 .stdin(Stdio::null())
318 .stdout(Stdio::null())
319 .stderr(Stdio::null())
320 .kill_on_drop(true)
321 .spawn()
322 .map_err(|e| format!("the new binary does not run: {e}"))?;
323 match tokio::time::timeout(SANITY_TIMEOUT, child.wait()).await {
324 Ok(Ok(status)) if status.success() => Ok(()),
325 Ok(Ok(status)) => Err(format!("the new binary exited with {status} for --version")),
326 Ok(Err(e)) => Err(format!("waiting for the new binary failed: {e}")),
327 Err(_) => Err("the new binary did not answer --version within 10 seconds".into()),
328 }
329}
330
331/// Keeps the current binary as `<exe>.prev` (a hard link when possible), then renames `staged`
332/// over `exe`.
333fn swap(exe: &Path, staged: &Path) -> Result<(), String> {
334 let prev = sibling(exe, "prev");
335 if prev.exists() {
336 std::fs::remove_file(&prev).map_err(|e| format!("cannot remove the old prev: {e}"))?;
337 }
338 if std::fs::hard_link(exe, &prev).is_err() {
339 std::fs::copy(exe, &prev).map_err(|e| format!("cannot keep the previous binary: {e}"))?;
340 }
341 std::fs::rename(staged, exe).map_err(|e| format!("cannot replace the binary: {e}"))
342}
343
344/// Whether a claim response should advertise the binary: self-update is on and the runner asked
345/// for this target. Adds `Forge-Binary-Sha256` to a 200 or 204 response.
346pub fn advertise(state: &AppState, request: &HeaderMap, res: &mut Response) {
347 if !state.config.self_update.enabled {
348 return;
349 }
350 if !matches!(res.status(), StatusCode::OK | StatusCode::NO_CONTENT) {
351 return;
352 }
353 let requested = request.get(TARGET_HEADER).and_then(|v| v.to_str().ok());
354 if !target_matches(requested) {
355 return;
356 }
357 let Some(running) = running() else {
358 return;
359 };
360 if let Ok(value) = HeaderValue::from_str(&running.sha256) {
361 res.headers_mut().insert(SHA_HEADER, value);
362 }
363}
364
365/// The running binary as a streamed response, with its sha256. The caller checks auth and that
366/// self-update is enabled. `Err` when the binary cannot be read.
367pub async fn binary_response() -> Result<Response, String> {
368 let running = running().ok_or("the running binary was not hashed at startup")?;
369 let file = tokio::fs::File::open(image_path())
370 .await
371 .map_err(|e| e.to_string())?;
372 let len = file.metadata().await.map_err(|e| e.to_string())?.len();
373 // 64 KiB frames, not ReaderStream's 4 KiB default: the binary is ~1 GB, and 4 KiB frames mean
374 // ~250k body frames to push through hyper for every download.
375 let frames =
376 ReaderStream::with_capacity(file, 64 * 1024).map(|chunk| chunk.map(http_body::Frame::data));
377 let mut res = Response::new(Body::new(StreamBody::new(frames)));
378 let headers = res.headers_mut();
379 headers.insert(
380 CONTENT_TYPE,
381 HeaderValue::from_static("application/octet-stream"),
382 );
383 headers.insert(CONTENT_LENGTH, HeaderValue::from(len));
384 if let Ok(value) = HeaderValue::from_str(&running.sha256) {
385 headers.insert(SHA_HEADER, value);
386 }
387 Ok(res)
388}
389
390fn sha256_reader(mut reader: impl std::io::Read) -> std::io::Result<String> {
391 let mut hasher = Sha256::new();
392 let mut buf = vec![0u8; 64 * 1024];
393 loop {
394 let n = reader.read(&mut buf)?;
395 if n == 0 {
396 break;
397 }
398 hasher.update(&buf[..n]);
399 }
400 Ok(hex::encode(hasher.finalize()))
401}
402
403#[cfg(test)]
404mod tests {
405 use super::*;
406 use forge_core::ci::CiRun;
407
408 fn cfg() -> SelfUpdateConfig {
409 SelfUpdateConfig {
410 enabled: true,
411 repo: "Tahinli/forge".into(),
412 branch: "main".into(),
413 job: "build".into(),
414 artifact: "dist_forge".into(),
415 }
416 }
417
418 fn run(trigger: &str, git_ref: &str, state: RunState, pull_number: Option<i64>) -> CiRun {
419 CiRun {
420 id: "run-7".into(),
421 repo_id: "repo-1".into(),
422 number: 7,
423 trigger: trigger.into(),
424 git_ref: git_ref.into(),
425 commit_oid: "a".repeat(40),
426 pull_number,
427 actor_id: "user-1".into(),
428 state,
429 config_error: None,
430 created_at: "now".into(),
431 finished_at: None,
432 }
433 }
434
435 /// A push run of the deploy branch that is still the newest run.
436 fn good() -> CiRun {
437 run("push", "refs/heads/main", RunState::Success, None)
438 }
439
440 #[test]
441 fn only_the_newest_successful_push_to_the_deploy_branch_deploys() {
442 let on = cfg();
443 let mut off = cfg();
444 off.enabled = false;
445 let failed = |state| run("push", "refs/heads/main", state, None);
446 // (case, config, repo, run, latest run id, want deploy)
447 let cases = vec![
448 (
449 "good push",
450 &on,
451 "Tahinli/forge",
452 good(),
453 Some("run-7"),
454 true,
455 ),
456 (
457 "repo name case",
458 &on,
459 "tahinli/FORGE",
460 good(),
461 Some("run-7"),
462 true,
463 ),
464 (
465 "other repo",
466 &on,
467 "Tahinli/other",
468 good(),
469 Some("run-7"),
470 false,
471 ),
472 (
473 "disabled",
474 &off,
475 "Tahinli/forge",
476 good(),
477 Some("run-7"),
478 false,
479 ),
480 (
481 "older run",
482 &on,
483 "Tahinli/forge",
484 good(),
485 Some("run-9"),
486 false,
487 ),
488 ("no latest run", &on, "Tahinli/forge", good(), None, false),
489 (
490 "pull request run",
491 &on,
492 "Tahinli/forge",
493 run(
494 "pull_request",
495 "refs/pull/3/head",
496 RunState::Success,
497 Some(3),
498 ),
499 Some("run-7"),
500 false,
501 ),
502 // Even if a PR run were stored on the branch ref, the trigger and pull number exclude it.
503 (
504 "pull request on branch ref",
505 &on,
506 "Tahinli/forge",
507 run(
508 "pull_request",
509 "refs/heads/main",
510 RunState::Success,
511 Some(3),
512 ),
513 Some("run-7"),
514 false,
515 ),
516 (
517 "push with a pull number",
518 &on,
519 "Tahinli/forge",
520 run("push", "refs/heads/main", RunState::Success, Some(3)),
521 Some("run-7"),
522 false,
523 ),
524 (
525 "feature branch",
526 &on,
527 "Tahinli/forge",
528 run("push", "refs/heads/feature", RunState::Success, None),
529 Some("run-7"),
530 false,
531 ),
532 (
533 "tag",
534 &on,
535 "Tahinli/forge",
536 run("tag", "refs/tags/v1", RunState::Success, None),
537 Some("run-7"),
538 false,
539 ),
540 (
541 "manual",
542 &on,
543 "Tahinli/forge",
544 run("manual", "refs/heads/main", RunState::Success, None),
545 Some("run-7"),
546 false,
547 ),
548 (
549 "failure",
550 &on,
551 "Tahinli/forge",
552 failed(RunState::Failure),
553 Some("run-7"),
554 false,
555 ),
556 (
557 "cancelled",
558 &on,
559 "Tahinli/forge",
560 failed(RunState::Cancelled),
561 Some("run-7"),
562 false,
563 ),
564 (
565 "error",
566 &on,
567 "Tahinli/forge",
568 failed(RunState::Error),
569 Some("run-7"),
570 false,
571 ),
572 (
573 "running",
574 &on,
575 "Tahinli/forge",
576 failed(RunState::Running),
577 Some("run-7"),
578 false,
579 ),
580 ];
581 for (case, config, repo, run, latest, want) in cases {
582 assert_eq!(
583 should_deploy(config, repo, &run, latest),
584 want,
585 "case {case}"
586 );
587 }
588 }
589
590 #[test]
591 fn same_sha_as_running_is_skipped() {
592 let sha = "ab12";
593 assert_eq!(
594 skip_reason(sha, sha, ""),
595 Some("same as the running binary")
596 );
597 assert_eq!(
598 skip_reason("AB12", sha, ""),
599 Some("same as the running binary")
600 );
601 assert_eq!(skip_reason("cd34", sha, ""), None);
602 }
603
604 #[test]
605 fn bad_list_entries_are_skipped() {
606 let bad = "# rolled back 2026-10-01\n1111\n 2222 \n\n";
607 assert_eq!(
608 skip_reason("2222", "ffff", bad),
609 Some("listed in the bad list")
610 );
611 assert_eq!(
612 skip_reason("1111", "ffff", bad),
613 Some("listed in the bad list")
614 );
615 // A comment line is not a sha.
616 assert_eq!(skip_reason("rolled", "ffff", bad), None);
617 assert_eq!(skip_reason("3333", "ffff", bad), None);
618 }
619
620 #[test]
621 fn target_must_match_this_build() {
622 assert!(target_matches(Some(&target())));
623 assert!(!target_matches(None));
624 assert!(!target_matches(Some("riscv64-plan9")));
625 }
626
627 #[test]
628 fn sha256_of_known_bytes() {
629 let digest = sha256_reader(&b"abc"[..]).unwrap();
630 assert_eq!(
631 digest,
632 "ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad"
633 );
634 }
635}