use std::io;
use std::os::fd::{AsRawFd, FromRawFd, OwnedFd};
use std::path::Path;
use std::time::Duration;
use tokio::io::Interest;
use tokio::io::unix::AsyncFd;
use tokio::net::UnixStream;
use super::{LifecycleError, PROBE_TIMEOUT};
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum Signal {
Term,
Kill,
}
impl Signal {
fn raw(self) -> libc::c_int {
match self {
Signal::Term => libc::SIGTERM,
Signal::Kill => libc::SIGKILL,
}
}
}
#[derive(Debug)]
pub struct PinnedProcess {
pid: u32,
fd: AsyncFd<OwnedFd>,
}
impl PinnedProcess {
pub(crate) fn open(pid: u32) -> Result<Option<Self>, LifecycleError> {
let raw_pid = libc::pid_t::try_from(pid).map_err(|_| LifecycleError::Io {
context: format!("pid {pid} out of range"),
source: io::Error::from(io::ErrorKind::InvalidInput),
})?;
let rc = unsafe { libc::syscall(libc::SYS_pidfd_open, raw_pid, 0) };
if rc < 0 {
let err = io::Error::last_os_error();
if err.raw_os_error() == Some(libc::ESRCH) {
return Ok(None);
}
return Err(LifecycleError::Io {
context: format!("pidfd_open({pid})"),
source: err,
});
}
let raw_fd = i32::try_from(rc).map_err(|_| LifecycleError::Io {
context: format!("pidfd_open({pid}) returned {rc}"),
source: io::Error::from(io::ErrorKind::InvalidData),
})?;
let owned = unsafe { OwnedFd::from_raw_fd(raw_fd) };
let fd = AsyncFd::with_interest(owned, Interest::READABLE).map_err(|source| {
LifecycleError::Io {
context: format!("register pidfd of {pid}"),
source,
}
})?;
Ok(Some(Self { pid, fd }))
}
pub fn pid(&self) -> u32 {
self.pid
}
pub fn send_signal(&self, signal: Signal) -> io::Result<()> {
let rc = unsafe {
libc::syscall(
libc::SYS_pidfd_send_signal,
self.fd.get_ref().as_raw_fd(),
signal.raw(),
std::ptr::null::<libc::siginfo_t>(),
0,
)
};
if rc < 0 {
return Err(io::Error::last_os_error());
}
Ok(())
}
pub(crate) fn has_exited(&self) -> bool {
let mut pfd = libc::pollfd {
fd: self.fd.get_ref().as_raw_fd(),
events: libc::POLLIN,
revents: 0,
};
let rc = unsafe { libc::poll(&raw mut pfd, 1, 0) };
rc > 0 && pfd.revents & libc::POLLIN != 0
}
pub(crate) async fn wait_exit(&self, limit: Duration) -> bool {
let deadline = tokio::time::Instant::now() + limit;
loop {
if self.has_exited() {
return true;
}
match tokio::time::timeout_at(deadline, self.fd.readable()).await {
Ok(Ok(mut guard)) => {
if !self.has_exited() {
guard.clear_ready();
}
}
Ok(Err(_)) | Err(_) => return self.has_exited(),
}
}
}
}
pub(crate) fn exe_name(pid: u32) -> io::Result<String> {
let target = std::fs::read_link(format!("/proc/{pid}/exe"))?;
Ok(strip_deleted(&target.to_string_lossy()))
}
pub(crate) fn strip_deleted(link_target: &str) -> String {
let trimmed = link_target
.strip_suffix(" (deleted)")
.unwrap_or(link_target);
Path::new(trimmed)
.file_name()
.map(|n| n.to_string_lossy().into_owned())
.unwrap_or_default()
}
pub(crate) enum Dial {
Peer(Option<u32>),
NotServing,
Inconclusive,
}
pub(crate) async fn dial(socket: &Path) -> Dial {
match tokio::time::timeout(PROBE_TIMEOUT, UnixStream::connect(socket)).await {
Ok(Ok(stream)) => Dial::Peer(crate::uds::peer_pid(&stream)),
Ok(Err(e))
if matches!(
e.kind(),
io::ErrorKind::NotFound | io::ErrorKind::ConnectionRefused
) =>
{
Dial::NotServing
}
Ok(Err(_)) | Err(_) => Dial::Inconclusive,
}
}