use std::path::Path;
pub fn detach_from_terminal(root: &Path) -> anyhow::Result<()> {
#[cfg(unix)]
{
if std::io::stdout().is_terminal() {
return relaunch(root);
}
if let Some(pipe) = adopted_pipe() {
*READY.lock().unwrap_poison() = Some(pipe);
}
Ok(())
}
#[cfg(not(unix))]
{
let _ = root;
Ok(())
}
}
pub fn report_running() {
send(RUNNING);
}
pub fn report_already_running() {
send(ALREADY_RUNNING);
}
pub fn report_failure(reason: &str) {
send(&format!(
"{FAILED_PREFIX}{}",
reason.replace('\n', " ").trim_end()
));
}
const RUNNING: &str = "running";
const ALREADY_RUNNING: &str = "already running";
const FAILED_PREFIX: &str = "failed: ";
#[cfg(unix)]
use std::io::{IsTerminal as _, Read as _, Write as _};
#[cfg(unix)]
use std::os::fd::{AsRawFd as _, FromRawFd as _, RawFd};
#[cfg(unix)]
use std::os::unix::process::CommandExt as _;
#[cfg(unix)]
use anyhow::{Context as _, anyhow};
#[cfg(unix)]
use crate::util::{UnwrapPoison as _, print_stderr, print_stdout};
#[cfg(unix)]
const DAEMON_LOG: &str = "daemon.log";
#[cfg(unix)]
const READY_FD_ENV: &str = "MAHBOT_LAUNCH_READY_FD";
#[cfg(unix)]
const READY_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(120);
#[cfg(unix)]
static READY: std::sync::Mutex<Option<std::fs::File>> = std::sync::Mutex::new(None);
#[cfg(unix)]
enum Ready {
Said(String),
Silent,
Gone,
}
#[cfg(unix)]
fn adopted_pipe() -> Option<std::fs::File> {
let value = std::env::var(READY_FD_ENV).ok()?;
unsafe { std::env::remove_var(READY_FD_ENV) };
let fd: RawFd = value.parse().ok()?;
let mut stat: libc::stat = unsafe { std::mem::zeroed() };
if fd < 3
|| unsafe { libc::fcntl(fd, libc::F_GETFD) } == -1
|| unsafe { libc::fstat(fd, &raw mut stat) } == -1
|| stat.st_mode & libc::S_IFMT != libc::S_IFIFO
{
return None;
}
unsafe { libc::fcntl(fd, libc::F_SETFD, libc::FD_CLOEXEC) };
Some(unsafe { std::fs::File::from_raw_fd(fd) })
}
#[cfg(unix)]
fn relaunch(root: &Path) -> anyhow::Result<()> {
let log_path = root.join(DAEMON_LOG);
std::fs::create_dir_all(root)
.with_context(|| format!("could not create {}", root.display()))?;
let log = std::fs::OpenOptions::new()
.create(true)
.append(true)
.open(&log_path)
.with_context(|| format!("could not open {}", log_path.display()))?;
let (reader, writer) = ready_pipe()?;
let exe = std::env::current_exe().context("could not resolve the product's own path")?;
let mut command = std::process::Command::new(&exe);
command
.args(std::env::args_os().skip(1))
.env(READY_FD_ENV, writer.as_raw_fd().to_string())
.stdin(std::process::Stdio::null())
.stdout(std::process::Stdio::from(
log.try_clone()
.context("could not hand the log to the service")?,
))
.stderr(std::process::Stdio::from(log));
unsafe {
command.pre_exec(|| {
if libc::setsid() == -1 {
return Err(std::io::Error::last_os_error());
}
Ok(())
});
}
command
.spawn()
.with_context(|| format!("could not start the service from {}", exe.display()))?;
drop(writer);
announce(read_word(reader), &log_path)
}
#[cfg(unix)]
fn ready_pipe() -> anyhow::Result<(std::fs::File, std::fs::File)> {
let mut fds = [0; 2];
if unsafe { libc::pipe(fds.as_mut_ptr()) } == -1 {
return Err(anyhow!(
"could not create the readiness pipe: {}",
std::io::Error::last_os_error()
));
}
let (reader, writer) = unsafe {
(
std::fs::File::from_raw_fd(fds[0]),
std::fs::File::from_raw_fd(fds[1]),
)
};
unsafe { libc::fcntl(fds[0], libc::F_SETFD, libc::FD_CLOEXEC) };
Ok((reader, writer))
}
#[cfg(unix)]
fn read_word(mut reader: std::fs::File) -> Ready {
let deadline = std::time::Instant::now() + READY_TIMEOUT;
let mut buffer = [0_u8; 1024];
loop {
let remaining = deadline.saturating_duration_since(std::time::Instant::now());
let mut poll = libc::pollfd {
fd: reader.as_raw_fd(),
events: libc::POLLIN,
revents: 0,
};
let ready = unsafe { libc::poll(&raw mut poll, 1, remaining_ms(remaining)) };
if ready == 0 {
return Ready::Silent;
}
if ready < 0 {
let interrupted =
std::io::Error::last_os_error().kind() == std::io::ErrorKind::Interrupted;
if interrupted && std::time::Instant::now() < deadline {
continue;
}
return Ready::Silent;
}
match reader.read(&mut buffer) {
Ok(0) => return Ready::Gone,
Ok(read) => {
return match String::from_utf8_lossy(&buffer[..read]).lines().next() {
Some(word) => Ready::Said(word.trim().to_string()),
None => Ready::Gone,
};
}
Err(e) if e.kind() == std::io::ErrorKind::Interrupted => {}
Err(_) => return Ready::Gone,
}
}
}
#[cfg(unix)]
fn remaining_ms(remaining: std::time::Duration) -> libc::c_int {
libc::c_int::try_from(remaining.as_millis()).unwrap_or(libc::c_int::MAX)
}
#[cfg(unix)]
fn announce(ready: Ready, log_path: &Path) -> ! {
let path = log_path.display();
match ready {
Ready::Said(word) if word == RUNNING => {
print_stdout(&format!("MahBot is running — its log is {path}"));
}
Ready::Said(word) if word == ALREADY_RUNNING => {
print_stdout("MahBot is already running.");
}
Ready::Said(word) => {
let reason = word.strip_prefix(FAILED_PREFIX).unwrap_or(word.as_str());
print_stderr(&format!("MahBot could not start: {reason}"));
std::process::exit(1);
}
Ready::Silent => print_stdout(&format!("MahBot is starting — its log is {path}")),
Ready::Gone => {
print_stderr(&format!("MahBot could not start — its log is {path}"));
std::process::exit(1);
}
}
std::process::exit(0);
}
#[cfg(unix)]
fn send(word: &str) {
let mut held = READY.lock().unwrap_poison();
if let Some(mut pipe) = held.take() {
let _ = pipe.write_all(format!("{word}\n").as_bytes());
}
}
#[cfg(not(unix))]
fn send(_word: &str) {}