diff --git a/src/api/docker.rs b/src/api/docker.rs new file mode 100644 index 0000000..9e6cd3f --- /dev/null +++ b/src/api/docker.rs @@ -0,0 +1,3 @@ +//! GET /api/v1/docker/* handlers (WS-E) +//! +//! Placeholder created in P0 so the owning workstream only edits its own files. diff --git a/src/api/journal.rs b/src/api/journal.rs new file mode 100644 index 0000000..02faf40 --- /dev/null +++ b/src/api/journal.rs @@ -0,0 +1,3 @@ +//! GET /api/v1/journal and /journal/follow handlers (WS-E) +//! +//! Placeholder created in P0 so the owning workstream only edits its own files. diff --git a/src/api/mod.rs b/src/api/mod.rs new file mode 100644 index 0000000..a246258 --- /dev/null +++ b/src/api/mod.rs @@ -0,0 +1,18 @@ +//! REST layer (WS-E owns `src/api/`). +//! +//! STUB: signature is final. Uses axum 0.8 `{name}` path syntax. The router +//! contains `/api/v1/*` only; `/healthz`, auth and `/mcp` are merged by +//! `main.rs` (P3 I1) so `/healthz` stays public. + +pub mod docker; +pub mod journal; +pub mod systemd; + +use axum::Router; + +use crate::state::AppState; + +/// Routes under `/api/v1`, already bound to `state`. +pub fn router(_state: AppState) -> Router { + todo!("WS-E E1") +} diff --git a/src/api/systemd.rs b/src/api/systemd.rs new file mode 100644 index 0000000..5cd6eed --- /dev/null +++ b/src/api/systemd.rs @@ -0,0 +1,3 @@ +//! GET /api/v1/systemd/* handlers (WS-E) +//! +//! Placeholder created in P0 so the owning workstream only edits its own files. diff --git a/src/auth/mod.rs b/src/auth/mod.rs new file mode 100644 index 0000000..9f823f0 --- /dev/null +++ b/src/auth/mod.rs @@ -0,0 +1,40 @@ +//! Bearer-token auth (WS-D owns `src/auth/`). +//! +//! STUB: signature is final. Failures respond `401` with +//! `WWW-Authenticate: Bearer` and the standard JSON error body (DEC-4), for +//! both REST and `/mcp`. Apply the layer to the protected router only. + +pub mod tokens; + +use std::convert::Infallible; + +use axum::extract::{Request, State}; +use axum::middleware::{self, Next}; +use axum::response::Response; +use axum::routing::Route; +use tower::{Layer, Service}; + +use crate::state::AppState; + +/// Verify `Authorization: Bearer ` (sha256 + indexed lookup). +/// When `config.auth.enabled` is false this passes requests through. +async fn require_token(State(_state): State, _req: Request, _next: Next) -> Response { + todo!("WS-D D5") +} + +/// Layer for `Router::layer` on the protected router (`/api/v1`, `/mcp`). +pub fn layer( + state: AppState, +) -> impl Layer< + Route, + Service = impl Service + + Clone + + Send + + Sync + + 'static, +> + Clone + + Send + + Sync + + 'static { + middleware::from_fn_with_state(state, require_token) +} diff --git a/src/auth/tokens.rs b/src/auth/tokens.rs new file mode 100644 index 0000000..8bb17db --- /dev/null +++ b/src/auth/tokens.rs @@ -0,0 +1,28 @@ +//! Token CRUD and the `slinuxm token` CLI (WS-D owns this file). +//! +//! STUB: `TokenCmd` and `run` signatures are final. Tokens have the prefix +//! `slinuxm_`, 32 random bytes, only the sha256 hash is stored, and the +//! plaintext is printed once on create. + +use anyhow::Result; +use clap::Subcommand; + +use crate::config::Config; + +#[derive(Debug, Clone, Subcommand)] +pub enum TokenCmd { + /// Create a token and print it once. + Create { + /// Unique token name. + name: String, + }, + /// List tokens (never prints secrets). + List, + /// Revoke a token by name. + Revoke { name: String }, +} + +/// Execute a token subcommand against the DB at `config.auth.db_path`. +pub async fn run(_cmd: TokenCmd, _config: &Config) -> Result<()> { + todo!("WS-D D3/D4") +} diff --git a/src/config.rs b/src/config.rs new file mode 100644 index 0000000..9bfa739 --- /dev/null +++ b/src/config.rs @@ -0,0 +1,398 @@ +//! Layered configuration. +//! +//! Precedence, lowest to highest: built-in defaults, TOML file, `SKYG_*` +//! environment variables (`__` separates nesting, e.g. `SKYG_SERVER__PORT`), +//! CLI overrides. +//! +//! No field is an `Option` so the effective config serializes to TOML. +//! An empty string or empty list means "unset". + +use std::collections::BTreeMap; +use std::net::{IpAddr, Ipv4Addr}; +use std::path::{Path, PathBuf}; + +use figment::providers::{Env, Format, Serialized, Toml}; +use figment::Figment; +use serde::{Deserialize, Serialize}; + +/// Default config file location, used only when it exists and `--config` is absent. +pub const DEFAULT_CONFIG_PATH: &str = "/etc/skyg-linux-tracker.toml"; +/// Environment variable prefix. +pub const ENV_PREFIX: &str = "SKYG_"; + +#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)] +#[serde(default)] +pub struct Config { + pub server: ServerConfig, + pub auth: AuthConfig, + pub otel: OtelConfig, + pub sources: SourcesConfig, + pub limits: LimitsConfig, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +#[serde(default)] +pub struct ServerConfig { + /// Listen address. Non-loopback requires `auth.enabled = true`. + pub bind: IpAddr, + pub port: u16, + /// Extra `Host` header values accepted on `/mcp`, added to the defaults + /// (loopback names plus `bind`). + pub allowed_hosts: Vec, + /// Extra `Origin` values accepted on `/mcp`, added to the defaults + /// (loopback origins plus `bind`). Entries include a scheme. + pub allowed_origins: Vec, +} + +impl Default for ServerConfig { + fn default() -> Self { + Self { + bind: IpAddr::V4(Ipv4Addr::LOCALHOST), + port: 9109, + allowed_hosts: Vec::new(), + allowed_origins: Vec::new(), + } + } +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +#[serde(default)] +pub struct AuthConfig { + pub enabled: bool, + pub db_path: PathBuf, +} + +impl Default for AuthConfig { + fn default() -> Self { + Self { + enabled: true, + db_path: PathBuf::from("/var/lib/skyg-linux-tracker/db.sqlite"), + } + } +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)] +pub enum OtelProtocol { + #[default] + #[serde(rename = "grpc")] + Grpc, + #[serde(rename = "http/protobuf")] + HttpProtobuf, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +#[serde(default)] +pub struct OtelConfig { + pub enabled: bool, + pub endpoint: String, + pub protocol: OtelProtocol, + pub service_name: String, + /// Extra OTLP headers or gRPC metadata (for example `authorization`). + pub headers: BTreeMap, + pub export_unit_metrics: bool, + pub export_logs: bool, + pub metrics_interval_secs: u64, + pub logs: OtelLogsConfig, + pub metrics: OtelMetricsConfig, +} + +impl Default for OtelConfig { + fn default() -> Self { + Self { + enabled: false, + endpoint: "http://localhost:4317".into(), + protocol: OtelProtocol::Grpc, + service_name: "skyg-linux-tracker".into(), + headers: BTreeMap::new(), + export_unit_metrics: true, + export_logs: false, + metrics_interval_secs: 30, + logs: OtelLogsConfig::default(), + metrics: OtelMetricsConfig::default(), + } + } +} + +/// Which journal units / containers feed OTel logs. Empty means all. +#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)] +#[serde(default)] +pub struct OtelLogsConfig { + pub journal_units: Vec, + pub docker_containers: Vec, +} + +/// Glob allowlists for exported metrics. +/// +/// Empty `units` means `*.service` and `*.timer` (DEC-7). Empty `containers` +/// means all containers. +#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)] +#[serde(default)] +pub struct OtelMetricsConfig { + pub units: Vec, + pub containers: Vec, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +#[serde(default)] +pub struct SourcesConfig { + pub docker_socket: PathBuf, + /// Journal namespace. Empty means the default journal. + pub journal_namespace: String, +} + +impl Default for SourcesConfig { + fn default() -> Self { + Self { + docker_socket: PathBuf::from("/var/run/docker.sock"), + journal_namespace: String::new(), + } + } +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +#[serde(default)] +pub struct LimitsConfig { + /// Maximum journal lines per snapshot or MCP call. + pub max_lines: usize, + /// Maximum container log lines (`tail`). + pub max_tail: usize, + /// Maximum duration of a bounded follow, in seconds. + pub max_follow_secs: u64, +} + +impl Default for LimitsConfig { + fn default() -> Self { + Self { + max_lines: 1000, + max_tail: 1000, + max_follow_secs: 60, + } + } +} + +#[derive(Debug, thiserror::Error)] +pub enum ConfigError { + #[error("config file not found: {0}")] + MissingFile(PathBuf), + #[error("invalid configuration: {0}")] + Load(Box), + #[error("invalid configuration: {0}")] + Invalid(String), +} + +impl From for ConfigError { + fn from(e: figment::Error) -> Self { + Self::Load(Box::new(e)) + } +} + +/// Highest-precedence layer. Only `Some` fields are applied. +#[derive(Debug, Clone, Default)] +pub struct CliOverrides { + pub bind: Option, + pub port: Option, + pub auth_enabled: Option, + pub db_path: Option, + pub docker_socket: Option, + pub journal_namespace: Option, + pub otel_enabled: Option, + pub otel_endpoint: Option, +} + +impl CliOverrides { + fn apply(&self, mut fig: Figment) -> Figment { + fn put(fig: Figment, key: &str, v: &Option) -> Figment { + match v { + Some(v) => fig.merge(Serialized::default(key, v)), + None => fig, + } + } + fig = put(fig, "server.bind", &self.bind); + fig = put(fig, "server.port", &self.port); + fig = put(fig, "auth.enabled", &self.auth_enabled); + fig = put(fig, "auth.db_path", &self.db_path); + fig = put(fig, "sources.docker_socket", &self.docker_socket); + fig = put(fig, "sources.journal_namespace", &self.journal_namespace); + fig = put(fig, "otel.enabled", &self.otel_enabled); + fig = put(fig, "otel.endpoint", &self.otel_endpoint); + fig + } +} + +impl Config { + /// Build the merged config. + /// + /// `file`: explicit `--config` path (must exist). When `None`, the default + /// path is read only if present. + pub fn load(file: Option<&Path>, cli: &CliOverrides) -> Result { + let mut fig = Figment::from(Serialized::defaults(Config::default())); + match file { + Some(p) => { + if !p.exists() { + return Err(ConfigError::MissingFile(p.to_path_buf())); + } + fig = fig.merge(Toml::file(p)); + } + None => { + let p = Path::new(DEFAULT_CONFIG_PATH); + if p.exists() { + fig = fig.merge(Toml::file(p)); + } + } + } + fig = fig.merge(Env::prefixed(ENV_PREFIX).split("__")); + fig = cli.apply(fig); + let cfg: Config = fig.extract()?; + cfg.validate()?; + Ok(cfg) + } + + /// Cross-field validation. + pub fn validate(&self) -> Result<(), ConfigError> { + if !self.auth.enabled && !self.server.bind.is_loopback() { + return Err(ConfigError::Invalid(format!( + "auth.enabled = false is only allowed on a loopback bind address (server.bind = {})", + self.server.bind + ))); + } + if self.limits.max_lines == 0 + || self.limits.max_tail == 0 + || self.limits.max_follow_secs == 0 + { + return Err(ConfigError::Invalid( + "limits.* must be greater than zero".into(), + )); + } + if self.otel.metrics_interval_secs == 0 { + return Err(ConfigError::Invalid( + "otel.metrics_interval_secs must be greater than zero".into(), + )); + } + Ok(()) + } + + /// Effective config as TOML, with OTLP header values redacted. + pub fn to_toml_redacted(&self) -> Result { + let mut c = self.clone(); + for v in c.otel.headers.values_mut() { + *v = "***".into(); + } + toml::to_string_pretty(&c) + } +} + +#[cfg(test)] +#[allow(clippy::result_large_err)] // figment::Jail closures return figment::Error +mod tests { + use super::*; + use figment::Jail; + + fn load(file: Option<&str>, cli: &CliOverrides) -> Result { + Config::load(file.map(Path::new), cli) + } + + #[test] + fn defaults_only() { + Jail::expect_with(|_| { + let c = load(None, &CliOverrides::default()).unwrap(); + assert_eq!(c, Config::default()); + assert_eq!(c.server.port, 9109); + assert!(c.auth.enabled); + assert_eq!(c.limits.max_lines, 1000); + assert_eq!(c.limits.max_follow_secs, 60); + Ok(()) + }); + } + + #[test] + fn file_overrides_defaults() { + Jail::expect_with(|jail| { + jail.create_file( + "c.toml", + r#" + [server] + port = 8000 + [otel.headers] + authorization = "Bearer x" + [otel.metrics] + units = ["nginx.service"] + [limits] + max_lines = 50 + "#, + )?; + let c = load(Some("c.toml"), &CliOverrides::default()).unwrap(); + assert_eq!(c.server.port, 8000); + assert_eq!(c.otel.headers["authorization"], "Bearer x"); + assert_eq!(c.otel.metrics.units, vec!["nginx.service"]); + assert_eq!(c.limits.max_lines, 50); + assert_eq!(c.limits.max_tail, 1000); + Ok(()) + }); + } + + #[test] + fn env_overrides_file() { + Jail::expect_with(|jail| { + jail.create_file("c.toml", "[server]\nport = 8000\n")?; + jail.set_env("SKYG_SERVER__PORT", "8100"); + jail.set_env("SKYG_LIMITS__MAX_TAIL", "7"); + let c = load(Some("c.toml"), &CliOverrides::default()).unwrap(); + assert_eq!(c.server.port, 8100); + assert_eq!(c.limits.max_tail, 7); + Ok(()) + }); + } + + #[test] + fn cli_overrides_env() { + Jail::expect_with(|jail| { + jail.create_file("c.toml", "[server]\nport = 8000\n")?; + jail.set_env("SKYG_SERVER__PORT", "8100"); + let cli = CliOverrides { + port: Some(8200), + ..Default::default() + }; + let c = load(Some("c.toml"), &cli).unwrap(); + assert_eq!(c.server.port, 8200); + Ok(()) + }); + } + + #[test] + fn auth_off_with_public_bind_is_rejected() { + Jail::expect_with(|jail| { + jail.set_env("SKYG_AUTH__ENABLED", "false"); + jail.set_env("SKYG_SERVER__BIND", "0.0.0.0"); + assert!(matches!( + load(None, &CliOverrides::default()), + Err(ConfigError::Invalid(_)) + )); + // Loopback with auth off is fine. + jail.set_env("SKYG_SERVER__BIND", "127.0.0.1"); + assert!(load(None, &CliOverrides::default()).is_ok()); + Ok(()) + }); + } + + #[test] + fn missing_explicit_file_is_error() { + Jail::expect_with(|_| { + assert!(matches!( + load(Some("nope.toml"), &CliOverrides::default()), + Err(ConfigError::MissingFile(_)) + )); + Ok(()) + }); + } + + #[test] + fn toml_roundtrip_and_redaction() { + let mut c = Config::default(); + c.otel + .headers + .insert("authorization".into(), "secret".into()); + let s = c.to_toml_redacted().unwrap(); + assert!(!s.contains("secret")); + assert!(s.contains("port = 9109")); + } +} diff --git a/src/db.rs b/src/db.rs new file mode 100644 index 0000000..757dd4a --- /dev/null +++ b/src/db.rs @@ -0,0 +1,14 @@ +//! SQLite pool for access tokens (WS-D owns this file). +//! +//! STUB: signature is final. Use runtime queries (DEC-3), WAL mode and a busy +//! timeout, create the directory `0700`, run embedded migrations. + +use anyhow::Result; +use sqlx::SqlitePool; + +use crate::config::Config; + +/// Open (creating if needed) `config.auth.db_path` and migrate. +pub async fn open(_config: &Config) -> Result { + todo!("WS-D D1") +} diff --git a/src/error.rs b/src/error.rs new file mode 100644 index 0000000..f47a762 --- /dev/null +++ b/src/error.rs @@ -0,0 +1,135 @@ +//! Application error type shared by every surface. +//! +//! Sources return `AppError`; REST renders it through [`IntoResponse`], MCP +//! through `From for rmcp::ErrorData`. + +use axum::http::{header, HeaderValue, StatusCode}; +use axum::response::{IntoResponse, Response}; +use axum::Json; +use serde::Serialize; + +#[derive(Debug, Clone, thiserror::Error)] +pub enum AppError { + /// Unknown unit, container, route target. + #[error("not found: {0}")] + NotFound(String), + /// Invalid input (bad unit name, out-of-range limit, bad priority). + #[error("bad request: {0}")] + BadRequest(String), + /// Missing, malformed, unknown or revoked bearer token. + #[error("unauthorized: {0}")] + Unauthorized(String), + /// A backend (D-Bus, journald, Docker socket, DB) is absent or denied. + #[error("unavailable: {0}")] + Unavailable(String), + /// Anything else. Details are logged, not necessarily exposed. + #[error("internal error: {0}")] + Internal(String), +} + +pub type AppResult = Result; + +impl AppError { + /// Stable machine-readable code used in REST bodies and MCP error data. + pub fn code(&self) -> &'static str { + match self { + Self::NotFound(_) => "not_found", + Self::BadRequest(_) => "bad_request", + Self::Unauthorized(_) => "unauthorized", + Self::Unavailable(_) => "unavailable", + Self::Internal(_) => "internal", + } + } + + pub fn status(&self) -> StatusCode { + match self { + Self::NotFound(_) => StatusCode::NOT_FOUND, + Self::BadRequest(_) => StatusCode::BAD_REQUEST, + Self::Unauthorized(_) => StatusCode::UNAUTHORIZED, + Self::Unavailable(_) => StatusCode::SERVICE_UNAVAILABLE, + Self::Internal(_) => StatusCode::INTERNAL_SERVER_ERROR, + } + } + + /// The bare message without the variant prefix. + pub fn message(&self) -> &str { + match self { + Self::NotFound(m) + | Self::BadRequest(m) + | Self::Unauthorized(m) + | Self::Unavailable(m) + | Self::Internal(m) => m, + } + } +} + +/// REST error body: `{"error": {"code": "...", "message": "..."}}`. +#[derive(Debug, Serialize)] +pub struct ErrorBody<'a> { + pub error: ErrorDetail<'a>, +} + +#[derive(Debug, Serialize)] +pub struct ErrorDetail<'a> { + pub code: &'a str, + pub message: &'a str, +} + +impl IntoResponse for AppError { + fn into_response(self) -> Response { + let body = ErrorBody { + error: ErrorDetail { + code: self.code(), + message: self.message(), + }, + }; + let mut resp = (self.status(), Json(body)).into_response(); + if matches!(self, AppError::Unauthorized(_)) { + resp.headers_mut() + .insert(header::WWW_AUTHENTICATE, HeaderValue::from_static("Bearer")); + } + resp + } +} + +impl From for rmcp::ErrorData { + fn from(err: AppError) -> Self { + let data = Some(serde_json::json!({ "code": err.code() })); + let msg = err.message().to_owned(); + match err { + AppError::NotFound(_) => rmcp::ErrorData::resource_not_found(msg, data), + AppError::BadRequest(_) => rmcp::ErrorData::invalid_params(msg, data), + AppError::Unauthorized(_) => rmcp::ErrorData::invalid_request(msg, data), + AppError::Unavailable(_) | AppError::Internal(_) => { + rmcp::ErrorData::internal_error(msg, data) + } + } + } +} + +impl From for AppError { + fn from(err: sqlx::Error) -> Self { + AppError::Internal(format!("database: {err}")) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn status_and_code() { + let e = AppError::NotFound("x".into()); + assert_eq!(e.status(), StatusCode::NOT_FOUND); + assert_eq!(e.code(), "not_found"); + let r = AppError::Unauthorized("no".into()).into_response(); + assert_eq!(r.status(), StatusCode::UNAUTHORIZED); + assert!(r.headers().contains_key(header::WWW_AUTHENTICATE)); + } + + #[test] + fn mcp_mapping() { + let e: rmcp::ErrorData = AppError::BadRequest("bad".into()).into(); + assert_eq!(e.message, "bad"); + } +} diff --git a/src/lib.rs b/src/lib.rs new file mode 100644 index 0000000..696e188 --- /dev/null +++ b/src/lib.rs @@ -0,0 +1,14 @@ +//! skyg-linux-tracker: read-only Linux system monitor. +//! +//! A library plus the `slinuxm` binary, so module items are not flagged as +//! dead code while the workstreams fill in their stubs. + +pub mod api; +pub mod auth; +pub mod config; +pub mod db; +pub mod error; +pub mod mcp; +pub mod sources; +pub mod state; +pub mod telemetry; diff --git a/src/main.rs b/src/main.rs new file mode 100644 index 0000000..6c8214a --- /dev/null +++ b/src/main.rs @@ -0,0 +1,107 @@ +//! `slinuxm` entry point: parse CLI, load layered config, dispatch. +//! +//! Phase 3 (I1) replaces the body of `serve` with the real wiring. + +use std::net::IpAddr; +use std::path::PathBuf; + +use anyhow::{bail, Context, Result}; +use clap::{Parser, Subcommand}; + +use skyg_linux_tracker::auth::tokens::{self, TokenCmd}; +use skyg_linux_tracker::config::{CliOverrides, Config}; + +#[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, + + /// Print the effective merged configuration and exit. + #[arg(long, global = true)] + print_config: bool, + + /// Listen address (server.bind). + #[arg(long, global = true)] + bind: Option, + /// Listen port (server.port). + #[arg(long, global = true)] + port: Option, + /// Enable or disable auth (auth.enabled). + #[arg(long, global = true, value_name = "BOOL")] + auth_enabled: Option, + /// SQLite token database (auth.db_path). + #[arg(long, global = true)] + db_path: Option, + /// Docker socket (sources.docker_socket). + #[arg(long, global = true)] + docker_socket: Option, + /// Journal namespace (sources.journal_namespace). + #[arg(long, global = true)] + journal_namespace: Option, + /// Enable or disable OTel export (otel.enabled). + #[arg(long, global = true, value_name = "BOOL")] + otel_enabled: Option, + /// OTLP endpoint (otel.endpoint). + #[arg(long, global = true)] + otel_endpoint: Option, + + #[command(subcommand)] + command: Option, +} + +#[derive(Debug, Subcommand)] +enum Command { + /// Run the server (default). + Serve, + /// Manage API access tokens. + Token { + #[command(subcommand)] + cmd: TokenCmd, + }, +} + +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(()); + } + + match cli.command.unwrap_or(Command::Serve) { + Command::Serve => serve(config).await, + Command::Token { cmd } => tokens::run(cmd, &config).await, + } +} + +async fn serve(config: Config) -> Result<()> { + // Phase 3 (I1): telemetry::init, db::open, AppState::live, router wiring, + // graceful shutdown. Until then, config validation is all `serve` does. + bail!( + "server wiring is not implemented yet (P3 I1); config is valid, bind = {}:{}", + config.server.bind, + config.server.port + ) +} diff --git a/src/mcp/mod.rs b/src/mcp/mod.rs new file mode 100644 index 0000000..09c8685 --- /dev/null +++ b/src/mcp/mod.rs @@ -0,0 +1,39 @@ +//! MCP server (WS-F owns `src/mcp/`). +//! +//! STUB: signatures are final. Pinned `rmcp` 3.5.1 validates `Host` and +//! `Origin` itself via `StreamableHttpServerConfig::with_allowed_hosts` and +//! `with_allowed_origins` (DEC-8). Feed it loopback names, `server.bind`, +//! `server.allowed_hosts` and `server.allowed_origins`. + +pub mod prompts; + +use rmcp::handler::server::ServerHandler; +use rmcp::model::ServerConfig; +use rmcp::transport::streamable_http_server::session::local::LocalSessionManager; +use rmcp::transport::streamable_http_server::StreamableHttpService; + +use crate::state::AppState; + +/// Per-session MCP handler. Holds the shared state. +#[derive(Clone)] +pub struct TrackerService { + #[allow(dead_code)] + state: AppState, +} + +impl TrackerService { + pub fn new(state: AppState) -> Self { + Self { state } + } +} + +impl ServerHandler for TrackerService { + fn get_info(&self) -> ServerConfig { + todo!("WS-F F4") + } +} + +/// Tower service to mount at `/mcp` with `nest_service`. +pub fn service(_state: AppState) -> StreamableHttpService { + todo!("WS-F F8") +} diff --git a/src/mcp/prompts.rs b/src/mcp/prompts.rs new file mode 100644 index 0000000..88b4756 --- /dev/null +++ b/src/mcp/prompts.rs @@ -0,0 +1,3 @@ +//! MCP prompts: diagnose_unit, container_health_report (WS-F) +//! +//! Placeholder created in P0 so the owning workstream only edits its own files. diff --git a/src/sources/docker.rs b/src/sources/docker.rs new file mode 100644 index 0000000..c68f169 --- /dev/null +++ b/src/sources/docker.rs @@ -0,0 +1,46 @@ +//! Docker source over the unix socket via `bollard` (WS-C owns this file). +//! +//! STUB: signatures are final, bodies are `todo!()`. +//! Notes for WS-C: build the client lazily. A missing or denied socket maps to +//! `AppError::Unavailable` per request and never fails startup (review G9). + +use async_trait::async_trait; +use tokio::sync::mpsc; +use tokio_util::sync::CancellationToken; + +use super::{ContainerStatus, ContainerSummary, DockerSource, LogLine, LogOptions}; +use crate::config::Config; +use crate::error::AppError; + +pub struct BollardDocker {} + +impl BollardDocker { + /// Must not fail or block. Reads `sources.docker_socket` and + /// `limits.max_tail` from `config`. Follow tasks stop on `shutdown`. + pub fn new(_config: &Config, _shutdown: CancellationToken) -> Self { + Self {} + } +} + +#[async_trait] +impl DockerSource for BollardDocker { + async fn ps(&self, _all: bool) -> Result, AppError> { + todo!("WS-C C2") + } + + async fn container_status(&self, _name: &str) -> Result { + todo!("WS-C C3") + } + + async fn logs(&self, _name: &str, _opts: &LogOptions) -> Result, AppError> { + todo!("WS-C C4") + } + + async fn follow_logs( + &self, + _name: &str, + _opts: &LogOptions, + ) -> Result, AppError> { + todo!("WS-C C4") + } +} diff --git a/src/sources/fake.rs b/src/sources/fake.rs new file mode 100644 index 0000000..e9ed6a1 --- /dev/null +++ b/src/sources/fake.rs @@ -0,0 +1,354 @@ +//! Fixture-backed in-memory sources for tests and for developing surfaces +//! without systemd, journald or Docker (DEC-2). +//! +//! `fake_state(config)` returns a ready `AppState`. Each fake exposes its +//! fixtures as public fields so tests can replace them. + +use std::sync::Arc; + +use async_trait::async_trait; +use jiff::Timestamp; +use tokio::sync::mpsc; +use tokio_util::sync::CancellationToken; + +use super::{ + clamp_count, ContainerStatus, ContainerSummary, DockerSource, JournalEntry, JournalQuery, + JournalSource, LogLine, LogOptions, LogStream, Priority, SystemdSource, TimerInfo, UnitStatus, + UnitSummary, +}; +use crate::config::Config; +use crate::error::AppError; +use crate::state::AppState; + +fn ts(s: &str) -> Timestamp { + s.parse().expect("valid fixture timestamp") +} + +/// An `AppState` backed by the fakes, without a DB pool. +pub fn fake_state(config: Config) -> AppState { + let shutdown = CancellationToken::new(); + AppState { + config: Arc::new(config), + systemd: Arc::new(FakeSystemd::default()), + journal: Arc::new(FakeJournal::new(shutdown.clone())), + docker: Arc::new(FakeDocker::new(shutdown.clone())), + db: None, + shutdown, + } +} + +// ---------------------------------------------------------------- systemd + +pub struct FakeSystemd { + pub units: Vec, + pub timers: Vec, +} + +impl Default for FakeSystemd { + fn default() -> Self { + let unit = |name: &str, desc: &str, active: &str, sub: &str, service: bool| UnitStatus { + name: name.into(), + description: desc.into(), + load_state: "loaded".into(), + active_state: active.into(), + sub_state: sub.into(), + fragment_path: Some(format!("/etc/systemd/system/{name}")), + unit_file_state: Some("enabled".into()), + active_enter_time: Some(ts("2026-10-15T08:00:00Z")), + active_exit_time: None, + main_pid: service.then_some(1234), + exec_main_status: service.then_some(if active == "failed" { 1 } else { 0 }), + n_restarts: service.then_some(if active == "failed" { 5 } else { 0 }), + result: service.then(|| { + if active == "failed" { + "exit-code" + } else { + "success" + } + .into() + }), + }; + Self { + units: vec![ + unit("sshd.service", "OpenSSH Daemon", "active", "running", true), + unit( + "nginx.service", + "Nginx web server", + "failed", + "failed", + true, + ), + unit( + "logrotate.timer", + "Daily rotation of log files", + "active", + "waiting", + false, + ), + ], + timers: vec![TimerInfo { + name: "logrotate.timer".into(), + unit: "logrotate.service".into(), + active_state: "active".into(), + next_elapse: Some(ts("2026-10-16T00:00:00Z")), + last_trigger: Some(ts("2026-10-15T00:00:00Z")), + }], + } + } +} + +#[async_trait] +impl SystemdSource for FakeSystemd { + async fn list_units(&self, state: Option<&str>) -> Result, AppError> { + Ok(self + .units + .iter() + .filter(|u| state.is_none_or(|s| u.active_state == s)) + .map(|u| UnitSummary { + name: u.name.clone(), + description: u.description.clone(), + load_state: u.load_state.clone(), + active_state: u.active_state.clone(), + sub_state: u.sub_state.clone(), + }) + .collect()) + } + + async fn list_timers(&self) -> Result, AppError> { + Ok(self.timers.clone()) + } + + async fn unit_status(&self, name: &str) -> Result { + self.units + .iter() + .find(|u| u.name == name) + .cloned() + .ok_or_else(|| AppError::NotFound(format!("unit {name}"))) + } +} + +// ---------------------------------------------------------------- journal + +pub struct FakeJournal { + pub entries: Vec, + shutdown: CancellationToken, +} + +impl FakeJournal { + pub fn new(shutdown: CancellationToken) -> Self { + let e = |t: &str, p: Priority, unit: &str, msg: &str| JournalEntry { + timestamp: ts(t), + priority: Some(p), + unit: Some(unit.into()), + identifier: Some(unit.trim_end_matches(".service").into()), + pid: Some(1234), + hostname: Some("fakehost".into()), + message: msg.into(), + cursor: Some(format!("s={t}")), + }; + Self { + entries: vec![ + e( + "2026-10-15T08:00:01Z", + Priority::Info, + "sshd.service", + "Server listening on 0.0.0.0 port 22.", + ), + e( + "2026-10-15T08:05:00Z", + Priority::Err, + "nginx.service", + "bind() to 0.0.0.0:80 failed", + ), + e( + "2026-10-15T08:05:01Z", + Priority::Crit, + "nginx.service", + "nginx.service: Failed with result 'exit-code'.", + ), + ], + shutdown, + } + } + + fn matching(&self, q: &JournalQuery) -> Vec { + self.entries + .iter() + .filter(|e| { + q.unit + .as_deref() + .is_none_or(|u| e.unit.as_deref() == Some(u)) + }) + .filter(|e| { + q.priority + .is_none_or(|p| e.priority.is_some_and(|ep| ep <= p)) + }) + .filter(|e| q.since.is_none_or(|s| e.timestamp >= s)) + .cloned() + .collect() + } +} + +#[async_trait] +impl JournalSource for FakeJournal { + async fn query(&self, q: &JournalQuery) -> Result, AppError> { + let all = self.matching(q); + let n = clamp_count(q.lines, usize::MAX); + let skip = all.len().saturating_sub(n); + Ok(all.into_iter().skip(skip).collect()) + } + + /// Sends the matching backlog, then idles until the receiver is dropped + /// or shutdown fires. + async fn follow(&self, q: &JournalQuery) -> Result, AppError> { + let backlog = self.query(q).await?; + let (tx, rx) = mpsc::channel(64); + let shutdown = self.shutdown.clone(); + tokio::spawn(async move { + for e in backlog { + if tx.send(e).await.is_err() { + return; + } + } + tokio::select! { + () = tx.closed() => {} + () = shutdown.cancelled() => {} + } + }); + Ok(rx) + } +} + +// ----------------------------------------------------------------- docker + +pub struct FakeDocker { + pub containers: Vec, + pub logs: Vec, + shutdown: CancellationToken, +} + +impl FakeDocker { + pub fn new(shutdown: CancellationToken) -> Self { + let c = |id: &str, name: &str, state: &str, health: Option<&str>| ContainerStatus { + summary: ContainerSummary { + id: id.into(), + name: name.into(), + image: format!("{name}:latest"), + state: state.into(), + health: health.map(Into::into), + created: Some(ts("2026-10-14T00:00:00Z")), + started_at: Some(ts("2026-10-14T00:00:05Z")), + uptime_seconds: (state == "running").then_some(3600), + restart_count: Some(0), + }, + finished_at: None, + exit_code: None, + oom_killed: Some(false), + health_output: health.map(|h| format!("probe says {h}")), + }; + Self { + containers: vec![ + c("aaaa1111", "web", "running", Some("healthy")), + c("bbbb2222", "db", "running", None), + c("cccc3333", "job", "exited", None), + ], + logs: vec![ + LogLine { + stream: LogStream::Stdout, + ts: Some(ts("2026-10-15T09:00:00Z")), + message: "ready".into(), + }, + LogLine { + stream: LogStream::Stderr, + ts: Some(ts("2026-10-15T09:00:01Z")), + message: "warning: slow query".into(), + }, + ], + shutdown, + } + } + + fn find(&self, name: &str) -> Result<&ContainerStatus, AppError> { + self.containers + .iter() + .find(|c| c.summary.name == name || c.summary.id == name) + .ok_or_else(|| AppError::NotFound(format!("container {name}"))) + } +} + +#[async_trait] +impl DockerSource for FakeDocker { + async fn ps(&self, all: bool) -> Result, AppError> { + Ok(self + .containers + .iter() + .filter(|c| all || c.summary.state == "running") + .map(|c| c.summary.clone()) + .collect()) + } + + async fn container_status(&self, name: &str) -> Result { + self.find(name).cloned() + } + + async fn logs(&self, name: &str, opts: &LogOptions) -> Result, AppError> { + self.find(name)?; + let n = clamp_count(opts.tail, usize::MAX); + let skip = self.logs.len().saturating_sub(n); + Ok(self.logs.iter().skip(skip).cloned().collect()) + } + + async fn follow_logs( + &self, + name: &str, + opts: &LogOptions, + ) -> Result, AppError> { + let backlog = self.logs(name, opts).await?; + let (tx, rx) = mpsc::channel(64); + let shutdown = self.shutdown.clone(); + tokio::spawn(async move { + for l in backlog { + if tx.send(l).await.is_err() { + return; + } + } + tokio::select! { + () = tx.closed() => {} + () = shutdown.cancelled() => {} + } + }); + Ok(rx) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[tokio::test] + async fn fakes_behave() { + let st = fake_state(Config::default()); + assert_eq!( + st.systemd.list_units(Some("failed")).await.unwrap().len(), + 1 + ); + assert!(matches!( + st.systemd.unit_status("nope.service").await, + Err(AppError::NotFound(_)) + )); + let q = JournalQuery { + priority: Some(Priority::Err), + ..Default::default() + }; + assert_eq!(st.journal.query(&q).await.unwrap().len(), 2); + assert_eq!(st.docker.ps(false).await.unwrap().len(), 2); + let mut rx = st + .docker + .follow_logs("web", &LogOptions::default()) + .await + .unwrap(); + assert!(rx.recv().await.is_some()); + st.shutdown.cancel(); + while rx.recv().await.is_some() {} + } +} diff --git a/src/sources/journal.rs b/src/sources/journal.rs new file mode 100644 index 0000000..91be47d --- /dev/null +++ b/src/sources/journal.rs @@ -0,0 +1,36 @@ +//! journald source over libsystemd (WS-B owns this file). +//! +//! STUB: signatures are final, bodies are `todo!()`. +//! Notes for WS-B: `systemd::journal::Journal` is neither `Send` nor `Sync`. +//! Open it inside `spawn_blocking` and never move it across threads or hold it +//! across an `.await`. Namespaces need `OpenOptions::open_namespace` +//! (feature `systemd_v245`, already enabled). + +use async_trait::async_trait; +use tokio::sync::mpsc; +use tokio_util::sync::CancellationToken; + +use super::{JournalEntry, JournalQuery, JournalSource}; +use crate::config::Config; +use crate::error::AppError; + +pub struct SdJournal {} + +impl SdJournal { + /// Must not fail or block. Reads `sources.journal_namespace` and + /// `limits.max_lines` from `config`. Follow tasks stop on `shutdown`. + pub fn new(_config: &Config, _shutdown: CancellationToken) -> Self { + Self {} + } +} + +#[async_trait] +impl JournalSource for SdJournal { + async fn query(&self, _q: &JournalQuery) -> Result, AppError> { + todo!("WS-B B2") + } + + async fn follow(&self, _q: &JournalQuery) -> Result, AppError> { + todo!("WS-B B3") + } +} diff --git a/src/sources/mod.rs b/src/sources/mod.rs new file mode 100644 index 0000000..87f9420 --- /dev/null +++ b/src/sources/mod.rs @@ -0,0 +1,381 @@ +//! Source traits and shared DTOs. +//! +//! `sources` is the only layer that talks to D-Bus, journald or Docker. REST, +//! MCP and OTel are thin projections over these traits. All reads are live. +//! +//! Conventions: +//! - Timestamps are `jiff::Timestamp`, serialized as RFC3339. +//! - Follow methods return a `tokio::sync::mpsc::Receiver`. The producer stops +//! when the receiver is dropped or the shutdown token fires. Errors that +//! occur after the stream started end the stream and are logged. +//! - Missing or denied backends map to `AppError::Unavailable`. + +pub mod docker; +pub mod fake; +pub mod journal; +pub mod systemd; + +use std::fmt; +use std::str::FromStr; + +use async_trait::async_trait; +use jiff::Timestamp; +use schemars::JsonSchema; +use serde::{Deserialize, Deserializer, Serialize, Serializer}; +use tokio::sync::mpsc; + +use crate::error::AppError; + +// ---------------------------------------------------------------- systemd + +/// One row of `ListUnits`. +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)] +pub struct UnitSummary { + /// Full unit name, e.g. `sshd.service`. + pub name: String, + pub description: String, + /// `loaded`, `not-found`, `masked`, `error`, ... + pub load_state: String, + /// `active`, `inactive`, `failed`, `activating`, `deactivating`, `reloading`. + pub active_state: String, + /// Type-specific detail, e.g. `running`, `exited`, `dead`, `waiting`. + pub sub_state: String, +} + +/// Detailed status of one unit. Service-only fields are `None` for other types. +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)] +pub struct UnitStatus { + pub name: String, + pub description: String, + pub load_state: String, + pub active_state: String, + pub sub_state: String, + /// Path to the unit file, if any. + pub fragment_path: Option, + /// `enabled`, `disabled`, `static`, ... if known. + pub unit_file_state: Option, + pub active_enter_time: Option, + pub active_exit_time: Option, + /// Service only. + pub main_pid: Option, + /// Service only: exit status of the main process. + pub exec_main_status: Option, + /// Service only: automatic restart count. + pub n_restarts: Option, + /// Service only: `success`, `exit-code`, `signal`, `timeout`, ... + pub result: Option, +} + +/// A `.timer` unit and its schedule. +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)] +pub struct TimerInfo { + /// Timer unit name, e.g. `logrotate.timer`. + pub name: String, + /// Unit the timer activates. + pub unit: String, + pub active_state: String, + /// `None` when not scheduled (property is 0 or `u64::MAX`). + pub next_elapse: Option, + pub last_trigger: Option, +} + +#[async_trait] +pub trait SystemdSource: Send + Sync { + /// List loaded units. `state`, when given, filters on `active_state`. + async fn list_units(&self, state: Option<&str>) -> Result, AppError>; + /// List `.timer` units with their schedule. + async fn list_timers(&self) -> Result, AppError>; + /// Status of one unit. Unknown unit is `AppError::NotFound`. + async fn unit_status(&self, name: &str) -> Result; +} + +// ---------------------------------------------------------------- journal + +/// Syslog severity, 0 (most severe) to 7. +#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)] +#[repr(u8)] +pub enum Priority { + Emerg = 0, + Alert = 1, + Crit = 2, + Err = 3, + Warning = 4, + Notice = 5, + Info = 6, + Debug = 7, +} + +impl Priority { + pub const ALL: [Priority; 8] = [ + Priority::Emerg, + Priority::Alert, + Priority::Crit, + Priority::Err, + Priority::Warning, + Priority::Notice, + Priority::Info, + Priority::Debug, + ]; + + pub fn as_u8(self) -> u8 { + self as u8 + } + + pub fn name(self) -> &'static str { + match self { + Priority::Emerg => "emerg", + Priority::Alert => "alert", + Priority::Crit => "crit", + Priority::Err => "err", + Priority::Warning => "warning", + Priority::Notice => "notice", + Priority::Info => "info", + Priority::Debug => "debug", + } + } + + pub fn from_u8(n: u8) -> Option { + Self::ALL.get(usize::from(n)).copied() + } +} + +impl fmt::Display for Priority { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.write_str(self.name()) + } +} + +impl FromStr for Priority { + type Err = AppError; + + /// Accepts `0`..`7` or a name (`err`, `error`, `warn`, `warning`, ...). + fn from_str(s: &str) -> Result { + let t = s.trim().to_ascii_lowercase(); + if let Ok(n) = t.parse::() { + return Priority::from_u8(n) + .ok_or_else(|| AppError::BadRequest(format!("priority {n} out of range 0-7"))); + } + Ok(match t.as_str() { + "emerg" | "emergency" | "panic" => Priority::Emerg, + "alert" => Priority::Alert, + "crit" | "critical" => Priority::Crit, + "err" | "error" => Priority::Err, + "warning" | "warn" => Priority::Warning, + "notice" => Priority::Notice, + "info" => Priority::Info, + "debug" => Priority::Debug, + _ => return Err(AppError::BadRequest(format!("unknown priority '{s}'"))), + }) + } +} + +impl Serialize for Priority { + fn serialize(&self, s: S) -> Result { + s.serialize_str(self.name()) + } +} + +impl<'de> Deserialize<'de> for Priority { + fn deserialize>(d: D) -> Result { + #[derive(Deserialize)] + #[serde(untagged)] + enum Raw { + Num(u8), + Str(String), + } + match Raw::deserialize(d)? { + Raw::Num(n) => Priority::from_u8(n) + .ok_or_else(|| serde::de::Error::custom(format!("priority {n} out of range 0-7"))), + Raw::Str(s) => s + .parse() + .map_err(|e: AppError| serde::de::Error::custom(e.message().to_owned())), + } + } +} + +impl JsonSchema for Priority { + fn schema_name() -> std::borrow::Cow<'static, str> { + "Priority".into() + } + + fn json_schema(_: &mut schemars::SchemaGenerator) -> schemars::Schema { + schemars::json_schema!({ + "description": "Syslog severity. Name (emerg, alert, crit, err, warning, notice, info, debug) or number 0-7. Serialized as the name.", + "oneOf": [ + { "type": "string", "enum": ["emerg", "alert", "crit", "err", "warning", "notice", "info", "debug"] }, + { "type": "integer", "minimum": 0, "maximum": 7 } + ] + }) + } +} + +/// Journal filter, shared by snapshot and follow. +#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize, JsonSchema)] +#[serde(default)] +pub struct JournalQuery { + /// Match `_SYSTEMD_UNIT` (or `UNIT` for coredump-style entries). Unit names are validated. + pub unit: Option, + /// Include entries at this severity or more severe (numerically `<=`). + pub priority: Option, + /// Maximum entries (snapshot) or backlog entries (follow). `None` means the + /// default of 100. Always capped by `limits.max_lines`. + pub lines: Option, + /// Only entries at or after this time. + pub since: Option, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)] +pub struct JournalEntry { + pub timestamp: Timestamp, + pub priority: Option, + /// `_SYSTEMD_UNIT`, falling back to `UNIT`. + pub unit: Option, + /// `SYSLOG_IDENTIFIER`. + pub identifier: Option, + pub pid: Option, + pub hostname: Option, + /// `MESSAGE`, lossily decoded as UTF-8. + pub message: String, + /// Opaque journal cursor. + pub cursor: Option, +} + +#[async_trait] +pub trait JournalSource: Send + Sync { + /// Snapshot: the most recent matching entries, in chronological order. + async fn query(&self, q: &JournalQuery) -> Result, AppError>; + /// Backlog (`q.lines`) followed by new entries as they arrive. + /// + /// The returned receiver ends when the producer stops: receiver dropped, + /// shutdown token fired, or a journal error. + async fn follow(&self, q: &JournalQuery) -> Result, AppError>; +} + +// ----------------------------------------------------------------- docker + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)] +pub struct ContainerSummary { + /// Full container id. + pub id: String, + /// Name without the leading slash. + pub name: String, + pub image: String, + /// `created`, `running`, `paused`, `restarting`, `exited`, `dead`. + pub state: String, + /// Health check status: `healthy`, `unhealthy`, `starting`. `None` if no health check. + pub health: Option, + pub created: Option, + pub started_at: Option, + /// Seconds since `started_at`, for running containers. + pub uptime_seconds: Option, + pub restart_count: Option, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)] +pub struct ContainerStatus { + #[serde(flatten)] + pub summary: ContainerSummary, + pub finished_at: Option, + pub exit_code: Option, + pub oom_killed: Option, + /// Last health check output, if any. + pub health_output: Option, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, JsonSchema)] +#[serde(rename_all = "lowercase")] +pub enum LogStream { + Stdout, + Stderr, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)] +pub struct LogLine { + pub stream: LogStream, + /// Docker-provided timestamp, if available. + pub ts: Option, + pub message: String, +} + +/// Options for container log reads. +#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize, JsonSchema)] +#[serde(default)] +pub struct LogOptions { + /// Last N lines. `None` means the default of 100. Capped by `limits.max_tail`. + pub tail: Option, + pub since: Option, +} + +#[async_trait] +pub trait DockerSource: Send + Sync { + /// List containers. `all = false` returns running containers only. + async fn ps(&self, all: bool) -> Result, AppError>; + /// Status by name or id. Unknown is `AppError::NotFound`. + async fn container_status(&self, name: &str) -> Result; + /// Snapshot of the last `opts.tail` lines, chronological. + async fn logs(&self, name: &str, opts: &LogOptions) -> Result, AppError>; + /// Backlog (`opts.tail`) followed by new lines as they arrive. + async fn follow_logs( + &self, + name: &str, + opts: &LogOptions, + ) -> Result, AppError>; +} + +// ---------------------------------------------------------------- helpers + +/// Default value of `JournalQuery.lines` and `LogOptions.tail`. +pub const DEFAULT_LINES: usize = 100; + +/// Resolve a requested count against the default and the configured cap. +pub fn clamp_count(requested: Option, cap: usize) -> usize { + requested.unwrap_or(DEFAULT_LINES).min(cap) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn priority_parse() { + assert_eq!("err".parse::().unwrap(), Priority::Err); + assert_eq!("3".parse::().unwrap(), Priority::Err); + assert_eq!("WARN".parse::().unwrap(), Priority::Warning); + assert!("8".parse::().is_err()); + assert!("loud".parse::().is_err()); + } + + #[test] + fn priority_serde() { + assert_eq!(serde_json::to_string(&Priority::Crit).unwrap(), "\"crit\""); + assert_eq!( + serde_json::from_str::("4").unwrap(), + Priority::Warning + ); + assert_eq!( + serde_json::from_str::("\"info\"").unwrap(), + Priority::Info + ); + assert!(serde_json::from_str::("9").is_err()); + } + + #[test] + fn timestamps_are_rfc3339() { + let ts: Timestamp = "2026-10-15T12:00:00Z".parse().unwrap(); + let line = LogLine { + stream: LogStream::Stderr, + ts: Some(ts), + message: "x".into(), + }; + let v = serde_json::to_value(&line).unwrap(); + assert_eq!(v["ts"], "2026-10-15T12:00:00Z"); + assert_eq!(v["stream"], "stderr"); + } + + #[test] + fn clamp() { + assert_eq!(clamp_count(None, 1000), 100); + assert_eq!(clamp_count(Some(5000), 1000), 1000); + assert_eq!(clamp_count(None, 50), 50); + } +} diff --git a/src/sources/systemd.rs b/src/sources/systemd.rs new file mode 100644 index 0000000..4a3264c --- /dev/null +++ b/src/sources/systemd.rs @@ -0,0 +1,38 @@ +//! systemd source over D-Bus (WS-A owns this file). +//! +//! STUB: signatures are final, bodies are `todo!()`. +//! Notes for WS-A: use `zbus_systemd::systemd1::{ManagerProxy, UnitProxy, +//! ServiceProxy, TimerProxy}`. There is no `ListTimers` method; list `*.timer` +//! units and read `TimerProxy` properties (see plan/review.md R1, R2). + +use async_trait::async_trait; +use tokio_util::sync::CancellationToken; + +use super::{SystemdSource, TimerInfo, UnitStatus, UnitSummary}; +use crate::config::Config; +use crate::error::AppError; + +pub struct DbusSystemd {} + +impl DbusSystemd { + /// Must not fail or block: connect to the bus lazily on first use and map + /// connection errors to `AppError::Unavailable`. + pub fn new(_config: &Config, _shutdown: CancellationToken) -> Self { + Self {} + } +} + +#[async_trait] +impl SystemdSource for DbusSystemd { + async fn list_units(&self, _state: Option<&str>) -> Result, AppError> { + todo!("WS-A A2") + } + + async fn list_timers(&self) -> Result, AppError> { + todo!("WS-A A3") + } + + async fn unit_status(&self, _name: &str) -> Result { + todo!("WS-A A4") + } +} diff --git a/src/state.rs b/src/state.rs new file mode 100644 index 0000000..caa85d9 --- /dev/null +++ b/src/state.rs @@ -0,0 +1,38 @@ +//! Shared application state handed to every surface. + +use std::sync::Arc; + +use sqlx::SqlitePool; +use tokio_util::sync::CancellationToken; + +use crate::config::Config; +use crate::sources::{DockerSource, JournalSource, SystemdSource}; + +/// Cheap to clone. Every stream and background task must select on +/// `shutdown` so graceful shutdown cannot hang on open SSE connections. +#[derive(Clone)] +pub struct AppState { + pub config: Arc, + pub systemd: Arc, + pub journal: Arc, + pub docker: Arc, + /// `None` when auth is disabled. + pub db: Option, + pub shutdown: CancellationToken, +} + +impl AppState { + /// State backed by the real sources. Source constructors are lazy and + /// never fail, so a missing Docker socket does not prevent startup. + pub fn live(config: Config, db: Option, shutdown: CancellationToken) -> Self { + use crate::sources::{docker::BollardDocker, journal::SdJournal, systemd::DbusSystemd}; + Self { + systemd: Arc::new(DbusSystemd::new(&config, shutdown.clone())), + journal: Arc::new(SdJournal::new(&config, shutdown.clone())), + docker: Arc::new(BollardDocker::new(&config, shutdown.clone())), + config: Arc::new(config), + db, + shutdown, + } + } +} diff --git a/src/telemetry/logs_export.rs b/src/telemetry/logs_export.rs new file mode 100644 index 0000000..671cca7 --- /dev/null +++ b/src/telemetry/logs_export.rs @@ -0,0 +1,3 @@ +//! Journal and docker log fan-out to OTel logs (WS-G) +//! +//! Placeholder created in P0 so the owning workstream only edits its own files. diff --git a/src/telemetry/metrics_export.rs b/src/telemetry/metrics_export.rs new file mode 100644 index 0000000..d7b1243 --- /dev/null +++ b/src/telemetry/metrics_export.rs @@ -0,0 +1,3 @@ +//! Metrics poll loop and observable gauges (WS-G) +//! +//! Placeholder created in P0 so the owning workstream only edits its own files. diff --git a/src/telemetry/mod.rs b/src/telemetry/mod.rs new file mode 100644 index 0000000..7ce6333 --- /dev/null +++ b/src/telemetry/mod.rs @@ -0,0 +1,32 @@ +//! OpenTelemetry export (WS-G owns `src/telemetry/`). +//! +//! STUB: signatures are final. Pinned `opentelemetry-otlp` 0.33.1: use +//! `WithExportConfig::{with_endpoint, with_protocol}` plus +//! `WithHttpConfig::with_headers` (HashMap) or +//! `WithTonicConfig::with_metadata` (tonic `MetadataMap`). + +pub mod logs_export; +pub mod metrics_export; + +use anyhow::Result; +use tokio::task::JoinHandle; + +use crate::config::Config; +use crate::state::AppState; + +/// Flushes and shuts down providers on drop. +pub struct TelemetryGuard { + _private: (), +} + +/// Install the tracing subscriber and, when `config.otel.enabled`, the OTLP +/// providers. Must work (stderr logging only) when OTel is disabled. +pub fn init(_config: &Config) -> Result { + todo!("WS-G G1/G2") +} + +/// Start the metrics poll loop and log fan-out tasks. All tasks stop on +/// `state.shutdown`. Returns no handles when export is disabled. +pub fn spawn_exporters(_state: AppState) -> Vec> { + todo!("WS-G G3/G5") +}