1use std::process::{Command, Stdio};
11use std::time::{Duration, Instant};
12
13use runner_manager_domain::model::Os;
14
15const COMMAND_TIMEOUT: Duration = Duration::from_secs(60);
19
20const WINDOWS_DELAY_SECS: u32 = 5;
22
23#[derive(Debug, Clone, PartialEq, Eq)]
25pub struct RebootCommand {
26 pub program: String,
27 pub args: Vec<String>,
28}
29
30impl RebootCommand {
31 fn new(program: &str, args: &[&str]) -> Self {
32 Self {
33 program: program.to_owned(),
34 args: args.iter().map(|arg| (*arg).to_owned()).collect(),
35 }
36 }
37
38 #[must_use]
40 pub fn display(&self) -> String {
41 std::iter::once(self.program.as_str())
42 .chain(self.args.iter().map(String::as_str))
43 .collect::<Vec<_>>()
44 .join(" ")
45 }
46}
47
48#[must_use]
62pub fn commands(os: Os, administrator: bool, reason: &str) -> Vec<RebootCommand> {
63 match os {
64 Os::Windows => {
65 let delay = WINDOWS_DELAY_SECS.to_string();
66 vec![RebootCommand {
67 program: windows_shutdown_exe(),
68 args: ["/r", "/t", &delay, "/d", "p:4:1", "/c", reason]
69 .iter()
70 .map(|arg| (*arg).to_owned())
71 .collect(),
72 }]
73 }
74 Os::Linux if administrator => vec![
75 RebootCommand::new("systemctl", &["reboot"]),
76 RebootCommand::new("shutdown", &["-r", "now", reason]),
77 RebootCommand::new("reboot", &[]),
78 ],
79 Os::Linux => vec![
80 RebootCommand::new("systemctl", &["--no-ask-password", "reboot"]),
81 RebootCommand::new("sudo", &["-n", "systemctl", "reboot"]),
82 RebootCommand::new("sudo", &["-n", "shutdown", "-r", "now", reason]),
83 ],
84 Os::MacOs if administrator => {
85 vec![RebootCommand::new("/sbin/shutdown", &["-r", "now"])]
86 }
87 Os::MacOs => vec![
88 RebootCommand::new(
89 "/usr/bin/osascript",
90 &["-e", "tell application \"System Events\" to restart"],
91 ),
92 RebootCommand::new("/usr/bin/sudo", &["-n", "/sbin/shutdown", "-r", "now"]),
93 ],
94 }
95}
96
97#[must_use]
102pub fn abort_commands(os: Os, administrator: bool) -> Vec<RebootCommand> {
103 match os {
104 Os::Windows => vec![RebootCommand {
105 program: windows_shutdown_exe(),
106 args: vec!["/a".to_owned()],
107 }],
108 Os::Linux if administrator => vec![RebootCommand::new("shutdown", &["-c"])],
109 Os::Linux => vec![RebootCommand::new("sudo", &["-n", "shutdown", "-c"])],
110 Os::MacOs => Vec::new(),
111 }
112}
113
114fn windows_shutdown_exe() -> String {
117 let root = std::env::var("SystemRoot").unwrap_or_else(|_| r"C:\Windows".to_owned());
118 format!(r"{root}\System32\shutdown.exe")
119}
120
121pub trait Rebooter: Send + Sync {
123 fn reboot(&self, reason: &str) -> Result<String, String>;
128
129 fn abort(&self) -> bool {
133 false
134 }
135}
136
137#[derive(Debug, Default, Clone, Copy)]
139pub struct SystemRebooter;
140
141impl Rebooter for SystemRebooter {
142 fn reboot(&self, reason: &str) -> Result<String, String> {
143 let os = crate::os::detect_os().ok_or("this system has no known way to restart")?;
144 let mut refused = Vec::new();
145 for command in commands(os, crate::host_fitness::is_elevated(), reason) {
146 match run(&command) {
147 Ok(()) => return Ok(command.display()),
148 Err(why) => refused.push(format!("`{}`: {why}", command.display())),
149 }
150 }
151 Err(refused.join("; "))
152 }
153
154 fn abort(&self) -> bool {
155 crate::os::detect_os().is_some_and(|os| {
156 abort_commands(os, crate::host_fitness::is_elevated())
157 .iter()
158 .any(|command| run(command).is_ok())
159 })
160 }
161}
162
163fn run(command: &RebootCommand) -> Result<(), String> {
166 let mut child = Command::new(&command.program)
167 .args(&command.args)
168 .stdin(Stdio::null())
169 .stdout(Stdio::null())
170 .stderr(Stdio::piped())
171 .spawn()
172 .map_err(|error| error.to_string())?;
173 let started = Instant::now();
174 loop {
175 if let Some(status) = child.try_wait().map_err(|error| error.to_string())? {
176 if status.success() {
177 return Ok(());
178 }
179 let mut stderr = String::new();
180 if let Some(mut pipe) = child.stderr.take() {
181 let _ = std::io::Read::read_to_string(&mut pipe, &mut stderr);
182 }
183 let stderr = stderr.split_whitespace().collect::<Vec<_>>().join(" ");
184 let mut why = format!("exited with {status}");
185 if !stderr.is_empty() {
186 why.push_str(": ");
187 why.push_str(&stderr[..stderr.floor_char_boundary(200)]);
188 }
189 return Err(why);
190 }
191 if started.elapsed() >= COMMAND_TIMEOUT {
192 let _ = child.kill();
193 let _ = child.wait();
194 return Err(format!(
195 "gave no answer within {} seconds",
196 COMMAND_TIMEOUT.as_secs()
197 ));
198 }
199 std::thread::sleep(Duration::from_millis(100));
200 }
201}
202
203#[cfg(test)]
204mod tests {
205 use super::*;
206
207 fn programs(os: Os, administrator: bool) -> Vec<String> {
208 commands(os, administrator, "why")
209 .into_iter()
210 .map(|command| command.display())
211 .collect()
212 }
213
214 #[test]
215 fn windows_restarts_with_shutdown_exe_and_says_why() {
216 for administrator in [true, false] {
217 let commands = commands(Os::Windows, administrator, "runner-manager: asked");
218 let [command] = commands.as_slice() else {
219 panic!("one command on Windows");
220 };
221 assert!(
222 command.program.ends_with(r"\System32\shutdown.exe"),
223 "{command:?}"
224 );
225 assert_eq!(
226 command.args,
227 [
228 "/r",
229 "/t",
230 "5",
231 "/d",
232 "p:4:1",
233 "/c",
234 "runner-manager: asked"
235 ]
236 );
237 }
238 }
239
240 #[test]
241 fn linux_root_reboots_directly_and_a_user_never_waits_for_a_password() {
242 assert_eq!(
243 programs(Os::Linux, true),
244 ["systemctl reboot", "shutdown -r now why", "reboot"]
245 );
246 let user = programs(Os::Linux, false);
247 assert_eq!(
248 user,
249 [
250 "systemctl --no-ask-password reboot",
251 "sudo -n systemctl reboot",
252 "sudo -n shutdown -r now why"
253 ]
254 );
255 assert!(
256 user.iter()
257 .filter(|command| command.starts_with("sudo"))
258 .all(|command| command.starts_with("sudo -n ")),
259 "sudo must never prompt"
260 );
261 }
262
263 #[test]
264 fn macos_root_shuts_down_and_a_login_agent_asks_system_events_first() {
265 assert_eq!(programs(Os::MacOs, true), ["/sbin/shutdown -r now"]);
266 assert_eq!(
267 programs(Os::MacOs, false),
268 [
269 "/usr/bin/osascript -e tell application \"System Events\" to restart",
270 "/usr/bin/sudo -n /sbin/shutdown -r now"
271 ]
272 );
273 }
274
275 #[test]
276 fn a_restart_that_did_not_begin_is_called_off_where_the_system_can() {
277 let aborts = |os, administrator| -> Vec<String> {
278 abort_commands(os, administrator)
279 .into_iter()
280 .map(|command| command.display())
281 .collect()
282 };
283 let [windows] = aborts(Os::Windows, true).try_into().unwrap();
284 assert!(windows.ends_with(r"\System32\shutdown.exe /a"), "{windows}");
285 assert_eq!(aborts(Os::Linux, true), ["shutdown -c"]);
286 assert_eq!(aborts(Os::Linux, false), ["sudo -n shutdown -c"]);
287 assert!(aborts(Os::MacOs, false).is_empty());
288 }
289
290 #[test]
291 fn a_failed_command_says_how_it_ended() {
292 let missing = RebootCommand::new("runner-manager-no-such-program", &[]);
294 assert!(run(&missing).is_err());
295 #[cfg(unix)]
296 {
297 let failing = RebootCommand::new("sh", &["-c", "echo refused >&2; exit 3"]);
298 let why = run(&failing).unwrap_err();
299 assert!(why.contains("refused"), "{why}");
300 }
301 }
302}