use std::{
ffi::OsString,
fs::File,
io,
path::Path,
process::{Command, Stdio},
time::{Duration, Instant},
};
use windows_sys::Win32::{
Foundation::{CloseHandle, ERROR_INVALID_PARAMETER, WAIT_OBJECT_0, WAIT_TIMEOUT},
System::Threading::{OpenProcess, WaitForSingleObject, PROCESS_SYNCHRONIZE},
};
use super::{endpoint::Listener, files::open_lock_file, process::spawn_detached};
use crate::daemon::{paths::DaemonPaths, server::Restarting};
const PREDECESSOR_EXIT_TIMEOUT: Duration = Duration::from_secs(5);
pub(in crate::daemon) fn relaunch(
restarting: Restarting,
executable: &Path,
args: impl FnOnce(Option<String>) -> Vec<OsString>,
) -> io::Result<()> {
let paths = restarting.paths.clone();
restarting.release();
tracing::info!(executable = %executable.display(), "starting the rho daemon again");
let mut command = Command::new(executable);
command
.args(args(Some(std::process::id().to_string())))
.stdin(Stdio::null())
.stdout(Stdio::null())
.stderr(Stdio::null());
spawn_detached(&mut command, &paths)
.map(drop)
.inspect_err(|error| {
tracing::error!(
executable = %executable.display(),
%error,
"could not start the rho daemon again; exiting"
);
})
}
pub(in crate::daemon) fn take_handoff(
paths: &DaemonPaths,
token: &str,
) -> io::Result<(File, Option<Listener>)> {
let predecessor = token.parse::<u32>().map_err(|error| {
io::Error::new(
io::ErrorKind::InvalidInput,
format!("expected the pid of the daemon that restarted, got {token:?}: {error}"),
)
})?;
wait_for_exit(predecessor)?;
Ok((open_lock_file(&paths.lock)?, None))
}
fn wait_for_exit(pid: u32) -> io::Result<()> {
let process = unsafe {
OpenProcess(PROCESS_SYNCHRONIZE, 0, pid)
};
if process.is_null() {
let error = io::Error::last_os_error();
return if error.raw_os_error() == Some(ERROR_INVALID_PARAMETER as i32) {
Ok(())
} else {
Err(error)
};
}
let started = Instant::now();
let waited = unsafe {
let waited = WaitForSingleObject(process, PREDECESSOR_EXIT_TIMEOUT.as_millis() as u32);
let error = io::Error::last_os_error();
CloseHandle(process);
(waited, error)
};
let elapsed = started.elapsed();
match waited {
(WAIT_OBJECT_0, _) => {
tracing::debug!(pid, ?elapsed, "the daemon that restarted has exited");
Ok(())
}
(WAIT_TIMEOUT, _) => Err(io::Error::new(
io::ErrorKind::TimedOut,
format!(
"the rho daemon that restarted (pid {pid}) did not exit within PREDECESSOR_EXIT_TIMEOUT ({PREDECESSOR_EXIT_TIMEOUT:?}; waited {elapsed:?})"
),
)),
(_, error) => Err(error),
}
}