use std::{
thread,
time::{Duration, Instant},
};
use allot_client::{BlockingClient, DaemonStart};
use anyhow::bail;
use serde::Serialize;
use crate::output::print_json;
const STOP_WAIT: Duration = Duration::from_secs(10);
const STOP_POLL: Duration = Duration::from_millis(100);
#[derive(Debug, Default, Serialize)]
struct NotRunning {
running: bool,
}
pub fn start() -> anyhow::Result<()> {
let client = BlockingClient::discover(true)?;
let started = client.ensure_running()?;
let health = client.health()?;
let verb = match started {
DaemonStart::AlreadyRunning => "already running",
DaemonStart::Started => "started",
};
println!(
"allotd {verb} at {} (pid {})",
client.base_url(),
health.pid
);
Ok(())
}
pub fn stop() -> anyhow::Result<()> {
let client = BlockingClient::discover(false)?;
match shutdown(&client)? {
Some(_) => println!("allotd stopped"),
None => println!("allotd is not running"),
}
Ok(())
}
pub fn shutdown(client: &BlockingClient) -> anyhow::Result<Option<u32>> {
let pid = match client.health() {
Ok(health) => health.pid,
Err(error) if error.is_unsent() => return Ok(None),
Err(error) => return Err(error.into()),
};
match client.shutdown() {
Err(error) if error.is_unsent() => return Ok(None),
other => other?,
}
let deadline = Instant::now() + STOP_WAIT;
while client.health().is_ok_and(|health| health.pid == pid) {
if Instant::now() >= deadline {
bail!(
"allotd is still answering {} s after the shutdown request",
STOP_WAIT.as_secs()
);
}
thread::sleep(STOP_POLL);
}
Ok(Some(pid))
}
pub fn status(json: bool) -> anyhow::Result<()> {
let client = BlockingClient::discover(false)?;
match client.health() {
Ok(health) if json => print_json(&health)?,
Err(error) if json && error.is_unreachable() => print_json(&NotRunning::default())?,
Ok(health) => {
println!(
"allotd {} running at {} (pid {}, up {} s)",
health.version,
client.base_url(),
health.pid,
health.uptime_secs
);
if let Some(error) = health.config_error {
println!("config rejected, allotd keeps the previous one: {error}");
}
}
Err(error) if error.is_unreachable() => {
println!("allotd is not running at {}", client.base_url());
}
Err(error) => return Err(error.into()),
}
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_not_running_json_has_only_the_running_flag() {
assert_eq!(
serde_json::to_string(&NotRunning::default()).unwrap(),
r#"{"running":false}"#
);
}
}