Skip to content
1        10        20        30        40        50        60        70        80        90        1001//! Background control for the local console. `start` runs `ui run` as a2//! detached process and `stop` ends it. The PID, port and log live in the Ino3//! state directory, so no root access or service manager is needed.45use std::{6    error::Error,7    fs::{self, OpenOptions},8    io::{self, ErrorKind, Read, Write},9    net::{SocketAddr, TcpStream},10    path::{Path, PathBuf},11    process::{Child, Command, Stdio},12    thread,13    time::{Duration, Instant},14};1516use super::{open_browser, prepare};17use crate::commands::once::cli::ServerUiArgs;1819const PID_FILE: &str = "console.pid";20const LOG_FILE: &str = "console.log";21const READY_TIMEOUT: Duration = Duration::from_secs(10);22const STOP_TIMEOUT: Duration = Duration::from_secs(10);23const POLL_INTERVAL: Duration = Duration::from_millis(100);2425pub fn start(args: &ServerUiArgs) -> Result<(), Box<dyn Error>> {26    require_unix()?;27    let dir = state_dir()?;28    fs::create_dir_all(&dir)?;29    let pid_path = dir.join(PID_FILE);30    if let Some(record) = running_record(&pid_path)? {31        println!(32            "Ino console is already running at {} (pid {})",33            console_url(record.port),34            record.pid35        );36        return Ok(());37    }3839    let (server, api_key) = prepare(args)?;40    let log_path = dir.join(LOG_FILE);41    let log = OpenOptions::new()42        .create(true)43        .append(true)44        .open(&log_path)?;45    let port = args.port.to_string();46    // The key goes through the environment, so the detached process never47    // needs to prompt for it. Only this user's processes can read it.48    let mut command = Command::new(std::env::current_exe()?);49    command50        .args([51            "once",52            "server",53            "ui",54            "run",55            "--server",56            server.as_str(),57            "--port",58            &port,59            "--no-open",60        ])61        .env("INO_API_KEY", api_key)62        .stdin(Stdio::null())63        .stdout(log.try_clone()?)64        .stderr(log);65    detach(&mut command);66    let mut child = command67        .spawn()68        .map_err(|error| format!("starting the Ino console: {error}"))?;69    let pid = child.id();70    fs::write(&pid_path, format!("{pid} {}\n", args.port))?;71    if let Err(error) = wait_until_ready(&mut child, args.port, &log_path) {72        let _ = child.kill();73        let _ = remove_pid_file(&pid_path);74        return Err(error);75    }7677    let url = console_url(args.port);78    println!("Ino console running in the background at {url} (pid {pid})");79    println!("Logs: {}", log_path.display());80    println!("Stop it with `ino once server ui stop`.");81    if !args.no_open {82        open_browser(&url);83    }84    Ok(())85}8687pub fn stop() -> Result<(), Box<dyn Error>> {88    require_unix()?;89    let pid_path = state_dir()?.join(PID_FILE);90    let Some(record) = running_record(&pid_path)? else {91        println!("Ino console is not running");92        return Ok(());93    };94    terminate(record.pid)?;95    wait_for_exit(record.pid)?;96    remove_pid_file(&pid_path)?;97    println!("Stopped Ino console (pid {})", record.pid);98    Ok(())99}100101fn require_unix() -> Result<(), Box<dyn Error>> {102    if cfg!(unix) {103        Ok(())104    } else {105        Err("the Ino console service needs a Unix-like system; use `ino once server ui run` instead".into())106    }107}108109pub(super) fn state_dir() -> Result<PathBuf, Box<dyn Error>> {110    let base = std::env::var_os("XDG_STATE_HOME")111        .filter(|value| !value.is_empty())112        .map(PathBuf::from)113        .or_else(|| {114            std::env::var_os("HOME").map(|home| PathBuf::from(home).join(".local").join("state"))115        })116        .ok_or("set HOME or XDG_STATE_HOME so Ino can keep the console state")?;117    Ok(base.join("ino"))118}119120fn console_url(port: u16) -> String {121    format!("http://127.0.0.1:{port}/")122}123124/// Waits until the detached console answers on its port, or reports why it125/// did not start. Another process on the port does not count as ready.126fn wait_until_ready(child: &mut Child, port: u16, log_path: &Path) -> Result<(), Box<dyn Error>> {127    let address = SocketAddr::from(([127, 0, 0, 1], port));128    let deadline = Instant::now() + READY_TIMEOUT;129    loop {130        if let Some(status) = child.try_wait()? {131            return Err(format!(132                "the Ino console exited before it was ready ({status}); see {}",133                log_path.display()134            )135            .into());136        }137        if console_responds(address) {138            return Ok(());139        }140        if Instant::now() >= deadline {141            return Err(format!(142                "the Ino console did not respond on {address} within {}s; see {}",143                READY_TIMEOUT.as_secs(),144                log_path.display()145            )146            .into());147        }148        thread::sleep(POLL_INTERVAL);149    }150}151152/// Asks the console for its session route, which answers 200 only for a153/// console that is serving.154fn console_responds(address: SocketAddr) -> bool {155    let Ok(mut stream) = TcpStream::connect_timeout(&address, POLL_INTERVAL) else {156        return false;157    };158    if stream.set_read_timeout(Some(READY_TIMEOUT)).is_err() {159        return false;160    }161    let request =162        format!("GET /_console/session HTTP/1.1\r\nHost: {address}\r\nConnection: close\r\n\r\n");163    if stream.write_all(request.as_bytes()).is_err() {164        return false;165    }166    let mut status_line = [0_u8; 12];167    stream.read_exact(&mut status_line).is_ok() && &status_line == b"HTTP/1.1 200"168}169170fn wait_for_exit(pid: i32) -> Result<(), Box<dyn Error>> {171    let deadline = Instant::now() + STOP_TIMEOUT;172    while process_exists(pid) {173        if Instant::now() >= deadline {174            return Err(format!(175                "the Ino console (pid {pid}) did not stop within {}s",176                STOP_TIMEOUT.as_secs()177            )178            .into());179        }180        thread::sleep(POLL_INTERVAL);181    }182    Ok(())183}184185struct Record {186    pid: i32,187    port: u16,188}189190/// Returns the recorded console when its process is still alive. A record191/// for a process that has exited is removed.192fn running_record(path: &Path) -> Result<Option<Record>, Box<dyn Error>> {193    let Some(record) = read_record(path)? else {194        return Ok(None);195    };196    if process_exists(record.pid) {197        return Ok(Some(record));198    }199    remove_pid_file(path)?;200    Ok(None)201}202203fn read_record(path: &Path) -> io::Result<Option<Record>> {204    let text = match fs::read_to_string(path) {205        Ok(text) => text,206        Err(error) if error.kind() == ErrorKind::NotFound => return Ok(None),207        Err(error) => return Err(error),208    };209    let mut fields = text.split_whitespace();210    let pid = fields.next().and_then(|field| field.parse::<i32>().ok());211    let port = fields.next().and_then(|field| field.parse::<u16>().ok());212    Ok(pid213        .zip(port)214        .filter(|(pid, _)| *pid > 0)215        .map(|(pid, port)| Record { pid, port }))216}217218fn remove_pid_file(path: &Path) -> io::Result<()> {219    match fs::remove_file(path) {220        Ok(()) => Ok(()),221        Err(error) if error.kind() == ErrorKind::NotFound => Ok(()),222        Err(error) => Err(error),223    }224}225226#[cfg(unix)]227fn detach(command: &mut Command) {228    use std::os::unix::process::CommandExt;229    // A separate process group keeps terminal signals, such as Ctrl+C, away230    // from the console.231    command.process_group(0);232}233234#[cfg(not(unix))]235fn detach(_command: &mut Command) {}236237#[cfg(unix)]238fn terminate(pid: i32) -> io::Result<()> {239    if unsafe { libc::kill(pid, libc::SIGTERM) } == 0 {240        Ok(())241    } else {242        Err(io::Error::last_os_error())243    }244}245246#[cfg(not(unix))]247fn terminate(_pid: i32) -> io::Result<()> {248    Err(io::Error::new(249        ErrorKind::Unsupported,250        "stopping the console needs a Unix-like system",251    ))252}253254#[cfg(unix)]255fn process_exists(pid: i32) -> bool {256    unsafe { libc::kill(pid, 0) == 0 }257}258259#[cfg(not(unix))]260fn process_exists(_pid: i32) -> bool {261    false262}263264#[cfg(test)]265mod tests {266    use std::fs;267268    use super::read_record;269270    #[test]271    fn pid_file_records_the_console_process_and_port() {272        let directory = tempfile::tempdir().unwrap();273        let path = directory.path().join("console.pid");274275        fs::write(&path, "4242 7878\n").unwrap();276        let record = read_record(&path).unwrap().unwrap();277        assert_eq!((record.pid, record.port), (4242, 7878));278279        fs::write(&path, "not a process").unwrap();280        assert!(read_record(&path).unwrap().is_none());281        assert!(282            read_record(&directory.path().join("missing.pid"))283                .unwrap()284                .is_none()285        );286    }287}