utils/spawn: Put processes into systemd scopes
Browse files at this commit6ba24e341fd1e0a8b387c705ce34cc3f19dcf375Parent: 13b6c742 changed files +139 -1
- src/main.rs +3 -1
- src/utils.rs +136 -0
src/main.rsmodified+3 -1
| @@ -16,7 +16,8 @@ use niri::dbus; | |||
| 16 | use niri::ipc::client::handle_msg; | 16 | use niri::ipc::client::handle_msg; |
| 17 | use niri::niri::State; | 17 | use niri::niri::State; |
| 18 | use niri::utils::{ | 18 | use niri::utils::{ |
| 19 | - cause_panic, spawn, version, REMOVE_ENV_RUST_BACKTRACE, REMOVE_ENV_RUST_LIB_BACKTRACE, | 19 | + cause_panic, spawn, version, IS_SYSTEMD_SERVICE, REMOVE_ENV_RUST_BACKTRACE, |
| 20 | + REMOVE_ENV_RUST_LIB_BACKTRACE, | ||
| 20 | }; | 21 | }; |
| 21 | use niri::watcher::Watcher; | 22 | use niri::watcher::Watcher; |
| 22 | use niri_config::Config; | 23 | use niri_config::Config; |
| @@ -38,6 +39,7 @@ fn main() -> Result<(), Box<dyn std::error::Error>> { | |||
| 38 | } | 39 | } |
| 39 | 40 | ||
| 40 | let is_systemd_service = env::var_os("NOTIFY_SOCKET").is_some(); | 41 | let is_systemd_service = env::var_os("NOTIFY_SOCKET").is_some(); |
| 42 | + IS_SYSTEMD_SERVICE.store(is_systemd_service, Ordering::Relaxed); | ||
| 41 | 43 | ||
| 42 | let directives = env::var("RUST_LOG").unwrap_or_else(|_| "niri=debug".to_owned()); | 44 | let directives = env::var("RUST_LOG").unwrap_or_else(|_| "niri=debug".to_owned()); |
| 43 | let env_filter = EnvFilter::builder().parse_lossy(directives); | 45 | let env_filter = EnvFilter::builder().parse_lossy(directives); |
src/utils.rsmodified+136 -0
| @@ -13,6 +13,7 @@ use std::time::Duration; | |||
| 13 | use anyhow::{ensure, Context}; | 13 | use anyhow::{ensure, Context}; |
| 14 | use directories::UserDirs; | 14 | use directories::UserDirs; |
| 15 | use git_version::git_version; | 15 | use git_version::git_version; |
| 16 | +use libc::close_range; | ||
| 16 | use niri_config::Config; | 17 | use niri_config::Config; |
| 17 | use smithay::output::Output; | 18 | use smithay::output::Output; |
| 18 | use smithay::reexports::rustix; | 19 | use smithay::reexports::rustix; |
| @@ -126,6 +127,22 @@ fn spawn_sync(command: impl AsRef<OsStr>, args: impl IntoIterator<Item = impl As | |||
| 126 | process.env_remove("RUST_LIB_BACKTRACE"); | 127 | process.env_remove("RUST_LIB_BACKTRACE"); |
| 127 | } | 128 | } |
| 128 | 129 | ||
| 130 | + // When running as a systemd session, we want to put children into their own transient scopes | ||
| 131 | + // in order to separate them from the niri process. This is helpful for example to prevent the | ||
| 132 | + // OOM killer from taking down niri together with a misbehaving client. | ||
| 133 | + // | ||
| 134 | + // Putting a child into a scope is done by calling systemd's StartTransientUnit D-Bus method | ||
| 135 | + // with a PID. Unfortunately, there seems to be a race in systemd where if the child exits at | ||
| 136 | + // just the right time, the transient unit will be created but empty, so it will linger around | ||
| 137 | + // forever. | ||
| 138 | + // | ||
| 139 | + // To prevent this, we'll use our double-fork (done for a separate reason) to help. In our | ||
| 140 | + // intermediate child we will send back the grandchild PID, and in niri we will create a | ||
| 141 | + // transient scope with both our intermediate child and the grandchild PIDs set. Only then we | ||
| 142 | + // will signal our intermediate child to exit. This way, even if the grandchild exits quickly, | ||
| 143 | + // a non-empty scope will be created (with just our intermediate child), then cleaned up when | ||
| 144 | + // our intermediate child exits. | ||
| 145 | + | ||
| 129 | // Make a pipe to receive the grandchild PID. | 146 | // Make a pipe to receive the grandchild PID. |
| 130 | let (pipe_pid_read, pipe_pid_write) = pipe_with(PipeFlags::CLOEXEC) | 147 | let (pipe_pid_read, pipe_pid_write) = pipe_with(PipeFlags::CLOEXEC) |
| 131 | .map_err(|err| { | 148 | .map_err(|err| { |
| @@ -133,21 +150,36 @@ fn spawn_sync(command: impl AsRef<OsStr>, args: impl IntoIterator<Item = impl As | |||
| 133 | }) | 150 | }) |
| 134 | .ok() | 151 | .ok() |
| 135 | .unzip(); | 152 | .unzip(); |
| 153 | + // Make a pipe to wait in the intermediate child. | ||
| 154 | + let (pipe_wait_read, pipe_wait_write) = pipe_with(PipeFlags::CLOEXEC) | ||
| 155 | + .map_err(|err| { | ||
| 156 | + warn!("error creating a pipe for child to wait on: {err:?}"); | ||
| 157 | + }) | ||
| 158 | + .ok() | ||
| 159 | + .unzip(); | ||
| 136 | 160 | ||
| 137 | unsafe { | 161 | unsafe { |
| 138 | // The fds will be duplicated after a fork and closed on exec or exit automatically. Get | 162 | // The fds will be duplicated after a fork and closed on exec or exit automatically. Get |
| 139 | // the raw fd inside so that it's not closed any extra times. | 163 | // the raw fd inside so that it's not closed any extra times. |
| 140 | let mut pipe_pid_read_fd = pipe_pid_read.as_ref().map(|fd| fd.as_raw_fd()); | 164 | let mut pipe_pid_read_fd = pipe_pid_read.as_ref().map(|fd| fd.as_raw_fd()); |
| 141 | let mut pipe_pid_write_fd = pipe_pid_write.as_ref().map(|fd| fd.as_raw_fd()); | 165 | let mut pipe_pid_write_fd = pipe_pid_write.as_ref().map(|fd| fd.as_raw_fd()); |
| 166 | + let mut pipe_wait_read_fd = pipe_wait_read.as_ref().map(|fd| fd.as_raw_fd()); | ||
| 167 | + let mut pipe_wait_write_fd = pipe_wait_write.as_ref().map(|fd| fd.as_raw_fd()); | ||
| 142 | 168 | ||
| 143 | // Double-fork to avoid having to waitpid the child. | 169 | // Double-fork to avoid having to waitpid the child. |
| 144 | process.pre_exec(move || { | 170 | process.pre_exec(move || { |
| 171 | + // Close FDs that we don't need. Especially important for the write ones to unblock the | ||
| 172 | + // readers. | ||
| 145 | if let Some(fd) = pipe_pid_read_fd.take() { | 173 | if let Some(fd) = pipe_pid_read_fd.take() { |
| 146 | close(fd); | 174 | close(fd); |
| 147 | } | 175 | } |
| 176 | + if let Some(fd) = pipe_wait_write_fd.take() { | ||
| 177 | + close(fd); | ||
| 178 | + } | ||
| 148 | 179 | ||
| 149 | // Convert the our FDs to OwnedFd, which will close them in all of our fork paths. | 180 | // Convert the our FDs to OwnedFd, which will close them in all of our fork paths. |
| 150 | let pipe_pid_write = pipe_pid_write_fd.take().map(|fd| OwnedFd::from_raw_fd(fd)); | 181 | let pipe_pid_write = pipe_pid_write_fd.take().map(|fd| OwnedFd::from_raw_fd(fd)); |
| 182 | + let pipe_wait_read = pipe_wait_read_fd.take().map(|fd| OwnedFd::from_raw_fd(fd)); | ||
| 151 | 183 | ||
| 152 | match libc::fork() { | 184 | match libc::fork() { |
| 153 | -1 => return Err(io::Error::last_os_error()), | 185 | -1 => return Err(io::Error::last_os_error()), |
| @@ -158,6 +190,17 @@ fn spawn_sync(command: impl AsRef<OsStr>, args: impl IntoIterator<Item = impl As | |||
| 158 | let _ = write_all(pipe, &grandchild_pid.to_ne_bytes()); | 190 | let _ = write_all(pipe, &grandchild_pid.to_ne_bytes()); |
| 159 | } | 191 | } |
| 160 | 192 | ||
| 193 | + // Wait until the parent signals us to exit. | ||
| 194 | + if let Some(pipe) = pipe_wait_read { | ||
| 195 | + // We're going to exit afterwards. Close all other FDs to allow | ||
| 196 | + // Command::spawn() to return in the parent process. | ||
| 197 | + let raw = pipe.as_raw_fd() as u32; | ||
| 198 | + let _ = close_range(0, raw - 1, 0); | ||
| 199 | + let _ = close_range(raw + 1, !0, 0); | ||
| 200 | + | ||
| 201 | + let _ = read_all(pipe, &mut [0]); | ||
| 202 | + } | ||
| 203 | + | ||
| 161 | libc::_exit(0) | 204 | libc::_exit(0) |
| 162 | } | 205 | } |
| 163 | } | 206 | } |
| @@ -175,6 +218,7 @@ fn spawn_sync(command: impl AsRef<OsStr>, args: impl IntoIterator<Item = impl As | |||
| 175 | }; | 218 | }; |
| 176 | 219 | ||
| 177 | drop(pipe_pid_write); | 220 | drop(pipe_pid_write); |
| 221 | + drop(pipe_wait_read); | ||
| 178 | 222 | ||
| 179 | // Wait for the grandchild PID. | 223 | // Wait for the grandchild PID. |
| 180 | if let Some(pipe) = pipe_pid_read { | 224 | if let Some(pipe) = pipe_pid_read { |
| @@ -183,6 +227,12 @@ fn spawn_sync(command: impl AsRef<OsStr>, args: impl IntoIterator<Item = impl As | |||
| 183 | Ok(()) => { | 227 | Ok(()) => { |
| 184 | let pid = i32::from_ne_bytes(buf); | 228 | let pid = i32::from_ne_bytes(buf); |
| 185 | trace!("spawned PID: {pid}"); | 229 | trace!("spawned PID: {pid}"); |
| 230 | + | ||
| 231 | + // Start a systemd scope for the grandchild. | ||
| 232 | + #[cfg(feature = "dbus")] | ||
| 233 | + if let Err(err) = start_systemd_scope(command, child.id(), pid as u32) { | ||
| 234 | + trace!("error starting systemd scope for spawned command: {err:?}"); | ||
| 235 | + } | ||
| 186 | } | 236 | } |
| 187 | Err(err) => { | 237 | Err(err) => { |
| 188 | warn!("error reading child PID: {err:?}"); | 238 | warn!("error reading child PID: {err:?}"); |
| @@ -190,6 +240,10 @@ fn spawn_sync(command: impl AsRef<OsStr>, args: impl IntoIterator<Item = impl As | |||
| 190 | } | 240 | } |
| 191 | } | 241 | } |
| 192 | 242 | ||
| 243 | + // Signal the intermediate child to exit now that we're done trying to creating a systemd scope. | ||
| 244 | + trace!("signaling child to exit"); | ||
| 245 | + drop(pipe_wait_write); | ||
| 246 | + | ||
| 193 | match child.wait() { | 247 | match child.wait() { |
| 194 | Ok(status) => { | 248 | Ok(status) => { |
| 195 | if !status.success() { | 249 | if !status.success() { |
| @@ -232,6 +286,88 @@ fn read_all(fd: impl AsFd, buf: &mut [u8]) -> rustix::io::Result<()> { | |||
| 232 | } | 286 | } |
| 233 | } | 287 | } |
| 234 | 288 | ||
| 289 | +pub static IS_SYSTEMD_SERVICE: AtomicBool = AtomicBool::new(false); | ||
| 290 | + | ||
| 291 | +/// Puts a (newly spawned) pid into a transient systemd scope. | ||
| 292 | +/// | ||
| 293 | +/// This separates the pid from the compositor scope, which for example prevents the OOM killer | ||
| 294 | +/// from bringing down the compositor together with a misbehaving client. | ||
| 295 | +#[cfg(feature = "dbus")] | ||
| 296 | +fn start_systemd_scope(name: &OsStr, intermediate_pid: u32, child_pid: u32) -> anyhow::Result<()> { | ||
| 297 | + use std::fmt::Write as _; | ||
| 298 | + use std::path::Path; | ||
| 299 | + use std::sync::OnceLock; | ||
| 300 | + | ||
| 301 | + use zbus::zvariant::{OwnedObjectPath, Value}; | ||
| 302 | + | ||
| 303 | + // We only start transient scopes if we're a systemd service ourselves. | ||
| 304 | + if !IS_SYSTEMD_SERVICE.load(Ordering::Relaxed) { | ||
| 305 | + return Ok(()); | ||
| 306 | + } | ||
| 307 | + | ||
| 308 | + let _span = tracy_client::span!(); | ||
| 309 | + | ||
| 310 | + // Extract the basename. | ||
| 311 | + let name = Path::new(name).file_name().unwrap_or(name); | ||
| 312 | + | ||
| 313 | + let mut scope_name = String::from("app-niri-"); | ||
| 314 | + | ||
| 315 | + // Escape for systemd similarly to libgnome-desktop, which says it had adapted this from | ||
| 316 | + // systemd source. | ||
| 317 | + for &c in name.as_bytes() { | ||
| 318 | + if c.is_ascii_alphanumeric() || matches!(c, b':' | b'_' | b'.') { | ||
| 319 | + scope_name.push(char::from(c)); | ||
| 320 | + } else { | ||
| 321 | + let _ = write!(scope_name, "\\x{c:02x}"); | ||
| 322 | + } | ||
| 323 | + } | ||
| 324 | + | ||
| 325 | + let _ = write!(scope_name, "-{child_pid}.scope"); | ||
| 326 | + | ||
| 327 | + // Ask systemd to start a transient scope. | ||
| 328 | + static CONNECTION: OnceLock<zbus::Result<zbus::blocking::Connection>> = OnceLock::new(); | ||
| 329 | + let conn = CONNECTION | ||
| 330 | + .get_or_init(zbus::blocking::Connection::session) | ||
| 331 | + .clone() | ||
| 332 | + .context("error connecting to session bus")?; | ||
| 333 | + | ||
| 334 | + let proxy = zbus::blocking::Proxy::new( | ||
| 335 | + &conn, | ||
| 336 | + "org.freedesktop.systemd1", | ||
| 337 | + "/org/freedesktop/systemd1", | ||
| 338 | + "org.freedesktop.systemd1.Manager", | ||
| 339 | + ) | ||
| 340 | + .context("error creating a Proxy")?; | ||
| 341 | + | ||
| 342 | + let signals = proxy | ||
| 343 | + .receive_signal("JobRemoved") | ||
| 344 | + .context("error creating a signal iterator")?; | ||
| 345 | + | ||
| 346 | + let pids: &[_] = &[intermediate_pid, child_pid]; | ||
| 347 | + let properties: &[_] = &[ | ||
| 348 | + ("PIDs", Value::new(pids)), | ||
| 349 | + ("CollectMode", Value::new("inactive-or-failed")), | ||
| 350 | + ]; | ||
| 351 | + let aux: &[(&str, &[(&str, Value)])] = &[]; | ||
| 352 | + | ||
| 353 | + let job: OwnedObjectPath = proxy | ||
| 354 | + .call("StartTransientUnit", &(scope_name, "fail", properties, aux)) | ||
| 355 | + .context("error calling StartTransientUnit")?; | ||
| 356 | + | ||
| 357 | + trace!("waiting for JobRemoved"); | ||
| 358 | + for message in signals { | ||
| 359 | + let body: (u32, OwnedObjectPath, &str, &str) = | ||
| 360 | + message.body().context("error parsing signal")?; | ||
| 361 | + | ||
| 362 | + if body.1 == job { | ||
| 363 | + // Our transient unit had started, we're good to exit the intermediate child. | ||
| 364 | + break; | ||
| 365 | + } | ||
| 366 | + } | ||
| 367 | + | ||
| 368 | + Ok(()) | ||
| 369 | +} | ||
| 370 | + | ||
| 235 | pub fn write_png_rgba8( | 371 | pub fn write_png_rgba8( |
| 236 | w: impl Write, | 372 | w: impl Write, |
| 237 | width: u32, | 373 | width: u32, |