forge
Explore
Log in

Don't you dare go Hollow

forge

Clone
★ 0

0 watching0 forksRustAGPL-3.07.1 MiB490f099Tahinli7 hours ago322 commits

restart.rs139 lines, 4.8 KiBHistoryRawDownload
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
7use std::sync::OnceLock;
8use std::sync::atomic::{AtomicBool, Ordering};
9use std::sync::{Mutex, PoisonError};
10
11use forge_ci::proto::RestartMode;
12use tokio::sync::Notify;
13
14/// A restart request seen from the forge, shared by the claim loop and the job heartbeats.
15#[derive(Default)]
16pub 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
23impl 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)]
60pub 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.
72pub 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.
82pub 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)]
93mod 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}