use std::{
io::{self, Write},
path::Path,
time::{Duration, Instant, SystemTime},
};
use super::service::run_manager_command;
use crate::daemon::paths::DaemonPaths;
const SCOPE_CALL_TIMEOUT: Duration = Duration::from_secs(1);
const MOVE_TIMEOUT: Duration = Duration::from_secs(1);
const MOVE_POLL_INTERVAL: Duration = Duration::from_millis(1);
pub(super) fn leave_caller_unit(pid: u32, paths: &DaemonPaths) {
let Ok(cgroup) = std::fs::read_to_string("/proc/self/cgroup") else {
return;
};
let Some(slice) = caller_slice(&cgroup) else {
return;
};
let unit = format!("rho-daemon-{pid}.scope");
let moved =
start_scope(&unit, slice, pid, &paths.home).and_then(|()| wait_until_moved(pid, &unit));
let Err(error) = moved else {
tracing::debug!(%unit, slice, "moved the rho daemon into a scope of its own");
return;
};
let warning = format!(
"could not confirm the rho daemon (pid {pid}) moved into {unit} in {slice}; \
stopping the systemd unit of the client that started it may stop it: {error}"
);
tracing::warn!("{warning}");
let line = format!(
"{} WARN {}: {warning}\n",
humantime::format_rfc3339_micros(SystemTime::now()),
module_path!()
);
if let Err(error) = paths
.open_log_file()
.and_then(|mut log| log.write_all(line.as_bytes()))
{
tracing::warn!(%error, log_file = %paths.log_file.display(), "could not write to the rho daemon log");
}
}
fn unified_path(proc_cgroup: &str) -> Option<&str> {
proc_cgroup
.lines()
.find_map(|line| line.strip_prefix("0::"))
}
fn caller_slice(proc_self_cgroup: &str) -> Option<&str> {
let components = unified_path(proc_self_cgroup)?
.split('/')
.skip_while(|component| !is_user_manager(component))
.skip(1);
let mut slice = None;
for component in components {
if !component.ends_with(".slice") {
return slice;
}
slice = Some(component);
}
None
}
fn is_user_manager(component: &str) -> bool {
component
.strip_prefix("user@")
.and_then(|rest| rest.strip_suffix(".service"))
.is_some_and(|uid| !uid.is_empty() && uid.bytes().all(|byte| byte.is_ascii_digit()))
}
fn start_scope(unit: &str, slice: &str, pid: u32, home: &Path) -> io::Result<()> {
let timeout = format!("--timeout={}", SCOPE_CALL_TIMEOUT.as_secs());
let pid = pid.to_string();
let description = format!("rho daemon for {}", home.display());
run_manager_command(
"busctl",
&[
"--user",
&timeout,
"call",
"org.freedesktop.systemd1",
"/org/freedesktop/systemd1",
"org.freedesktop.systemd1.Manager",
"StartTransientUnit",
"ssa(sv)a(sa(sv))",
unit,
"fail",
"4",
"PIDs",
"au",
"1",
&pid,
"Slice",
"s",
slice,
"CollectMode",
"s",
"inactive-or-failed",
"Description",
"s",
&description,
"0",
],
)
}
fn wait_until_moved(pid: u32, unit: &str) -> io::Result<()> {
let started = Instant::now();
let cgroup = format!("/proc/{pid}/cgroup");
loop {
let current = std::fs::read_to_string(&cgroup)?;
if unified_path(¤t).and_then(|path| path.rsplit('/').next()) == Some(unit) {
return Ok(());
}
let elapsed = started.elapsed();
if elapsed >= MOVE_TIMEOUT {
return Err(io::Error::new(
io::ErrorKind::TimedOut,
format!("not in {unit} after MOVE_TIMEOUT ({MOVE_TIMEOUT:?}; waited {elapsed:?})"),
));
}
std::thread::sleep(MOVE_POLL_INTERVAL);
}
}
#[cfg(test)]
#[path = "user_scope_tests.rs"]
mod tests;