Files
skyg-linux-tracker/src/main.rs
T

241 lines
7.9 KiB
Rust

//! `slinuxm` entry point: parse CLI, load layered config, dispatch.
use std::net::IpAddr;
use std::path::PathBuf;
use std::net::SocketAddr;
use anyhow::{Context, Result};
use clap::{Parser, Subcommand};
use tokio_util::sync::CancellationToken;
use skyg_linux_tracker::auth::tokens::{self, TokenCmd};
use skyg_linux_tracker::config::{CliOverrides, Config};
use skyg_linux_tracker::peers::cli::{self, PeerCmd};
use skyg_linux_tracker::peers::registry::PeersReloader;
use skyg_linux_tracker::peers::PeerRegistry;
use skyg_linux_tracker::state::AppState;
use skyg_linux_tracker::{db, server, telemetry, tls};
#[derive(Debug, Parser)]
#[command(name = "slinuxm", version, about = "Read-only Linux system monitor")]
struct Cli {
/// Config file (default: /etc/skyg-linux-tracker.toml if present).
#[arg(long, global = true, env = "SKYG_CONFIG")]
config: Option<PathBuf>,
/// Print the effective merged configuration and exit.
#[arg(long, global = true)]
print_config: bool,
/// Listen address (server.bind).
#[arg(long, global = true)]
bind: Option<IpAddr>,
/// Listen port (server.port).
#[arg(long, global = true)]
port: Option<u16>,
/// Enable or disable auth (auth.enabled).
#[arg(long, global = true, value_name = "BOOL")]
auth_enabled: Option<bool>,
/// SQLite token database (auth.db_path).
#[arg(long, global = true)]
db_path: Option<PathBuf>,
/// Docker socket (sources.docker_socket).
#[arg(long, global = true)]
docker_socket: Option<PathBuf>,
/// Journal namespace (sources.journal_namespace).
#[arg(long, global = true)]
journal_namespace: Option<String>,
/// Enable or disable OTel export (otel.enabled).
#[arg(long, global = true, value_name = "BOOL")]
otel_enabled: Option<bool>,
/// OTLP endpoint (otel.endpoint).
#[arg(long, global = true)]
otel_endpoint: Option<String>,
#[command(subcommand)]
command: Option<Command>,
}
#[derive(Debug, Subcommand)]
enum Command {
/// Run the server (default).
Serve,
/// Manage API access tokens.
Token {
#[command(subcommand)]
cmd: TokenCmd,
},
/// Inspect configured peers (read-only).
Peer {
#[command(subcommand)]
cmd: PeerCmd,
},
}
impl Cli {
fn overrides(&self) -> CliOverrides {
CliOverrides {
bind: self.bind,
port: self.port,
auth_enabled: self.auth_enabled,
db_path: self.db_path.clone(),
docker_socket: self.docker_socket.clone(),
journal_namespace: self.journal_namespace.clone(),
otel_enabled: self.otel_enabled,
otel_endpoint: self.otel_endpoint.clone(),
}
}
}
#[tokio::main]
async fn main() -> Result<()> {
let cli = Cli::parse();
let config = Config::load(cli.config.as_deref(), &cli.overrides())?;
if cli.print_config {
print!(
"{}",
config.to_toml_redacted().context("serializing config")?
);
return Ok(());
}
let overrides = cli.overrides();
let config_path = cli.config.clone();
match cli.command.unwrap_or(Command::Serve) {
Command::Serve => serve(config, config_path, overrides).await,
Command::Token { cmd } => tokens::run(cmd, &config).await,
Command::Peer { cmd } => cli::run(cmd, &config).await,
}
}
/// Upper bounds for shutdown phases (the OTel flush adds up to 5s per
/// provider, so the unit uses TimeoutStopSec=30).
const DRAIN_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(10);
const EXPORTER_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(10);
async fn serve(
config: Config,
config_path: Option<PathBuf>,
overrides: CliOverrides,
) -> Result<()> {
// Install SIGHUP handling before anything else: the default action would
// terminate the process, with or without TLS.
let hup = tokio::signal::unix::signal(tokio::signal::unix::SignalKind::hangup())
.context("installing SIGHUP handler")?;
let guard = telemetry::init(&config).context("initialising telemetry")?;
let db = if config.auth.enabled {
Some(db::open(&config).await?)
} else {
tracing::warn!("auth is disabled: all endpoints are open (loopback only)");
None
};
let addr = SocketAddr::new(config.server.bind, config.server.port);
// TLS is optional: nothing from the tls module runs unless enabled.
let tls = if config.server.tls.enabled {
let cert = tls::ReloadableCert::load(&config.server.tls)
.context("loading TLS certificate and key")?;
Some((tls::acceptor(cert.clone())?, cert))
} else {
if !config.server.bind.is_loopback() {
tracing::warn!(
bind = %config.server.bind,
"listening on a non-loopback address without TLS: bearer tokens travel in cleartext (set server.tls.enabled or terminate TLS in front)"
);
}
None
};
let listener = tokio::net::TcpListener::bind(addr)
.await
.with_context(|| format!("binding {addr}"))?;
let shutdown = CancellationToken::new();
let peers_config = config.peers.clone();
let mut state = AppState::live(config, db, shutdown.clone());
// A disabled peers section leaves `state.peers = None`: no routes, tools,
// tasks or metrics.
if peers_config.enabled {
state.peers = Some(
PeerRegistry::start(peers_config, shutdown.clone())
.context("starting peer registry")?,
);
}
let peers = state.peers.clone();
let exporters = telemetry::spawn_exporters(state.clone());
let pool = state.db.clone();
let app = server::build_router(state);
let reloader = peers
.as_ref()
.map(|registry| PeersReloader::new(registry.clone(), config_path, overrides));
tls::spawn_sighup_reload(
tls.as_ref().map(|(_, cert)| cert.clone()),
hup,
shutdown.clone(),
reloader,
);
let signal_token = shutdown.clone();
tokio::spawn(async move {
wait_for_signal().await;
tracing::info!("shutdown signal received");
signal_token.cancel();
});
// `serve_listener` returns once the shutdown token fires and connections
// drain. If the token has not fired it is a server error, so return
// immediately. Bound the drain so a stuck client cannot hang SIGTERM.
let acceptor = tls.map(|(acceptor, _)| acceptor);
let serving: std::pin::Pin<Box<dyn std::future::Future<Output = Result<()>> + Send>> =
Box::pin(server::serve_listener(
listener,
acceptor,
app,
shutdown.clone(),
server::Limits::default(),
));
tokio::pin!(serving);
let result = tokio::select! {
r = &mut serving => r,
_ = shutdown.cancelled() => {
match tokio::time::timeout(DRAIN_TIMEOUT, &mut serving).await {
Ok(r) => r,
Err(_) => {
tracing::warn!("graceful drain timed out; closing remaining connections");
Ok(())
}
}
}
};
// Reached on signal or server error: stop everything, then flush OTel.
shutdown.cancel();
if let Some(peers) = &peers {
peers.shutdown().await;
}
let join_all = async {
for h in exporters {
let _ = h.await;
}
};
if tokio::time::timeout(EXPORTER_TIMEOUT, join_all)
.await
.is_err()
{
tracing::warn!("exporter tasks did not stop in time");
}
guard.shutdown().await;
if let Some(pool) = pool {
pool.close().await;
}
result
}
async fn wait_for_signal() {
use tokio::signal::unix::{signal, SignalKind};
let mut term = signal(SignalKind::terminate()).expect("SIGTERM handler");
tokio::select! {
_ = term.recv() => {}
_ = tokio::signal::ctrl_c() => {}
}
}