ci / rust (push) Successful in 1m37s
The daemon never noticed when a session's command exited and tmux tore the session down — the in-memory `SessionManager` map plus the registry catalog kept showing it as `Running`, and a follow-up `maestro attach` would hang on an empty broadcast. Adds a per-host background task that polls `tmux list-sessions` every 2s, diffs against the in-memory set, and reaps anything we still track but tmux has lost: drops the record, deletes the sidecar + FIFO, cleans up its worktree if requested, and emits `SessionEvent::Removed` so the registry purges its catalog. The task holds a `Weak<Inner>` so it exits cleanly once the last `SessionManager` clone is dropped. Skips the tmux subprocess when the in-memory map is empty.
182 lines
5.7 KiB
Rust
182 lines
5.7 KiB
Rust
//! `maestrod` — the Maestro per-host daemon binary.
|
|
//!
|
|
//! Two subcommands:
|
|
//! - `maestrod` / `maestrod run` — start the daemon.
|
|
//! - `maestrod configure` — bootstrap the config file.
|
|
|
|
use std::error::Error;
|
|
use std::path::PathBuf;
|
|
use std::process::ExitCode;
|
|
|
|
use clap::{Parser, Subcommand};
|
|
use maestro_daemon::session::DEFAULT_LIVENESS_INTERVAL;
|
|
use maestro_daemon::sidecar::SidecarStore;
|
|
use maestro_daemon::tmux::Tmux;
|
|
use maestro_daemon::worktree::WorktreeManager;
|
|
use maestro_daemon::{
|
|
attach, default_config_path, default_state_dir, load_config, run_configure, ConfigureInputs,
|
|
EnvOverrides, JwtVerifier, RegistryClient, SessionManager,
|
|
};
|
|
use tokio::net::TcpListener;
|
|
use tracing_subscriber::EnvFilter;
|
|
|
|
#[derive(Debug, Parser)]
|
|
#[command(
|
|
name = "maestrod",
|
|
version,
|
|
about = "Per-host Maestro daemon: tmux wrapper + registry client"
|
|
)]
|
|
struct Cli {
|
|
/// Override the config-file path (default `~/.config/maestrod/config.toml`).
|
|
#[arg(long, global = true, env = "MAESTROD_CONFIG")]
|
|
config: Option<PathBuf>,
|
|
|
|
#[command(subcommand)]
|
|
command: Option<Command>,
|
|
}
|
|
|
|
#[derive(Debug, Subcommand)]
|
|
enum Command {
|
|
/// Start the daemon. Default when no subcommand is given.
|
|
Run,
|
|
/// Write `~/.config/maestrod/config.toml` interactively or from flags.
|
|
Configure(ConfigureCmd),
|
|
}
|
|
|
|
#[derive(Debug, clap::Args)]
|
|
struct ConfigureCmd {
|
|
/// Registry WS URL (e.g. `wss://maestro.example.com/daemon`).
|
|
#[arg(long)]
|
|
registry_url: Option<String>,
|
|
/// Reachable URL clients dial for this daemon's attach WS.
|
|
#[arg(long)]
|
|
daemon_url: Option<String>,
|
|
/// Shared MAESTRO_TOKEN. Tip: pipe from `pass` / `op` / `secret-tool`.
|
|
#[arg(long)]
|
|
token: Option<String>,
|
|
/// Stable daemon ID. Defaults to the system hostname.
|
|
#[arg(long)]
|
|
daemon_id: Option<String>,
|
|
/// Local bind address for the per-session WS endpoint.
|
|
#[arg(long)]
|
|
bind_addr: Option<String>,
|
|
/// Override the daemon's state directory.
|
|
#[arg(long)]
|
|
state_dir: Option<PathBuf>,
|
|
/// Override the worktree root.
|
|
#[arg(long)]
|
|
worktree_root: Option<PathBuf>,
|
|
/// Override the recorded hostname (defaults to `gethostname(2)`).
|
|
#[arg(long)]
|
|
hostname: Option<String>,
|
|
/// Overwrite an existing config file.
|
|
#[arg(long)]
|
|
force: bool,
|
|
/// Disable interactive prompts (errors if any required field is missing).
|
|
#[arg(long)]
|
|
non_interactive: bool,
|
|
}
|
|
|
|
#[tokio::main]
|
|
async fn main() -> ExitCode {
|
|
let cli = Cli::parse();
|
|
let filter = EnvFilter::try_from_default_env().unwrap_or_else(|_| EnvFilter::new("info"));
|
|
tracing_subscriber::fmt().with_env_filter(filter).init();
|
|
|
|
let result: Result<(), Box<dyn Error>> = match cli.command.unwrap_or(Command::Run) {
|
|
Command::Run => run(cli.config).await,
|
|
Command::Configure(args) => configure(cli.config, args),
|
|
};
|
|
|
|
match result {
|
|
Ok(()) => ExitCode::SUCCESS,
|
|
Err(e) => {
|
|
tracing::error!(error = %e, "maestrod failed");
|
|
eprintln!("maestrod: {e}");
|
|
ExitCode::FAILURE
|
|
}
|
|
}
|
|
}
|
|
|
|
async fn run(config_override: Option<PathBuf>) -> Result<(), Box<dyn Error>> {
|
|
let config_path: PathBuf = match config_override {
|
|
Some(p) => p,
|
|
None => default_config_path()?,
|
|
};
|
|
let config = load_config(&config_path, EnvOverrides::from_env())?;
|
|
tracing::info!(
|
|
daemon_id = %config.daemon_id,
|
|
registry = %config.registry_url,
|
|
bind = %config.bind_addr,
|
|
"loaded config"
|
|
);
|
|
|
|
let _ = default_state_dir(); // surface XDG diagnostics early but don't override
|
|
std::fs::create_dir_all(config.sidecar_dir())?;
|
|
std::fs::create_dir_all(config.fifo_dir())?;
|
|
std::fs::create_dir_all(&config.worktree_root)?;
|
|
|
|
let sidecar = SidecarStore::new(config.sidecar_dir());
|
|
let worktree_mgr = WorktreeManager::new(config.worktree_root.clone());
|
|
let tmux = Tmux::new();
|
|
let manager = SessionManager::new(
|
|
config.daemon_id.clone(),
|
|
tmux,
|
|
sidecar,
|
|
worktree_mgr,
|
|
config.fifo_dir(),
|
|
);
|
|
|
|
let recovered = manager.recover().await?;
|
|
tracing::info!(recovered, "adopted existing tmux sessions");
|
|
manager.start_liveness_watcher(DEFAULT_LIVENESS_INTERVAL);
|
|
|
|
let verifier = JwtVerifier::new(&config.token, &config.daemon_id);
|
|
let router = attach::router(manager.clone(), verifier);
|
|
|
|
let listener = TcpListener::bind(config.bind_addr).await?;
|
|
let bound = listener.local_addr()?;
|
|
tracing::info!(addr = %bound, "attach WS listening");
|
|
|
|
let client = RegistryClient::new(
|
|
config.registry_url.clone(),
|
|
config.daemon_id.clone(),
|
|
config.hostname.clone(),
|
|
config.daemon_url.clone(),
|
|
config.token.clone(),
|
|
manager.clone(),
|
|
);
|
|
|
|
tokio::spawn(async move { client.run().await });
|
|
|
|
let shutdown = async {
|
|
let _ = tokio::signal::ctrl_c().await;
|
|
tracing::info!("ctrl-c received — shutting down");
|
|
};
|
|
|
|
axum::serve(listener, router)
|
|
.with_graceful_shutdown(shutdown)
|
|
.await?;
|
|
Ok(())
|
|
}
|
|
|
|
fn configure(config_override: Option<PathBuf>, args: ConfigureCmd) -> Result<(), Box<dyn Error>> {
|
|
let path: PathBuf = match config_override {
|
|
Some(p) => p,
|
|
None => default_config_path()?,
|
|
};
|
|
let inputs = ConfigureInputs {
|
|
registry_url: args.registry_url,
|
|
daemon_url: args.daemon_url,
|
|
token: args.token,
|
|
daemon_id: args.daemon_id,
|
|
bind_addr: args.bind_addr,
|
|
state_dir: args.state_dir,
|
|
worktree_root: args.worktree_root,
|
|
hostname: args.hostname,
|
|
};
|
|
let written = run_configure(&path, inputs, !args.non_interactive, args.force)?;
|
|
eprintln!("wrote {}", written.display());
|
|
Ok(())
|
|
}
|