use std::time::Duration;
use crate::cli::{is_running, read_pid_file, BIND_ADDR};
const RESTART_TIMEOUT: Duration = Duration::from_secs(5);
const POLL_INTERVAL: Duration = Duration::from_millis(100);
pub fn stop_running_and_wait() -> anyhow::Result<()> {
let _ = crate::cli::http_request("POST", "/api/v1/shutdown");
if wait_until_stopped() {
return Ok(());
}
if let Some(pid) = read_pid_file() {
kill_pid(pid);
if wait_until_stopped() {
return Ok(());
}
}
if is_running() {
anyhow::bail!("could not stop the running moadim instance at http://{BIND_ADDR}");
}
Ok(())
}
fn wait_until_stopped() -> bool {
let deadline = std::time::Instant::now() + RESTART_TIMEOUT;
while std::time::Instant::now() < deadline {
if !is_running() {
return true;
}
std::thread::sleep(POLL_INTERVAL);
}
!is_running()
}
#[cfg(unix)]
fn kill_pid(pid: u32) {
let _ = std::process::Command::new("kill")
.args(["-9", &pid.to_string()])
.output();
}
#[cfg(not(unix))]
fn kill_pid(pid: u32) {
let _ = std::process::Command::new("taskkill")
.args(["/F", "/PID", &pid.to_string()])
.output();
}