Skip to main content

lean_ctx/
daemon.rs

1use std::fs;
2use std::io::Write;
3use std::path::PathBuf;
4use std::process::Command;
5
6use anyhow::{Context, Result};
7
8use crate::ipc;
9
10fn data_dir() -> PathBuf {
11    dirs::data_local_dir()
12        .unwrap_or_else(|| dirs::home_dir().unwrap_or_default().join(".local/share"))
13        .join("lean-ctx")
14}
15
16pub fn daemon_pid_path() -> PathBuf {
17    data_dir().join("daemon.pid")
18}
19
20pub fn daemon_addr() -> ipc::DaemonAddr {
21    ipc::DaemonAddr::default_for_current_os()
22}
23
24pub fn is_daemon_running() -> bool {
25    let pid_path = daemon_pid_path();
26    let Ok(contents) = fs::read_to_string(&pid_path) else {
27        return false;
28    };
29    let Ok(pid) = contents.trim().parse::<u32>() else {
30        return false;
31    };
32    if ipc::process::is_alive(pid) {
33        return true;
34    }
35    let _ = fs::remove_file(&pid_path);
36    ipc::cleanup(&daemon_addr());
37    false
38}
39
40pub fn read_daemon_pid() -> Option<u32> {
41    let contents = fs::read_to_string(daemon_pid_path()).ok()?;
42    contents.trim().parse::<u32>().ok()
43}
44
45pub fn start_daemon(args: &[String]) -> Result<()> {
46    if is_daemon_running() {
47        let pid = read_daemon_pid().unwrap_or(0);
48        anyhow::bail!("Daemon already running (PID {pid}). Use --stop to stop it first.");
49    }
50
51    ipc::cleanup(&daemon_addr());
52
53    if let Ok(data_dir) = crate::core::data_dir::lean_ctx_data_dir() {
54        crate::config_io::cleanup_legacy_backups(&data_dir);
55    }
56
57    let exe = std::env::current_exe().context("cannot determine own executable path")?;
58
59    let mut cmd_args = vec!["serve".to_string()];
60    for arg in args {
61        if arg == "--daemon" || arg == "-d" {
62            continue;
63        }
64        cmd_args.push(arg.clone());
65    }
66    cmd_args.push("--_foreground-daemon".to_string());
67
68    let log_dir = data_dir();
69    let _ = fs::create_dir_all(&log_dir);
70    let stderr_log = log_dir.join("daemon-stderr.log");
71    let stderr_file = fs::OpenOptions::new()
72        .create(true)
73        .write(true)
74        .truncate(true)
75        .open(&stderr_log)
76        .ok();
77
78    let stderr_cfg = match stderr_file {
79        Some(f) => std::process::Stdio::from(f),
80        None => std::process::Stdio::null(),
81    };
82
83    let child = Command::new(&exe)
84        .args(&cmd_args)
85        .stdin(std::process::Stdio::null())
86        .stdout(std::process::Stdio::null())
87        .stderr(stderr_cfg)
88        .spawn()
89        .with_context(|| format!("failed to spawn daemon: {}", exe.display()))?;
90
91    let pid = child.id();
92    write_pid_file(pid)?;
93
94    std::thread::sleep(std::time::Duration::from_millis(200));
95
96    if !ipc::process::is_alive(pid) {
97        let _ = fs::remove_file(daemon_pid_path());
98        let stderr_content = fs::read_to_string(&stderr_log).unwrap_or_default();
99        let stderr_trimmed = stderr_content.trim();
100        if stderr_trimmed.is_empty() {
101            anyhow::bail!("Daemon process exited immediately. Check logs for errors.");
102        }
103        anyhow::bail!("Daemon process exited immediately:\n{stderr_trimmed}");
104    }
105
106    let addr = daemon_addr();
107    eprintln!(
108        "lean-ctx daemon started (PID {pid})\n  Endpoint: {}\n  PID file: {}",
109        addr.display(),
110        daemon_pid_path().display()
111    );
112
113    Ok(())
114}
115
116pub fn stop_daemon() -> Result<()> {
117    let pid_path = daemon_pid_path();
118
119    let Some(pid) = read_daemon_pid() else {
120        eprintln!("No daemon PID file found. Nothing to stop.");
121        return Ok(());
122    };
123
124    if !ipc::process::is_alive(pid) {
125        eprintln!("Daemon (PID {pid}) is not running. Cleaning up stale files.");
126        ipc::cleanup(&daemon_addr());
127        let _ = fs::remove_file(&pid_path);
128        return Ok(());
129    }
130
131    // Step 1: Try graceful HTTP shutdown.
132    let http_shutdown_ok = try_http_shutdown();
133
134    // Step 2: Wait up to 3s for process exit.
135    if http_shutdown_ok {
136        for _ in 0..30 {
137            std::thread::sleep(std::time::Duration::from_millis(100));
138            if !ipc::process::is_alive(pid) {
139                break;
140            }
141        }
142    }
143
144    // Step 3: OS-level graceful termination if still alive.
145    if ipc::process::is_alive(pid) {
146        let _ = ipc::process::terminate_gracefully(pid);
147        for _ in 0..20 {
148            std::thread::sleep(std::time::Duration::from_millis(100));
149            if !ipc::process::is_alive(pid) {
150                break;
151            }
152        }
153    }
154
155    // Step 4: Force kill as last resort.
156    if ipc::process::is_alive(pid) {
157        eprintln!("Daemon (PID {pid}) did not stop gracefully, force killing.");
158        let _ = ipc::process::force_kill(pid);
159        std::thread::sleep(std::time::Duration::from_millis(100));
160    }
161
162    let _ = fs::remove_file(&pid_path);
163    ipc::cleanup(&daemon_addr());
164    eprintln!("lean-ctx daemon stopped (PID {pid}).");
165    Ok(())
166}
167
168fn try_http_shutdown() -> bool {
169    let Ok(rt) = tokio::runtime::Runtime::new() else {
170        return false;
171    };
172
173    rt.block_on(async {
174        crate::daemon_client::daemon_request("POST", "/v1/shutdown", "")
175            .await
176            .is_ok()
177    })
178}
179
180pub fn daemon_status() -> String {
181    let addr = daemon_addr();
182    if let Some(pid) = read_daemon_pid() {
183        if ipc::process::is_alive(pid) {
184            let listening = addr.is_listening();
185            return format!(
186                "Daemon running (PID {pid})\n  Endpoint: {} ({})\n  PID file: {}",
187                addr.display(),
188                if listening { "ready" } else { "missing" },
189                daemon_pid_path().display()
190            );
191        }
192        return format!("Daemon not running (stale PID file for PID {pid})");
193    }
194    "Daemon not running".to_string()
195}
196
197fn write_pid_file(pid: u32) -> Result<()> {
198    let pid_path = daemon_pid_path();
199    if let Some(parent) = pid_path.parent() {
200        fs::create_dir_all(parent)
201            .with_context(|| format!("cannot create dir: {}", parent.display()))?;
202    }
203    let mut f = fs::File::create(&pid_path)
204        .with_context(|| format!("cannot write PID file: {}", pid_path.display()))?;
205    write!(f, "{pid}")?;
206    Ok(())
207}
208
209/// Write the current process's PID. Called from the foreground-daemon process.
210pub fn init_foreground_daemon() -> Result<()> {
211    let pid = std::process::id();
212    write_pid_file(pid)?;
213    Ok(())
214}
215
216/// Cleanup PID file and IPC endpoint on shutdown.
217pub fn cleanup_daemon_files() {
218    let _ = fs::remove_file(daemon_pid_path());
219    ipc::cleanup(&daemon_addr());
220}