Skip to main content

runner_manager_platform/
reboot.rs

1//! Restarting this machine, for `host reboot`.
2//!
3//! The daemon decides *when* (once every running job has finished); this
4//! module only knows *how*, on each system and for each account the service
5//! may run as, and tries the ways in order until one is accepted. Which
6//! commands are tried is a pure function ([`commands`]) so every system's
7//! choice is tested on every system, and the daemon takes a [`Rebooter`] so
8//! that no test ever restarts the machine running it.
9
10use std::process::{Command, Stdio};
11use std::time::{Duration, Instant};
12
13use runner_manager_domain::model::Os;
14
15/// How long one command may take to answer before the next is tried. A
16/// restart that was accepted answers at once; `osascript` can wait on a
17/// consent dialog nobody will see.
18const COMMAND_TIMEOUT: Duration = Duration::from_secs(60);
19
20/// The seconds Windows waits between accepting the restart and starting it.
21const WINDOWS_DELAY_SECS: u32 = 5;
22
23/// One way to ask the system for a restart.
24#[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    /// As a person would type it, for messages.
39    #[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/// The commands that restart `os`, in the order they are tried, for a
49/// service running as an administrator (`root`, LocalSystem) or not.
50///
51/// - **Windows**: `shutdown.exe /r`, which LocalSystem and an interactive
52///   user can both run; `/d p:4:1` records a planned restart for
53///   maintenance in the event log, `/c` says who asked.
54/// - **Linux**: as root, `systemctl reboot`, then `shutdown -r now`, then
55///   `reboot` for a system without systemd. As a user, the same through
56///   `sudo -n` (a password is never asked for), after `systemctl reboot`
57///   without a password prompt, which polkit allows some sessions.
58/// - **macOS**: as root, `shutdown -r now`. As a user (a login LaunchAgent),
59///   System Events' restart, which asks the open applications to quit, then
60///   `sudo -n shutdown -r now`.
61#[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/// The commands that call off a restart `commands` asked for and the system
98/// has not begun: `shutdown /a` within Windows' delay, `shutdown -c` for a
99/// scheduled Linux shutdown. macOS has none: an application that refuses
100/// to quit has already called its restart off.
101#[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
114/// `shutdown.exe` by its full path, so a `shutdown` earlier on `PATH` is not
115/// the one run.
116fn 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
121/// Asks the system to restart.
122pub trait Rebooter: Send + Sync {
123    /// Asks for the restart, and says which command the system accepted.
124    ///
125    /// # Errors
126    /// Why every way was refused, one line per command tried.
127    fn reboot(&self, reason: &str) -> Result<String, String>;
128
129    /// Calls off a restart the system accepted and has not begun, where the
130    /// system can. `true` only when a command said it did: otherwise the
131    /// restart may still come.
132    fn abort(&self) -> bool {
133        false
134    }
135}
136
137/// The real thing: runs [`commands`] for this machine until one is accepted.
138#[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
163/// Runs `command` and waits for it within [`COMMAND_TIMEOUT`]. Its output
164/// is kept only to say why it failed.
165fn 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        // `false`-like commands only: nothing here may restart anything.
293        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}