use std::fs::{self, File, OpenOptions, TryLockError};
use std::io::{self, BufRead, BufReader, Read, Write};
use std::os::unix::fs::PermissionsExt;
use std::os::unix::net::{UnixListener, UnixStream};
use std::path::PathBuf;
use std::sync::{Arc, RwLock};
use std::thread;
use std::time::{Duration, Instant};
use marathon_core::protocol::{Reply, Request, from_line, to_line};
use crate::Engine;
const IO_TIMEOUT: Duration = Duration::from_secs(5);
const MAX_LINE: u64 = 64 * 1024;
const STACK: usize = 256 * 1024;
pub fn support_dir() -> PathBuf {
if let Some(dir) = std::env::var_os("MARATHON_DIR") {
return dir.into();
}
let home = std::env::var_os("HOME").unwrap_or_else(|| "/tmp".into());
PathBuf::from(home).join("Library/Application Support/Marathon")
}
fn socket_path() -> PathBuf {
support_dir().join("marathon.sock")
}
pub fn request(req: &Request) -> io::Result<Reply> {
let stream = UnixStream::connect(socket_path())?;
set_timeouts(&stream)?;
(&stream).write_all(to_line(req).as_bytes())?;
let line = read_line(&stream)?;
if line.is_empty() {
return Err(io::ErrorKind::UnexpectedEof.into());
}
from_line(&line).map_err(io::Error::other)
}
fn set_timeouts(stream: &UnixStream) -> io::Result<()> {
stream.set_read_timeout(Some(IO_TIMEOUT))?;
stream.set_write_timeout(Some(IO_TIMEOUT))
}
fn read_line(stream: &UnixStream) -> io::Result<String> {
let mut line = String::new();
BufReader::new(stream.take(MAX_LINE)).read_line(&mut line)?;
Ok(line)
}
pub fn is_no_server(err: &io::Error) -> bool {
matches!(
err.kind(),
io::ErrorKind::NotFound
| io::ErrorKind::ConnectionRefused
| io::ErrorKind::ConnectionReset
| io::ErrorKind::UnexpectedEof
)
}
pub struct Server {
busy: Arc<RwLock<()>>,
_lock: File,
}
impl Server {
pub fn start(engine: Engine, wait: Duration) -> io::Result<Server> {
let dir = support_dir();
fs::create_dir_all(&dir)?;
fs::set_permissions(&dir, fs::Permissions::from_mode(0o700))?;
let lock = OpenOptions::new()
.create(true)
.truncate(false)
.write(true)
.open(dir.join("marathon.lock"))?;
acquire(&lock, wait)?;
let path = socket_path();
crate::store::remove(&path)?;
let listener = UnixListener::bind(&path)?;
engine.start_saving();
let busy = Arc::new(RwLock::new(()));
let b = busy.clone();
thread::Builder::new()
.name("marathon-ipc".into())
.stack_size(STACK)
.spawn(move || {
for stream in listener.incoming() {
let Ok(stream) = stream else {
thread::sleep(Duration::from_millis(100));
continue;
};
let (engine, b) = (engine.clone(), b.clone());
let _ = thread::Builder::new()
.name("marathon-client".into())
.stack_size(STACK)
.spawn(move || {
let _guard = b.read().unwrap_or_else(|e| e.into_inner());
let _ = answer(&engine, stream);
});
}
})?;
Ok(Server { busy, _lock: lock })
}
pub fn take_over(engine: &Engine) -> io::Result<()> {
let deadline = Instant::now() + Duration::from_secs(3);
let released = loop {
match Server::start(engine.clone(), Duration::ZERO) {
Ok(server) => return server.keep(),
Err(e) if e.kind() != io::ErrorKind::WouldBlock => return Err(e),
Err(_) => {}
}
match request(&Request::Release) {
Ok(Ok(theirs)) => break theirs.session,
Ok(Err(e)) => return Err(io::Error::new(io::ErrorKind::AlreadyExists, e)),
Err(_) if Instant::now() < deadline => thread::sleep(Duration::from_millis(20)),
Err(e) => {
return Err(io::Error::new(
io::ErrorKind::AlreadyExists,
format!("another Marathon process serves and does not answer: {e}"),
));
}
}
};
match Server::start(engine.clone(), Duration::from_secs(3)) {
Ok(server) => {
if let Some(session) = released {
engine.start(session)?;
}
server.keep()
}
Err(e) if e.kind() == io::ErrorKind::WouldBlock => {
let engine = engine.clone();
thread::Builder::new()
.name("marathon-takeover".into())
.stack_size(STACK)
.spawn(move || {
if let Err(e) = Server::start(engine, Duration::MAX).and_then(Server::keep)
{
eprintln!("Marathon: can't take over from the CLI helper: {e}");
}
})?;
Ok(())
}
Err(e) => Err(e),
}
}
pub fn keep(self) -> io::Result<()> {
std::mem::forget(self);
Ok(())
}
pub fn quiesce<R>(&self, f: impl FnOnce() -> R) -> R {
let _guard = self.busy.write().unwrap_or_else(|e| e.into_inner());
f()
}
}
fn acquire(lock: &File, wait: Duration) -> io::Result<()> {
if wait == Duration::MAX {
return lock.lock();
}
let deadline = Instant::now() + wait;
loop {
match lock.try_lock() {
Ok(()) => return Ok(()),
Err(TryLockError::Error(e)) => return Err(e),
Err(TryLockError::WouldBlock) if Instant::now() < deadline => {
thread::sleep(Duration::from_millis(10))
}
Err(TryLockError::WouldBlock) => return Err(io::ErrorKind::WouldBlock.into()),
}
}
}
fn answer(engine: &Engine, stream: UnixStream) -> io::Result<()> {
set_timeouts(&stream)?;
let reply: Reply = from_line(&read_line(&stream)?).and_then(|req| engine.handle(req));
(&stream).write_all(to_line(&reply).as_bytes())
}