aboutsummaryrefslogtreecommitdiff
path: root/src/platform/linux/shutdown.rs
blob: b678161a03283769e46f445eac6967364f0047a0 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::Arc;
use std::time::Duration;

use futures_util::StreamExt;

pub(crate) fn monitor_host_shutdown(
    requested: Arc<AtomicBool>,
    wake: impl Fn() + Send + Sync + 'static,
) -> Option<tokio::task::JoinHandle<()>> {
    Some(tokio::spawn(async move {
        let mut retry = Duration::from_secs(1);
        loop {
            match watch_shutdown(&requested, &wake).await {
                Ok(()) => retry = Duration::from_secs(1),
                Err(err) => {
                    tracing::debug!(err = %err, retry_seconds = retry.as_secs(), "host shutdown notification unavailable");
                    tokio::time::sleep(retry).await;
                    retry = (retry * 2).min(Duration::from_secs(60));
                }
            }
        }
    }))
}

async fn watch_shutdown(
    requested: &AtomicBool,
    wake: &(impl Fn() + Send + Sync),
) -> zbus::Result<()> {
    let connection = zbus::Connection::system().await?;
    watch_connection(connection, requested, wake).await
}

async fn watch_connection(
    connection: zbus::Connection,
    requested: &AtomicBool,
    wake: &(impl Fn() + Send + Sync),
) -> zbus::Result<()> {
    let manager = zbus::Proxy::new(
        &connection,
        "org.freedesktop.login1",
        "/org/freedesktop/login1",
        "org.freedesktop.login1.Manager",
    )
    .await?;
    let mut owners = manager.receive_owner_changed().await?;
    let mut signals = manager.receive_signal("PrepareForShutdown").await?;
    let inhibitor: zbus::zvariant::OwnedFd = manager
        .call(
            "Inhibit",
            &(
                "shutdown",
                "Herdr",
                "Save terminal workspace layout",
                "delay",
            ),
        )
        .await?;
    tracing::debug!("host shutdown notification ready");

    let mut preparing: bool = manager.get_property("PreparingForShutdown").await?;
    loop {
        if preparing {
            tracing::info!("host shutdown requested; preserving session before pane termination");
            requested.store(true, Ordering::Release);
            wake();
            // Keep the delay lock until the server has saved and drops its monitor.
            // logind caps the delay even if the server gets stuck.
            std::future::pending::<()>().await;
        }
        tokio::select! {
            biased;
            _ = owners.next() => break,
            signal = signals.next() => {
                let Some(signal) = signal else { break };
                preparing = signal.body().deserialize()?;
            }
        }
    }
    drop(inhibitor);
    Ok(())
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::io::{BufRead, Read};
    use std::os::unix::net::UnixStream;
    use std::process::{Child, Command, Stdio};
    use std::sync::Mutex;

    struct PrivateBus(Child);

    impl Drop for PrivateBus {
        fn drop(&mut self) {
            let _ = self.0.kill();
            let _ = self.0.wait();
        }
    }

    struct LoginManager {
        preparing: bool,
        peer: Arc<Mutex<Option<UnixStream>>>,
    }

    #[zbus::interface(name = "org.freedesktop.login1.Manager")]
    impl LoginManager {
        fn inhibit(
            &self,
            what: &str,
            _who: &str,
            _why: &str,
            mode: &str,
        ) -> zbus::fdo::Result<zbus::zvariant::OwnedFd> {
            assert_eq!((what, mode), ("shutdown", "delay"));
            let (lock, peer) = UnixStream::pair().unwrap();
            peer.set_nonblocking(true).unwrap();
            *self.peer.lock().unwrap() = Some(peer);
            Ok(std::os::fd::OwnedFd::from(lock).into())
        }

        #[zbus(property)]
        fn preparing_for_shutdown(&self) -> bool {
            self.preparing
        }
    }

    #[tokio::test]
    #[ignore = "requires dbus-daemon; uses a private bus, never requests host shutdown"]
    async fn shutdown_warning_holds_inhibitor_until_monitor_is_dropped() {
        for already_preparing in [false, true] {
            let mut bus = PrivateBus(
                Command::new("dbus-daemon")
                    .args(["--session", "--nofork", "--print-address=1"])
                    .stdout(Stdio::piped())
                    .spawn()
                    .unwrap(),
            );
            let mut address = String::new();
            std::io::BufReader::new(bus.0.stdout.take().unwrap())
                .read_line(&mut address)
                .unwrap();
            let peer = Arc::new(Mutex::new(None));
            let service = zbus::connection::Builder::address(address.trim())
                .unwrap()
                .name("org.freedesktop.login1")
                .unwrap()
                .serve_at(
                    "/org/freedesktop/login1",
                    LoginManager {
                        preparing: already_preparing,
                        peer: peer.clone(),
                    },
                )
                .unwrap()
                .build()
                .await
                .unwrap();
            let client = zbus::connection::Builder::address(address.trim())
                .unwrap()
                .build()
                .await
                .unwrap();
            let requested = Arc::new(AtomicBool::new(false));
            let wake = Arc::new(tokio::sync::Notify::new());
            let task = tokio::spawn({
                let requested = requested.clone();
                let wake = wake.clone();
                async move {
                    watch_connection(client, &requested, &move || wake.notify_one())
                        .await
                        .unwrap();
                }
            });
            tokio::time::timeout(Duration::from_secs(5), async {
                while peer.lock().unwrap().is_none() {
                    tokio::task::yield_now().await;
                }
                if !already_preparing {
                    assert!(!requested.load(Ordering::Acquire));
                    service
                        .emit_signal(
                            None::<&str>,
                            "/org/freedesktop/login1",
                            "org.freedesktop.login1.Manager",
                            "PrepareForShutdown",
                            &true,
                        )
                        .await
                        .unwrap();
                }
                wake.notified().await;
            })
            .await
            .unwrap();
            assert!(requested.load(Ordering::Acquire));
            let mut peer = peer.lock().unwrap().take().unwrap();
            assert_eq!(
                peer.read(&mut [0]).unwrap_err().kind(),
                std::io::ErrorKind::WouldBlock,
                "shutdown must remain inhibited while the server saves"
            );
            task.abort();
            assert!(task.await.unwrap_err().is_cancelled());
            assert_eq!(peer.read(&mut [0]).unwrap(), 0);
        }
    }
}