ci / rust (push) Failing after 2m51s
`PairAttachVerifier` now stores `allow_inbound` behind `Arc<RwLock<_>>` so clones share the same set. Two triggers re-read the unified config file and swap it atomically: - SIGHUP — `systemctl --user reload maestrod`, or any `kill -HUP`. The installer's user unit now sets `ExecReload=/bin/kill -HUP $MAINPID`. - `POST /api/policy/reload` — used by `maestro policy reload`. The CLI reads `[daemon].bind_addr` from the unified config (default 7070) and POSTs to `http://127.0.0.1:<port>`. No PID lookup required. Also adds `maestro policy show [--json]` and `GET /api/policy` for "did my edit get picked up?" debugging. A broken mid-edit config logs an error and leaves the previously-effective list in place rather than locking everyone out. In-flight attaches keep their existing connection — revocation requires killing the session, as spec'd. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
230 lines
7.8 KiB
Rust
230 lines
7.8 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, local_api, policy, run_configure,
|
|
spawn_session_publisher, spawn_sighup_listener, ConfigureInputs, EnvOverrides, JwtVerifier,
|
|
LocalEventBus, PairAttachVerifier, PolicyState, 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 unified Maestro config-file path (default `~/.config/maestro/config.toml`).
|
|
#[arg(long, global = true, env = "MAESTRO_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/maestro/config.toml` interactively or from flags.
|
|
Configure(ConfigureCmd),
|
|
}
|
|
|
|
#[derive(Debug, clap::Args)]
|
|
struct ConfigureCmd {
|
|
/// Registry base URL (e.g. `https://maestro.example.com`). The daemon
|
|
/// derives its WS endpoint by scheme-swapping and appending `/daemon`.
|
|
#[arg(long)]
|
|
registry_url: Option<String>,
|
|
/// Reachable URL clients dial for this daemon's attach WS.
|
|
#[arg(long)]
|
|
daemon_url: Option<String>,
|
|
/// Shared token (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 = match config.tmux_tmpdir.clone() {
|
|
Some(p) => Tmux::new().with_tmpdir(p),
|
|
None => Tmux::new(),
|
|
};
|
|
let manager = SessionManager::new_with_replay(
|
|
config.daemon_id.clone(),
|
|
tmux,
|
|
sidecar,
|
|
worktree_mgr,
|
|
config.fifo_dir(),
|
|
config.pty_replay_bytes,
|
|
);
|
|
|
|
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 pair_verifier = PairAttachVerifier::new(
|
|
&config.token,
|
|
&config.daemon_id,
|
|
config.allow_inbound.iter().cloned(),
|
|
);
|
|
|
|
// Daemon-local event bus (NAP-248): own session events + peer catalog
|
|
// deltas funnel through here for `WS /api/events` subscribers.
|
|
let events = LocalEventBus::new();
|
|
spawn_session_publisher(manager.clone(), events.clone());
|
|
|
|
// Build the registry client first so we can hand its catalog mirror to
|
|
// the local-API state — both halves share the same Arc<Mutex<…>>. Hand
|
|
// the event bus to the catalog mirror so peer deltas fan out too.
|
|
let client = RegistryClient::new_with_bus(
|
|
config.registry_url.clone(),
|
|
config.daemon_id.clone(),
|
|
config.hostname.clone(),
|
|
config.daemon_url.clone(),
|
|
config.token.clone(),
|
|
manager.clone(),
|
|
Some(events.clone()),
|
|
)
|
|
.with_perimeter(config.perimeter_id.clone(), config.private_addr.clone());
|
|
let catalog = client.catalog();
|
|
|
|
let local_state = local_api::state_for(
|
|
manager.clone(),
|
|
config.hostname.clone(),
|
|
config.daemon_url.clone(),
|
|
catalog.clone(),
|
|
events,
|
|
);
|
|
let broker_state = local_api::BrokerState {
|
|
manager: manager.clone(),
|
|
catalog,
|
|
broker: client.broker(),
|
|
self_daemon_id: std::sync::Arc::new(config.daemon_id.clone()),
|
|
self_perimeter_id: config.perimeter_id.clone().map(std::sync::Arc::new),
|
|
};
|
|
// NAP-237: hot-reload `[daemon.policy].allow_inbound` via SIGHUP or
|
|
// POST /api/policy/reload. Both swap the same verifier instance.
|
|
let policy_state = PolicyState {
|
|
verifier: pair_verifier.clone(),
|
|
config_path: std::sync::Arc::new(config_path.clone()),
|
|
};
|
|
spawn_sighup_listener(policy_state.clone());
|
|
|
|
let router = attach::router(manager.clone(), verifier, pair_verifier)
|
|
.merge(local_api::router(local_state))
|
|
.merge(local_api::broker_router(broker_state))
|
|
.merge(policy::router(policy_state));
|
|
|
|
let listener = TcpListener::bind(config.bind_addr).await?;
|
|
let bound = listener.local_addr()?;
|
|
tracing::info!(addr = %bound, "attach WS listening");
|
|
|
|
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(())
|
|
}
|