diff --git a/.claude/rules/engine-async.md b/.claude/rules/engine-async.md index cb045b6..3ed1df6 100644 --- a/.claude/rules/engine-async.md +++ b/.claude/rules/engine-async.md @@ -15,7 +15,7 @@ paths: - Bloklayan I/O (sysfs/I2C/UART, dosya, senkron IPC), uzun CPU işleri ve SVM çağrıları `tokio::task::spawn_blocking` içinde çalışır. Async kodda `std::fs` ve `std::thread::sleep` kullanılmaz. - `std::sync::Mutex`/`RwLock` guard'ı `.await` boyunca tutulmaz. Kısa kritik bölüm → guard'ı düşür → sonra await. - Kanallar: sınırsız (`unbounded`) kanal yeni kodda kullanılmaz. Kapasiteyi ve dolu durumdaki davranışı (bekle / düşür / hata) açıkça seç. -- Yeni arka plan görevinin kapanış yolu olmalı. Not: şu an yalnız SIGINT dinleniyor (R-13). +- Yeni arka plan görevinin kapanış yolu olmalı. Main loop SIGINT, SIGTERM (`signal::TermSignal`, S-43) ve IPC `Shutdown` ile döngüden çıkar ve kapanış adımlarını koşar. ## Sürücüler (driver actor) - Sürücü hatası tüm actor'ü düşürmez; yeniden bağlanma ve backoff sürücünün içinde kalır (R-25). diff --git a/HowToUses/03_WEB_EDITOR.md b/HowToUses/03_WEB_EDITOR.md index 24893f1..0f03b58 100644 --- a/HowToUses/03_WEB_EDITOR.md +++ b/HowToUses/03_WEB_EDITOR.md @@ -19,7 +19,10 @@ bash tools/editor-dev.sh [device[:port]] The script checks the device (`/api/about`, whether the editor gate asks for a login) and starts the editor at `http://localhost:8091/`. Add a connection with the device user; leave `peer` empty (it defaults to the page origin). -With auth on, the device needs `--ws-allowed-origins http://localhost:8091`: +With auth on (DEPLOYMENT_CHECKLIST §7a), log in with the device's Sandstar +user; the login sets an `HttpOnly` session cookie for the page origin. The +device needs `--ws-allowed-origins http://localhost:8091` (or +`SANDSTAR_WS_ALLOWED_ORIGINS`): the editor's WebSockets, tree and file reads, and kit uploads (`PUT /file/*`) use the session cookie from the login and are checked against the page origin. Edits in the editor go to the running app on the device. diff --git a/crates/sandstar-cli/src/client.rs b/crates/sandstar-cli/src/client.rs index 25b21d7..ab8f488 100644 --- a/crates/sandstar-cli/src/client.rs +++ b/crates/sandstar-cli/src/client.rs @@ -4,6 +4,12 @@ use sandstar_ipc::protocol::{read_frame, write_frame}; use sandstar_ipc::types::{EngineCommand, EngineResponse}; use std::io; use std::net::TcpStream; +use std::time::Duration; + +/// Longest wait for the server, per read or write. Above the server's own +/// deadlines (5 s read, 10 s engine, 5 s write), so the server's error reply +/// arrives first; below it the CLI would give up on a busy but healthy engine. +const IO_TIMEOUT: Duration = Duration::from_secs(20); /// Send a command to the engine server and return the response. pub fn send_command(address: &str, cmd: &EngineCommand) -> io::Result { @@ -28,15 +34,22 @@ pub fn send_command(address: &str, cmd: &EngineCommand) -> io::Result io::Result { if !address.contains(':') { let stream = std::os::unix::net::UnixStream::connect(address)?; + stream.set_read_timeout(Some(IO_TIMEOUT))?; + stream.set_write_timeout(Some(IO_TIMEOUT))?; return Ok(ConnStream::Unix(stream)); } let stream = TcpStream::connect(address)?; + stream.set_read_timeout(Some(IO_TIMEOUT))?; + stream.set_write_timeout(Some(IO_TIMEOUT))?; Ok(ConnStream::Tcp(stream)) } #[cfg(not(unix))] fn connect(address: &str) -> io::Result { - TcpStream::connect(address) + let stream = TcpStream::connect(address)?; + stream.set_read_timeout(Some(IO_TIMEOUT))?; + stream.set_write_timeout(Some(IO_TIMEOUT))?; + Ok(stream) } // --- Platform-specific stream type --- diff --git a/crates/sandstar-ipc/src/protocol.rs b/crates/sandstar-ipc/src/protocol.rs index 2af7a2e..f66c98a 100644 --- a/crates/sandstar-ipc/src/protocol.rs +++ b/crates/sandstar-ipc/src/protocol.rs @@ -8,7 +8,7 @@ use serde::{de::DeserializeOwned, Serialize}; use std::io; /// Maximum frame size (1 MB). Prevents OOM from malformed length prefixes. -const MAX_FRAME_SIZE: u32 = 1_048_576; +pub const MAX_FRAME_SIZE: u32 = 1_048_576; /// Write a serializable value as a length-prefixed bincode frame. /// diff --git a/crates/sandstar-server/src/dispatch.rs b/crates/sandstar-server/src/dispatch.rs index 6ba6174..acf13d0 100644 --- a/crates/sandstar-server/src/dispatch.rs +++ b/crates/sandstar-server/src/dispatch.rs @@ -1,20 +1,19 @@ -//! Command dispatch: deserialize IPC commands, execute on engine, send response. +//! Command dispatch: run an IPC command on the engine (main loop side). +//! +//! The connection itself (framing, deadlines) lives in `crate::ipc` (R-28). -use std::io; use std::time::Instant; use sandstar_engine::{Engine, EngineValue}; use sandstar_hal::{HalDiagnostics, HalRead, HalWrite}; -use sandstar_ipc::protocol::{read_frame, write_frame}; use sandstar_ipc::types::*; use tracing::{debug, info, warn}; use crate::config::ServerConfig; use crate::history::HistoryStore; -use crate::ipc::Stream; use crate::reload; -/// Result of handling an IPC connection. +/// What the main loop must do after an IPC command. pub enum ConnectionResult { /// Normal command processed, continue accepting connections. Continue, @@ -24,19 +23,15 @@ pub enum ConnectionResult { PollNow, } -/// Handle a single IPC connection: read one command, dispatch, write response. -pub fn handle_connection( - mut stream: Stream, +/// Run one IPC command on the engine: what the main loop must do next, and +/// the reply for the client. +pub fn run( + cmd: EngineCommand, engine: &mut Engine, config: &ServerConfig, start_time: Instant, history_store: &HistoryStore, -) -> io::Result { - let cmd: EngineCommand = match read_frame(&mut stream)? { - Some(cmd) => cmd, - None => return Ok(ConnectionResult::Continue), // clean disconnect - }; - +) -> (ConnectionResult, EngineResponse) { debug!(?cmd, "received command"); crate::metrics::metrics() .ipc_requests @@ -47,10 +42,10 @@ pub fn handle_connection( EngineCommand::PollNow => ConnectionResult::PollNow, _ => ConnectionResult::Continue, }; - let response = execute(cmd, engine, config, start_time, history_store); - write_frame(&mut stream, &response)?; - - Ok(result) + ( + result, + execute(cmd, engine, config, start_time, history_store), + ) } /// Execute a command against the engine and produce a response. diff --git a/crates/sandstar-server/src/ipc.rs b/crates/sandstar-server/src/ipc.rs index 79f5911..9e8198b 100644 --- a/crates/sandstar-server/src/ipc.rs +++ b/crates/sandstar-server/src/ipc.rs @@ -2,10 +2,27 @@ //! //! On Unix: Unix domain sockets. //! On Windows: TCP on localhost (named pipes require winapi; TCP is simpler for dev). +//! +//! Connections are accepted and served on their own tasks, off the main loop +//! (R-28). A connection task reads one command frame, hands it to the main +//! loop over a channel, and writes the reply. Reading, getting the command to +//! and back from the engine, and writing each have a total deadline, so a slow +//! or stuck client never holds the engine, REST, SOX or the watchdog. On a +//! failure the client gets an `EngineResponse::Error` when it can still be +//! written. Wire format is unchanged: `[u32 LE length][bincode]`. use std::io; +use std::sync::atomic::{AtomicU64, Ordering}; +use std::sync::{Arc, Mutex}; use std::time::Duration; +use sandstar_ipc::protocol::MAX_FRAME_SIZE; +use sandstar_ipc::types::{EngineCommand, EngineResponse}; +use tokio::io::{AsyncRead, AsyncReadExt, AsyncWrite, AsyncWriteExt}; +use tokio::sync::{mpsc, oneshot, Semaphore}; +use tokio::time::{timeout, timeout_at, Instant}; +use tracing::{error, warn}; + // --- Platform abstraction --- /// Opaque listener type. @@ -17,10 +34,89 @@ pub type Listener = tokio::net::TcpListener; /// Opaque stream type. #[cfg(unix)] -pub type Stream = std::os::unix::net::UnixStream; +pub type Stream = tokio::net::UnixStream; #[cfg(not(unix))] -pub type Stream = std::net::TcpStream; +pub type Stream = tokio::net::TcpStream; + +/// Total time to read one command frame, and again to write the reply. +pub const IO_TIMEOUT: Duration = Duration::from_secs(5); + +/// Time for the command to reach the engine and its reply to come back +/// (queue wait included); as `EngineHandle`'s 10 s. +pub const REPLY_TIMEOUT: Duration = Duration::from_secs(10); + +/// Connections served at the same time; more get a "busy" reply. +pub const MAX_CONNECTIONS: usize = 4; + +/// How long `Shutdown` waits for its reply to be written before stopping. +pub const SHUTDOWN_REPLY_WAIT: Duration = Duration::from_secs(1); + +/// Pause after a failed `accept` (e.g. out of file descriptors). +const ACCEPT_BACKOFF: Duration = Duration::from_millis(100); + +/// Time for a short error reply on a failure path. +const ERROR_REPLY_TIMEOUT: Duration = Duration::from_secs(1); + +/// At most one log line per kind of IPC failure in this period. +const LOG_EVERY: Duration = Duration::from_secs(10); + +/// One command for the main loop. +pub struct IpcRequest { + pub cmd: EngineCommand, + /// The reply goes back to the connection task. + pub reply: oneshot::Sender, + /// Fires once the reply is written, so `Shutdown` can wait for it. + pub written: oneshot::Receiver<()>, +} + +impl IpcRequest { + /// The client's task has given up (deadline passed): do not run it. + pub fn abandoned(&self) -> bool { + self.reply.is_closed() + } +} + +/// Variant name of a command, for logs (no field values). +pub fn command_name(cmd: &EngineCommand) -> String { + let debug = format!("{cmd:?}"); + debug + .split(|c: char| !c.is_alphanumeric()) + .next() + .unwrap_or_default() + .to_string() +} + +/// Lets one log line through per `LOG_EVERY`, counting the rest. +struct LogLimit { + last: Mutex>, + suppressed: AtomicU64, +} + +impl LogLimit { + const fn new() -> Self { + Self { + last: Mutex::new(None), + suppressed: AtomicU64::new(0), + } + } + + /// `Some(n)`: log now; `n` lines were suppressed since the last one. + fn check(&self) -> Option { + let now = std::time::Instant::now(); + let mut last = self.last.lock().unwrap_or_else(|p| p.into_inner()); + if last.is_some_and(|t| now.duration_since(t) < LOG_EVERY) { + self.suppressed.fetch_add(1, Ordering::Relaxed); + return None; + } + *last = Some(now); + Some(self.suppressed.swap(0, Ordering::Relaxed)) + } +} + +static BUSY_LOG: LogLimit = LogLimit::new(); +static CONN_ERROR_LOG: LogLimit = LogLimit::new(); +static ACCEPT_ERROR_LOG: LogLimit = LogLimit::new(); /// Create the IPC listener. pub async fn create_listener(path: &str) -> io::Result { @@ -44,37 +140,204 @@ pub async fn create_listener(path: &str) -> io::Result { } } -/// Accept one connection, returning a synchronous stream for frame I/O. +/// Accept one connection. +pub async fn accept(listener: &Listener) -> io::Result { + let (stream, _addr) = listener.accept().await?; + Ok(stream) +} + +/// Accept connections until the main loop is gone, each served on its own task. +pub fn spawn_accept_loop( + listener: Listener, + tx: mpsc::Sender, + slots: Arc, +) -> tokio::task::JoinHandle<()> { + tokio::spawn(async move { + while !tx.is_closed() { + match accept(&listener).await { + Ok(stream) => spawn_connection(stream, tx.clone(), slots.clone()), + Err(e) => { + if let Some(n) = ACCEPT_ERROR_LOG.check() { + error!(err = %e, suppressed = n, "failed to accept IPC connection"); + } + tokio::time::sleep(ACCEPT_BACKOFF).await; + } + } + } + }) +} + +/// Serve `stream` on its own task if a connection slot is free; otherwise +/// tell the client the server is busy. +pub fn spawn_connection(stream: Stream, tx: mpsc::Sender, slots: Arc) { + let Ok(permit) = slots.try_acquire_owned() else { + if let Some(n) = BUSY_LOG.check() { + warn!( + max = MAX_CONNECTIONS, + suppressed = n, + "IPC: too many connections, refusing" + ); + } + tokio::spawn(async move { + let mut stream = stream; + reply_error(&mut stream, "busy: too many IPC connections, try again").await; + }); + return; + }; + tokio::spawn(async move { + let _permit = permit; + if let Err(e) = serve(stream, &tx, IO_TIMEOUT, REPLY_TIMEOUT).await { + if let Some(n) = CONN_ERROR_LOG.check() { + warn!(err = %e, suppressed = n, "IPC connection failed"); + } + } + }); +} + +/// Read one command, pass it to the main loop, write the reply. /// -/// We accept via tokio (async) then convert to std (sync) for the -/// blocking bincode read/write in the single-threaded runtime. -pub async fn accept(listener: &Listener) -> io::Result<(Stream, Vec, Vec)> { - #[cfg(unix)] - { - let (stream, _addr) = listener.accept().await?; - let std_stream = stream.into_std()?; - std_stream.set_nonblocking(false)?; - // Prevent a hung client from blocking the event loop + watchdog. - std_stream.set_read_timeout(Some(Duration::from_secs(5)))?; - Ok((std_stream, Vec::new(), Vec::new())) +/// A clean disconnect before any byte is `Ok`. Every step that waits on the +/// client or the main loop has a deadline; errors name the command and say +/// whether it ran. +pub async fn serve( + mut stream: S, + tx: &mpsc::Sender, + io_timeout: Duration, + reply_timeout: Duration, +) -> io::Result<()> +where + S: AsyncRead + AsyncWrite + Unpin, +{ + let cmd: EngineCommand = match timeout(io_timeout, read_frame(&mut stream)).await { + Err(_) => return Err(timed_out("client too slow sending the command")), + Ok(Err(e)) => { + if e.kind() == io::ErrorKind::InvalidData { + reply_error(&mut stream, &format!("bad command frame: {e}")).await; + } + return Err(e); + } + Ok(Ok(None)) => return Ok(()), + Ok(Ok(Some(cmd))) => cmd, + }; + let name = command_name(&cmd); + + // One deadline for queueing the command and getting its reply. + let deadline = Instant::now() + reply_timeout; + let (reply_tx, reply_rx) = oneshot::channel(); + let (written_tx, written_rx) = oneshot::channel(); + let request = IpcRequest { + cmd, + reply: reply_tx, + written: written_rx, + }; + match timeout_at(deadline, tx.send(request)).await { + Err(_) => { + reply_error(&mut stream, "engine busy: command not queued, not run").await; + return Err(timed_out(&format!("{name}: engine queue full, not run"))); + } + Ok(Err(_)) => { + reply_error(&mut stream, "server is stopping: command not run").await; + return Err(broken(&format!("{name}: engine loop has stopped, not run"))); + } + Ok(Ok(())) => {} } - #[cfg(not(unix))] - { - let (stream, _addr) = listener.accept().await?; - let std_stream = stream.into_std()?; - std_stream.set_nonblocking(false)?; - // Prevent a hung client from blocking the event loop + watchdog. - std_stream.set_read_timeout(Some(Duration::from_secs(5)))?; - Ok((std_stream, Vec::new(), Vec::new())) + // On timeout `reply_rx` is dropped here, so the main loop skips the + // command if it has not started it yet. + let response = match timeout_at(deadline, reply_rx).await { + Err(_) => { + reply_error( + &mut stream, + "timed out waiting for the engine: command not run", + ) + .await; + return Err(timed_out(&format!("{name}: engine did not answer in time"))); + } + Ok(Err(_)) => { + reply_error(&mut stream, "engine did not run the command").await; + return Err(broken(&format!("{name}: engine loop dropped the command"))); + } + Ok(Ok(r)) => r, + }; + + match timeout(io_timeout, write_frame(&mut stream, &response)).await { + Err(_) => { + return Err(timed_out(&format!( + "{name} ran, client too slow reading the reply" + ))) + } + Ok(Err(e)) => { + return Err(io::Error::new( + e.kind(), + format!("{name} ran, reply not delivered: {e}"), + )) + } + Ok(Ok(())) => {} + } + // Nobody waits unless the command was Shutdown. + let _ = written_tx.send(()); + Ok(()) +} + +/// Best effort: the connection is failing anyway. +async fn reply_error(stream: &mut S, msg: &str) { + let response = EngineResponse::Error(msg.to_string()); + let _ = timeout(ERROR_REPLY_TIMEOUT, write_frame(stream, &response)).await; +} + +fn timed_out(what: &str) -> io::Error { + io::Error::new(io::ErrorKind::TimedOut, what.to_string()) +} + +fn broken(what: &str) -> io::Error { + io::Error::new(io::ErrorKind::BrokenPipe, what.to_string()) +} + +/// Async version of `sandstar_ipc::protocol::read_frame`. `None` only when +/// the client closed before sending anything; a partial frame is an error. +async fn read_frame(reader: &mut R) -> io::Result> { + let mut len_buf = [0u8; 4]; + if reader.read(&mut len_buf[..1]).await? == 0 { + return Ok(None); + } + reader.read_exact(&mut len_buf[1..]).await?; + let len = u32::from_le_bytes(len_buf); + if len > MAX_FRAME_SIZE { + return Err(io::Error::new( + io::ErrorKind::InvalidData, + format!("frame too large: {len} bytes (max {MAX_FRAME_SIZE})"), + )); } + let mut payload = vec![0u8; len as usize]; + reader.read_exact(&mut payload).await?; + bincode::deserialize(&payload) + .map(Some) + .map_err(|e| io::Error::new(io::ErrorKind::InvalidData, e)) +} + +/// Async version of `sandstar_ipc::protocol::write_frame`. +async fn write_frame( + writer: &mut W, + value: &EngineResponse, +) -> io::Result<()> { + let payload = + bincode::serialize(value).map_err(|e| io::Error::new(io::ErrorKind::InvalidData, e))?; + let len = u32::try_from(payload.len()) + .map_err(|_| io::Error::new(io::ErrorKind::InvalidData, "reply too large"))?; + writer.write_all(&len.to_le_bytes()).await?; + writer.write_all(&payload).await?; + writer.flush().await } /// Clean up the socket file on shutdown (Unix only). pub fn cleanup(path: &str) { #[cfg(unix)] { - let _ = std::fs::remove_file(path); + if let Err(e) = std::fs::remove_file(path) { + if e.kind() != io::ErrorKind::NotFound { + warn!(err = %e, path, "failed to remove IPC socket file"); + } + } } #[cfg(not(unix))] @@ -86,6 +349,7 @@ pub fn cleanup(path: &str) { #[cfg(test)] mod tests { use super::*; + use tokio::io::duplex; // Tests run against the platform transport: a Unix socket file on Unix // (the production path on the device), TCP on localhost elsewhere. @@ -111,8 +375,8 @@ mod tests { (listener, addr) } - fn connect(target: &Target) -> Stream { - Stream::connect(target).unwrap() + async fn connect(target: &Target) -> Stream { + Stream::connect(target).await.unwrap() } fn cleanup_test(target: &Target) { @@ -122,6 +386,39 @@ mod tests { let _ = target; } + fn frame(cmd: &EngineCommand) -> Vec { + let mut buf = Vec::new(); + sandstar_ipc::protocol::write_frame(&mut buf, cmd).unwrap(); + buf + } + + async fn read_reply(r: &mut R) -> EngineResponse { + let mut len = [0u8; 4]; + r.read_exact(&mut len).await.unwrap(); + let mut body = vec![0u8; u32::from_le_bytes(len) as usize]; + r.read_exact(&mut body).await.unwrap(); + bincode::deserialize(&body).unwrap() + } + + fn error_text(r: &EngineResponse) -> &str { + match r { + EngineResponse::Error(s) => s, + _ => panic!("expected an error reply"), + } + } + + /// Stand-in for the main loop: answers every live command with `Ok`. + fn answer_all(mut rx: mpsc::Receiver) -> tokio::task::JoinHandle { + tokio::spawn(async move { + let mut n = 0; + while let Some(req) = rx.recv().await { + n += 1; + let _ = req.reply.send(EngineResponse::Ok); + } + n + }) + } + #[tokio::test] async fn test_create_listener() { let (_listener, target) = bind_test("create").await; @@ -136,26 +433,11 @@ mod tests { cleanup_test(&target); } - #[tokio::test] - async fn test_accept_sets_read_timeout() { - let (listener, target) = bind_test("timeout").await; - - // Connect a client - let _client = connect(&target); - - // Accept it on the server side - let (stream, _, _) = accept(&listener).await.unwrap(); - let timeout = stream.read_timeout().unwrap(); - assert_eq!(timeout, Some(Duration::from_secs(5))); - cleanup_test(&target); - } - #[test] fn test_cleanup_idempotent() { // Calling cleanup on a non-existent path should not panic cleanup("127.0.0.1:0"); cleanup("/tmp/nonexistent-sandstar-test-socket"); - // If we get here without panicking, the test passes } #[cfg(unix)] @@ -167,66 +449,280 @@ mod tests { assert!(!target.exists()); } - #[tokio::test] - async fn test_round_trip_frame() { - use sandstar_ipc::protocol::{read_frame, write_frame}; - use sandstar_ipc::types::{EngineCommand, EngineResponse}; + #[test] + fn test_command_name_has_no_field_values() { + let cmd = EngineCommand::ReadChannel { channel: 1113 }; + assert_eq!(command_name(&cmd), "ReadChannel"); + assert_eq!(command_name(&EngineCommand::Status), "Status"); + } + #[tokio::test] + async fn test_round_trip_over_platform_socket() { let (listener, target) = bind_test("roundtrip").await; - let client_target = target.clone(); + let (tx, rx) = mpsc::channel(MAX_CONNECTIONS); + let main_loop = answer_all(rx); + let slots = Arc::new(Semaphore::new(MAX_CONNECTIONS)); + let accept_loop = spawn_accept_loop(listener, tx, slots); + + let mut c = connect(&target).await; + c.write_all(&frame(&EngineCommand::Status)).await.unwrap(); + assert!(matches!(read_reply(&mut c).await, EngineResponse::Ok)); + accept_loop.abort(); + let _ = accept_loop.await; + assert_eq!(main_loop.await.unwrap(), 1); + cleanup_test(&target); + } - // Client sends a command - let handle = std::thread::spawn(move || { - let mut client = connect(&client_target); - let cmd = EngineCommand::Status; - write_frame(&mut client, &cmd).unwrap(); + #[tokio::test(start_paused = true)] + async fn test_read_deadline_is_total_not_per_read() { + // One byte every 1 s: every single read is quick, the whole frame + // would finish at ~7 s. A per-read 5 s limit would let it through. + let (mut client, server) = duplex(64); + let (tx, mut rx) = mpsc::channel(1); + let start = Instant::now(); + let task = tokio::spawn(async move { serve(server, &tx, IO_TIMEOUT, REPLY_TIMEOUT).await }); + for b in frame(&EngineCommand::Status) { + if client.write_all(&[b]).await.is_err() { + break; + } + tokio::time::sleep(Duration::from_secs(1)).await; + } + let err = task.await.unwrap().unwrap_err(); + assert_eq!(err.kind(), io::ErrorKind::TimedOut); + let took = Instant::now() - start; + assert!( + took >= IO_TIMEOUT && took < IO_TIMEOUT + Duration::from_secs(2), + "{took:?}" + ); + assert!( + rx.try_recv().is_err(), + "an unfinished frame must not reach the engine" + ); + } - // Read back the response - let resp: EngineResponse = read_frame(&mut client).unwrap().unwrap(); - resp - }); + #[tokio::test(start_paused = true)] + async fn test_client_that_never_reads_the_reply_times_out() { + // A tiny pipe the client never drains: the reply cannot be written. + let (mut client, server) = duplex(8); + let (tx, mut rx) = mpsc::channel(1); + let task = tokio::spawn(async move { serve(server, &tx, IO_TIMEOUT, REPLY_TIMEOUT).await }); + client + .write_all(&frame(&EngineCommand::ListChannels)) + .await + .unwrap(); + let req = rx.recv().await.unwrap(); + let mut written = req.written; + let channels = (0..200) + .map(|i| sandstar_ipc::types::ChannelInfo { + id: i, + label: format!("channel {i}"), + channel_type: "Analog".into(), + direction: "In".into(), + enabled: true, + status: "Ok".into(), + raw: 0.0, + cur: 0.0, + }) + .collect(); + let _ = req.reply.send(EngineResponse::Channels(channels)); + let err = task.await.unwrap().unwrap_err(); + assert_eq!(err.kind(), io::ErrorKind::TimedOut); + assert!(err.to_string().contains("ListChannels ran"), "{err}"); + assert!(written.try_recv().is_err(), "no ack for an unwritten reply"); + let _ = client; // kept open, never read + } - // Server accepts and echoes back a response - let (mut stream, _, _) = accept(&listener).await.unwrap(); - let cmd: EngineCommand = sandstar_ipc::protocol::read_frame(&mut stream) - .unwrap() + #[tokio::test] + async fn test_written_ack_follows_the_reply() { + let (mut client, server) = duplex(1024); + let (tx, mut rx) = mpsc::channel(1); + let task = tokio::spawn(async move { serve(server, &tx, IO_TIMEOUT, REPLY_TIMEOUT).await }); + client + .write_all(&frame(&EngineCommand::Shutdown)) + .await .unwrap(); - assert!(matches!(cmd, EngineCommand::Status)); + let req = rx.recv().await.unwrap(); + let _ = req.reply.send(EngineResponse::Ok); + req.written.await.expect("ack after the reply is written"); + assert!(matches!(read_reply(&mut client).await, EngineResponse::Ok)); + task.await.unwrap().unwrap(); + } - let resp = EngineResponse::Ok; - sandstar_ipc::protocol::write_frame(&mut stream, &resp).unwrap(); + #[tokio::test(start_paused = true)] + async fn test_stuck_engine_times_out_and_the_command_is_abandoned() { + let (mut client, server) = duplex(1024); + let (tx, mut rx) = mpsc::channel(1); + let task = tokio::spawn(async move { serve(server, &tx, IO_TIMEOUT, REPLY_TIMEOUT).await }); + client + .write_all(&frame(&EngineCommand::Status)) + .await + .unwrap(); + let held = rx.recv().await.unwrap(); // never answered + assert!(!held.abandoned()); + let err = task.await.unwrap().unwrap_err(); + assert_eq!(err.kind(), io::ErrorKind::TimedOut); + assert!( + held.abandoned(), + "the main loop must see the client gave up" + ); + assert!(error_text(&read_reply(&mut client).await).contains("not run")); + } - let client_resp = handle.join().unwrap(); - assert!(matches!(client_resp, EngineResponse::Ok)); - cleanup_test(&target); + #[tokio::test(start_paused = true)] + async fn test_full_queue_times_out_without_queueing() { + // The queue is full and nothing drains it (engine in a poll). + let (tx, mut rx) = mpsc::channel(1); + let (blocker, _) = oneshot::channel(); + let (_, blocker_written) = oneshot::channel(); + tx.send(IpcRequest { + cmd: EngineCommand::Status, + reply: blocker, + written: blocker_written, + }) + .await + .unwrap(); + let (mut client, server) = duplex(1024); + client + .write_all(&frame(&EngineCommand::Status)) + .await + .unwrap(); + let err = serve(server, &tx, IO_TIMEOUT, REPLY_TIMEOUT) + .await + .unwrap_err(); + assert_eq!(err.kind(), io::ErrorKind::TimedOut); + assert!(err.to_string().contains("not run"), "{err}"); + assert!(error_text(&read_reply(&mut client).await).contains("not queued")); + rx.recv().await.unwrap(); + assert!(rx.try_recv().is_err(), "only the blocker was queued"); } #[tokio::test] - async fn test_concurrent_connections() { - let (listener, target) = bind_test("concurrent").await; - - // Three sequential clients connect and exchange a frame - for i in 0..3 { - let client_target = target.clone(); - let handle = std::thread::spawn(move || { - let mut client = connect(&client_target); - let cmd = sandstar_ipc::types::EngineCommand::ListChannels; - sandstar_ipc::protocol::write_frame(&mut client, &cmd).unwrap(); - }); - - let (mut stream, _, _) = accept(&listener).await.unwrap(); - let cmd: sandstar_ipc::types::EngineCommand = - sandstar_ipc::protocol::read_frame(&mut stream) - .unwrap() - .unwrap(); - assert!( - matches!(cmd, sandstar_ipc::types::EngineCommand::ListChannels), - "client {} should send ListChannels", - i - ); + async fn test_oversized_length_is_refused() { + let (mut client, server) = duplex(256); + let (tx, mut rx) = mpsc::channel(1); + client + .write_all(&(MAX_FRAME_SIZE + 1).to_le_bytes()) + .await + .unwrap(); + let err = serve(server, &tx, IO_TIMEOUT, REPLY_TIMEOUT) + .await + .unwrap_err(); + assert_eq!(err.kind(), io::ErrorKind::InvalidData); + assert!(rx.try_recv().is_err()); + assert!(error_text(&read_reply(&mut client).await).contains("bad command frame")); + } - handle.join().unwrap(); + #[tokio::test] + async fn test_garbage_payload_is_refused() { + let (mut client, server) = duplex(64); + let (tx, mut rx) = mpsc::channel(1); + client + .write_all(&[3, 0, 0, 0, 0xff, 0xff, 0xff]) + .await + .unwrap(); + let err = serve(server, &tx, IO_TIMEOUT, REPLY_TIMEOUT) + .await + .unwrap_err(); + assert_eq!(err.kind(), io::ErrorKind::InvalidData); + assert!(rx.try_recv().is_err()); + } + + #[tokio::test] + async fn test_empty_connection_is_quiet() { + let (client, server) = duplex(64); + drop(client); + let (tx, mut rx) = mpsc::channel(1); + serve(server, &tx, IO_TIMEOUT, REPLY_TIMEOUT).await.unwrap(); + assert!(rx.try_recv().is_err()); + } + + #[tokio::test] + async fn test_partial_length_prefix_is_an_error() { + let (mut client, server) = duplex(64); + client.write_all(&[10, 0]).await.unwrap(); + drop(client); + let (tx, _rx) = mpsc::channel(1); + let err = serve(server, &tx, IO_TIMEOUT, REPLY_TIMEOUT) + .await + .unwrap_err(); + assert_eq!(err.kind(), io::ErrorKind::UnexpectedEof); + } + + #[tokio::test] + async fn test_short_payload_is_an_error() { + // Length says 10, two bytes arrive, then the client hangs up. + let (mut client, server) = duplex(64); + client.write_all(&[10, 0, 0, 0, 1, 2]).await.unwrap(); + drop(client); + let (tx, _rx) = mpsc::channel(1); + let err = serve(server, &tx, IO_TIMEOUT, REPLY_TIMEOUT) + .await + .unwrap_err(); + assert_eq!(err.kind(), io::ErrorKind::UnexpectedEof); + } + + #[tokio::test] + async fn test_connections_over_the_limit_get_busy_and_slots_come_back() { + let (listener, target) = bind_test("limit").await; + let (tx, mut rx) = mpsc::channel(MAX_CONNECTIONS); + let slots = Arc::new(Semaphore::new(MAX_CONNECTIONS)); + let mut idle = Vec::new(); + for _ in 0..MAX_CONNECTIONS { + idle.push(connect(&target).await); + let stream = accept(&listener).await.unwrap(); + spawn_connection(stream, tx.clone(), slots.clone()); } + tokio::task::yield_now().await; + assert_eq!(slots.available_permits(), 0); + + let mut extra = connect(&target).await; + let stream = accept(&listener).await.unwrap(); + spawn_connection(stream, tx.clone(), slots.clone()); + let reply = tokio::time::timeout(Duration::from_secs(2), read_reply(&mut extra)) + .await + .expect("refused at once"); + assert!(error_text(&reply).contains("busy")); + + // Idle clients hang up: every slot is released. + drop(idle); + tokio::time::timeout(Duration::from_secs(2), async { + while slots.available_permits() < MAX_CONNECTIONS { + tokio::time::sleep(Duration::from_millis(10)).await; + } + }) + .await + .expect("permits released"); + assert!(rx.try_recv().is_err()); cleanup_test(&target); } + + #[tokio::test] + async fn test_a_slow_client_does_not_hold_another() { + let (tx, rx) = mpsc::channel(MAX_CONNECTIONS); + let main_loop = answer_all(rx); + // A client that sent half a length prefix and went quiet. + let (mut slow, slow_server) = duplex(64); + slow.write_all(&[1, 0]).await.unwrap(); + let slow_task = tokio::spawn({ + let tx = tx.clone(); + async move { serve(slow_server, &tx, IO_TIMEOUT, REPLY_TIMEOUT).await } + }); + // A normal client is answered while the slow one waits. + let (mut fast, fast_server) = duplex(1024); + fast.write_all(&frame(&EngineCommand::Status)) + .await + .unwrap(); + tokio::time::timeout( + Duration::from_secs(1), + serve(fast_server, &tx, IO_TIMEOUT, REPLY_TIMEOUT), + ) + .await + .expect("served without waiting for the slow client") + .unwrap(); + assert!(matches!(read_reply(&mut fast).await, EngineResponse::Ok)); + slow_task.abort(); + drop(tx); + drop(slow); + let _ = main_loop.await; + } } diff --git a/crates/sandstar-server/src/main.rs b/crates/sandstar-server/src/main.rs index 0be9514..8fe5662 100644 --- a/crates/sandstar-server/src/main.rs +++ b/crates/sandstar-server/src/main.rs @@ -114,6 +114,14 @@ async fn main() -> Result<(), Box> { libc::signal(libc::SIGPIPE, libc::SIG_IGN); } + // 0a. Listen for SIGTERM before anything needs cleaning up (PID file, + // /dev/watchdog, IPC socket). systemd stops the service with SIGTERM; + // without a listener the process died at once and skipped the + // shutdown (R-13). A SIGTERM during startup stays pending and the first + // loop turn shuts down. Extra signals during shutdown are ignored; + // systemd escalates to SIGKILL after TimeoutStopSec. + let mut term = signal::TermSignal::new()?; + // 0b. Enable core dumps for post-mortem debugging (Unix only). #[cfg(unix)] { @@ -680,6 +688,12 @@ async fn main() -> Result<(), Box> { let mut shutdown = pin!(tokio::signal::ctrl_c()); let mut hup = signal::HupSignal::new()?; let mut ipc_shutdown = false; + let mut stop_signal: Option<&str> = None; + // IPC connections are served on their own tasks; only the command reaches + // this loop (R-28). + let (ipc_tx, mut ipc_rx) = mpsc::channel::(ipc::MAX_CONNECTIONS); + let ipc_slots = Arc::new(tokio::sync::Semaphore::new(ipc::MAX_CONNECTIONS)); + let _ipc_accept = ipc::spawn_accept_loop(listener, ipc_tx, ipc_slots); // 12. Main event loop info!("engine running — press Ctrl+C to stop"); @@ -918,47 +932,53 @@ async fn main() -> Result<(), Box> { } } - // --- Incoming IPC connection (only when engine is available) --- - result = ipc::accept(&listener), if engine.is_some() => { - match result { - Ok((stream, _read_buf, _write_buf)) => { - let conn_result = dispatch::handle_connection( - stream, - engine.as_mut().expect("select! guard ensures engine.is_some()"), - &config, - start_time, - &history_store, - ); - match conn_result { - Ok(dispatch::ConnectionResult::Shutdown) => { - info!("shutdown requested via IPC"); - ipc_shutdown = true; - break; - } - Ok(dispatch::ConnectionResult::PollNow) => { - if !poll_in_progress { - let mut eng = engine.take().expect("select! guard ensures engine.is_some()"); - let mut ctrl = control_runner.take().unwrap_or_default(); - poll_in_progress = true; - let tx = poll_result_tx.clone(); - tokio::task::spawn_blocking(move || { - let poll_start = Instant::now(); - let notifications = eng.poll_update(); - ctrl.execute(&mut eng, Instant::now()); - let elapsed = poll_start.elapsed(); - let _ = tx.blocking_send((eng, ctrl, notifications, elapsed)); - }); - } - } - Ok(dispatch::ConnectionResult::Continue) => {} - Err(e) => { - error!(err = %e, "IPC connection error"); - } + // --- IPC command (only when engine is available) --- + Some(req) = ipc_rx.recv(), if engine.is_some() => { + let name = ipc::command_name(&req.cmd); + if req.abandoned() { + // The client was told "not run" (deadline passed in the queue). + warn!(cmd = %name, "IPC: client gave up while the command was queued; not run"); + continue; + } + let (conn_result, response) = dispatch::run( + req.cmd, + engine.as_mut().expect("select! guard ensures engine.is_some()"), + &config, + start_time, + &history_store, + ); + if req.reply.send(response).is_err() { + warn!(cmd = %name, "IPC: command ran, but the client gave up before the reply"); + } + match conn_result { + dispatch::ConnectionResult::Shutdown => { + info!("shutdown requested via IPC"); + // Let the reply reach the client before the runtime goes. + if !matches!( + tokio::time::timeout(ipc::SHUTDOWN_REPLY_WAIT, req.written).await, + Ok(Ok(())) + ) { + warn!("IPC: shutdown reply not confirmed as written"); } + ipc_shutdown = true; + break; } - Err(e) => { - error!(err = %e, "failed to accept IPC connection"); + dispatch::ConnectionResult::PollNow => { + if !poll_in_progress { + let mut eng = engine.take().expect("select! guard ensures engine.is_some()"); + let mut ctrl = control_runner.take().unwrap_or_default(); + poll_in_progress = true; + let tx = poll_result_tx.clone(); + tokio::task::spawn_blocking(move || { + let poll_start = Instant::now(); + let notifications = eng.poll_update(); + ctrl.execute(&mut eng, Instant::now()); + let elapsed = poll_start.elapsed(); + let _ = tx.blocking_send((eng, ctrl, notifications, elapsed)); + }); + } } + dispatch::ConnectionResult::Continue => {} } } @@ -1007,15 +1027,27 @@ async fn main() -> Result<(), Box> { sd_notify::watchdog(); } - // --- Shutdown signal (Ctrl+C / SIGTERM) — always works --- + // --- Shutdown signals — always work --- _ = &mut shutdown => { - info!("shutdown signal received (Ctrl+C)"); + info!("shutdown signal received (SIGINT / Ctrl+C)"); + stop_signal = Some("SIGINT"); + break; + } + _ = term.recv() => { + info!("shutdown signal received (SIGTERM)"); + stop_signal = Some("SIGTERM"); break; } } } // 13. Graceful shutdown + // Tell systemd we are stopping (matters for an IPC shutdown, where systemd + // did not ask for it). + sd_notify::notify("STOPPING=1"); + // A poll that never comes back keeps a blocking task the runtime would + // wait for forever on exit; then we leave with process::exit below. + let mut poll_stuck = false; // If poll is in progress, wait up to 5s for it to finish if poll_in_progress { match tokio::time::timeout(Duration::from_secs(5), poll_result_rx.recv()).await { @@ -1028,9 +1060,13 @@ async fn main() -> Result<(), Box> { } Err(_) => { warn!("poll completion timed out (5s) — shutting down anyway"); + poll_stuck = true; } } } + // The loop no longer feeds the watchdogs; the poll wait took up to 5 s. + watchdog.kick(); + sd_notify::watchdog(); // Stop Sedona VM if running #[cfg(feature = "svm")] @@ -1042,16 +1078,27 @@ async fn main() -> Result<(), Box> { let reason = if ipc_shutdown { "IPC command" } else { - "signal" + stop_signal.unwrap_or("signal") }; info!(uptime_secs = uptime.as_secs(), reason, "engine stopped"); if let Some(ref mut eng) = engine { if let Err(e) = eng.hal.shutdown() { warn!(err = %e, "HAL shutdown error"); } + } else { + warn!("HAL shutdown skipped: the engine did not come back from its poll"); } watchdog.close(); ipc::cleanup(&config.socket_path); + if poll_stuck { + // Dropping the runtime would wait for the stuck poll without limit + // (tokio: Runtime drop blocks on spawn_blocking tasks), until systemd + // sends SIGKILL. Clean up and leave now. + warn!("exiting without waiting for the stuck poll"); + drop(_pid_guard); + drop(_log_guard); + std::process::exit(0); + } // _pid_guard dropped here -> PID file removed // _log_guard dropped here -> log file flushed diff --git a/crates/sandstar-server/src/pid.rs b/crates/sandstar-server/src/pid.rs index 3967984..2520792 100644 --- a/crates/sandstar-server/src/pid.rs +++ b/crates/sandstar-server/src/pid.rs @@ -92,12 +92,8 @@ impl PidFile { impl Drop for PidFile { fn drop(&mut self) { if let Err(e) = fs::remove_file(&self.path) { - // Don't panic in Drop - eprintln!( - "warning: failed to remove PID file {}: {}", - self.path.display(), - e - ); + // Don't panic in Drop; the log guard is still alive here. + tracing::warn!(err = %e, path = %self.path.display(), "failed to remove PID file"); } } } diff --git a/crates/sandstar-server/src/signal.rs b/crates/sandstar-server/src/signal.rs index fff957c..0698837 100644 --- a/crates/sandstar-server/src/signal.rs +++ b/crates/sandstar-server/src/signal.rs @@ -1,7 +1,9 @@ //! Platform-agnostic signal handling. //! -//! On Unix, SIGHUP triggers config reload. -//! On Windows, reload is IPC-only (no SIGHUP equivalent). +//! On Unix, SIGHUP triggers config reload and SIGTERM (`systemctl stop`) +//! a graceful shutdown (R-13). +//! On Windows, reload is IPC-only (no SIGHUP equivalent) and shutdown is +//! Ctrl+C or IPC. /// Platform-agnostic SIGHUP listener. /// @@ -30,7 +32,12 @@ impl HupSignal { pub async fn recv(&mut self) { #[cfg(unix)] { - self.inner.recv().await; + if self.inner.recv().await.is_none() { + // The signal driver is gone: never report a signal that + // did not arrive. + tracing::error!("signal listener closed"); + std::future::pending::<()>().await; + } } #[cfg(not(unix))] { @@ -39,3 +46,45 @@ impl HupSignal { } } } + +/// Platform-agnostic SIGTERM listener. +/// +/// On Unix, resolves when SIGTERM is received (`systemctl stop`/`restart`). +/// On Windows, the future never resolves. +pub struct TermSignal { + #[cfg(unix)] + inner: tokio::signal::unix::Signal, +} + +impl TermSignal { + /// Create a new SIGTERM listener. Once created, SIGTERM no longer kills + /// the process directly; the caller must shut down. + pub fn new() -> std::io::Result { + #[cfg(unix)] + { + let inner = tokio::signal::unix::signal(tokio::signal::unix::SignalKind::terminate())?; + Ok(Self { inner }) + } + #[cfg(not(unix))] + { + Ok(Self {}) + } + } + + /// Wait for SIGTERM. On Windows, this future never resolves. + pub async fn recv(&mut self) { + #[cfg(unix)] + { + if self.inner.recv().await.is_none() { + // The signal driver is gone: never report a signal that + // did not arrive. + tracing::error!("signal listener closed"); + std::future::pending::<()>().await; + } + } + #[cfg(not(unix))] + { + std::future::pending::<()>().await; + } + } +} diff --git a/crates/sandstar-server/src/watchdog.rs b/crates/sandstar-server/src/watchdog.rs index fbe9175..2867a0e 100644 --- a/crates/sandstar-server/src/watchdog.rs +++ b/crates/sandstar-server/src/watchdog.rs @@ -195,8 +195,13 @@ impl Watchdog { pub fn close(&mut self) { if let Some(ref mut fd) = self.dev_watchdog { // Magic close: "V" disables watchdog on close - let _ = fd.write_all(b"V"); - info!("watchdog: /dev/watchdog closed (magic close)"); + match fd.write_all(b"V") { + Ok(()) => info!("watchdog: /dev/watchdog closed (magic close)"), + // The kernel watchdog stays armed and resets the board. + Err(e) => { + warn!(err = %e, "watchdog: magic close failed, /dev/watchdog stays armed") + } + } } self.dev_watchdog = None; self.gpio60_value = None; diff --git a/crates/sandstar-server/tests/sigterm.rs b/crates/sandstar-server/tests/sigterm.rs new file mode 100644 index 0000000..4ebf715 --- /dev/null +++ b/crates/sandstar-server/tests/sigterm.rs @@ -0,0 +1,152 @@ +//! SIGTERM (`systemctl stop`) runs the graceful shutdown (R-13, S-43). +//! +//! Starts the real server binary, sends SIGTERM, and checks the exit code, +//! the shutdown log line and the cleanup of the PID file and IPC socket. +//! Unix only: there is no SIGTERM on Windows. +#![cfg(unix)] + +use std::io::{BufRead, BufReader}; +use std::path::PathBuf; +use std::process::{Child, Command, ExitStatus, Stdio}; +use std::sync::{Arc, Mutex}; +use std::time::{Duration, Instant}; + +/// A running server; killed and reaped if the test fails before it exits. +struct Server { + child: Child, + lines: Arc>>, + readers: Vec>, + dir: PathBuf, + pid_file: PathBuf, + socket: PathBuf, +} + +impl Server { + fn start(name: &str) -> Self { + let dir = + std::env::temp_dir().join(format!("sandstar-sigterm-{}-{name}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + let pid_file = dir.join("engine.pid"); + let socket = dir.join("engine.sock"); + let port = { + let l = std::net::TcpListener::bind("127.0.0.1:0").unwrap(); + l.local_addr().unwrap().port() + }; + let mut child = Command::new(env!("CARGO_BIN_EXE_sandstar-engine-server")) + .args(["--http-port", &port.to_string(), "--http-bind", "127.0.0.1"]) + .arg("--pid-file") + .arg(&pid_file) + .arg("--socket") + .arg(&socket) + // Without --log-file the tracing logs go to stdout + // (tracing_subscriber::fmt default); eprintln lines to stderr. + .stdout(Stdio::piped()) + .stderr(Stdio::piped()) + .spawn() + .unwrap(); + let lines = Arc::new(Mutex::new(Vec::new())); + let read_into = |stream: Box| { + let lines = lines.clone(); + std::thread::spawn(move || { + for line in BufReader::new(stream).lines().map_while(Result::ok) { + lines.lock().unwrap().push(line); + } + }) + }; + let readers = vec![ + read_into(Box::new(child.stdout.take().unwrap())), + read_into(Box::new(child.stderr.take().unwrap())), + ]; + Self { + child, + lines, + readers, + dir, + pid_file, + socket, + } + } + + fn log(&self) -> String { + self.lines.lock().unwrap().join("\n") + } + + fn wait_for_line(&self, pred: impl Fn(&str) -> bool, within: Duration) { + let start = Instant::now(); + while start.elapsed() < within { + if self.lines.lock().unwrap().iter().any(|l| pred(l)) { + return; + } + std::thread::sleep(Duration::from_millis(20)); + } + panic!("expected log line did not appear:\n{}", self.log()); + } + + fn sigterm(&self) { + let status = Command::new("kill") + .args(["-TERM", &self.child.id().to_string()]) + .status() + .unwrap(); + assert!(status.success(), "kill -TERM"); + } + + fn wait_exit(&mut self, within: Duration) -> ExitStatus { + let start = Instant::now(); + loop { + if let Some(s) = self.child.try_wait().unwrap() { + for r in self.readers.drain(..) { + let _ = r.join(); + } + return s; + } + if start.elapsed() > within { + panic!("server did not stop within {within:?}:\n{}", self.log()); + } + std::thread::sleep(Duration::from_millis(50)); + } + } + + fn assert_clean_sigterm_exit(&mut self) { + let exit = self.wait_exit(Duration::from_secs(20)); + let log = self.log(); + assert!(exit.success(), "exit after SIGTERM: {exit:?}\n{log}"); + assert!( + log.lines() + .any(|l| l.contains("engine stopped") && l.contains("SIGTERM")), + "shutdown log line with the signal:\n{log}" + ); + assert!(!self.pid_file.exists(), "PID file removed on shutdown"); + assert!(!self.socket.exists(), "IPC socket removed on shutdown"); + } +} + +impl Drop for Server { + fn drop(&mut self) { + if matches!(self.child.try_wait(), Ok(None)) { + let _ = self.child.kill(); + let _ = self.child.wait(); + } + let _ = std::fs::remove_dir_all(&self.dir); + } +} + +#[test] +fn sigterm_runs_the_graceful_shutdown() { + let mut server = Server::start("running"); + server.wait_for_line(|l| l.contains("engine running"), Duration::from_secs(30)); + assert!(server.pid_file.exists(), "PID file written at start"); + assert!(server.socket.exists(), "IPC socket created at start"); + server.sigterm(); + server.assert_clean_sigterm_exit(); +} + +#[test] +fn sigterm_during_startup_is_held_until_the_loop_runs() { + // The listener is installed before the first stderr line; a SIGTERM + // sent then must not kill the process mid-startup. + let mut server = Server::start("startup"); + server.wait_for_line(|_| true, Duration::from_secs(30)); + server.sigterm(); + server.assert_clean_sigterm_exit(); +} diff --git a/docs/Progress/DEPLOYMENT_CHECKLIST.md b/docs/Progress/DEPLOYMENT_CHECKLIST.md index 68a6a7a..ad9acdc 100644 --- a/docs/Progress/DEPLOYMENT_CHECKLIST.md +++ b/docs/Progress/DEPLOYMENT_CHECKLIST.md @@ -108,11 +108,41 @@ Read the journal soon after the start: it is volatile and holds well under an ho - `tables loaded` with the expected count; - a watchdog line saying GPIO60 was opened, or why not (the engine retries for about 5 minutes); - no repeated `poll cycle exceeded`; + - from S-43 on, a stop or restart ends the previous run with `shutdown signal received (SIGTERM)`, `engine stopped … reason="SIGTERM"` and `watchdog: /dev/watchdog closed (magic close)` when `/dev/watchdog` was open. On the first deploy of S-43 the old binary is stopped, so these lines appear from the next restart on. `magic close failed`, `HAL shutdown skipped` or `exiting without waiting for the stuck poll` need a look; - with `--cluster` and no mTLS certificates (the packaged unit): `roxWarp: no mTLS configured, cluster listener disabled` and `cluster listener not started`, so port 7443 is not listening (S-36). With certificates expect `starting mTLS listener`; `mTLS config failed` means the certificate files need fixing. 5. **Warnings:** count ERROR and WARN lines from the start time and compare them with the known types for this device (for example BACnet `comm fault` when a BACnet drop-in is active). Investigate anything new. 6. **Data:** `curl -s http://localhost:8085/api/status` and spot-read a few channels with `/api/read`. 7. **Next day:** confirm that log pruning kept at most 14 dated files in `/var/log/sandstar/`. +## 7a. Turning REST auth on or off + +The packaged unit starts with no auth. Auth is a device-local setting: an +`EnvironmentFile` drop-in, so the password is not in the unit file or in +`systemctl show`. Needs explicit approval (new kind of device write). Back up +`/etc/systemd/system/sandstar-engine.service.d` and `/etc/sandstar` first. + +1. `/etc/sandstar/auth.env`, owner `root:root`, mode `0600` (write it with + `umask 077`; never print it): + - `SANDSTAR_AUTH_USER=` and `SANDSTAR_AUTH_PASS=`: SCRAM login (editor); + - optional `SANDSTAR_AUTH_TOKEN=`: bearer for scripts; + - `SANDSTAR_WS_ALLOWED_ORIGINS=[,...]`: page origins allowed besides + the device itself, e.g. the editor dev server `http://localhost:8091`. +2. `/etc/systemd/system/sandstar-engine.service.d/auth.conf` (0644): + `[Service]` / `EnvironmentFile=/etc/sandstar/auth.env`. +3. `systemctl daemon-reload && systemctl restart sandstar-engine`. +4. Verify on the device (no credentials, no real write): + - `/api/about`, `/api/read`, `/health`, `/api/cluster/status`: 200; + - `POST /api/pointWrite`, `HEAD /live/sedonaState`, `GET /api/sox/tree`, + `PUT /file/x`: 401; + - log: one `SCRAM-SHA-256 auth configured` line, no new ERROR; + - `systemctl show sandstar-engine -p Environment` does not contain the password; + - the editor logs in (`bash tools/editor-dev.sh`) and loads the tree. +5. Off: remove both files, `daemon-reload`, restart. + +Clients that write without credentials get 401 once auth is on. Reads listed +above stay open. `health-monitor.sh` (cron) only reads `/health` and +`/api/diagnostics`. + ## 8. Rollback Rolling back is a write outside the deploy scope and needs its own approval. diff --git a/docs/Progress/HARDCODED_LIMITS.md b/docs/Progress/HARDCODED_LIMITS.md index ded0e03..8cc56a3 100644 --- a/docs/Progress/HARDCODED_LIMITS.md +++ b/docs/Progress/HARDCODED_LIMITS.md @@ -132,7 +132,12 @@ Audited: 2026-03-10 | Constant | Value | File | Line | Recommendation | |----------|-------|------|------|----------------| | `MAX_FRAME_SIZE` | 1,048,576 (1MB) | `sandstar-ipc/src/protocol.rs` | 11 | **Document** — max IPC message size. Prevents unbounded allocation. | -| IPC read timeout | 5s | `sandstar-server/src/ipc.rs` | 58,68 | **Document** — prevents blocking IPC reads indefinitely. | +| IPC `IO_TIMEOUT` | 5s | `sandstar-server/src/ipc.rs` | 43 | **Document** — total time to read one command frame, and again to write the reply. Connections are served on their own tasks, never in the main loop (R-28, S-42). | +| IPC `REPLY_TIMEOUT` | 10s | `sandstar-server/src/ipc.rs` | 47 | **Document** — one deadline for queueing the command and getting the engine's reply. On expiry the client gets `Error(...not run)`; the main loop skips a command whose client gave up (S-42). | +| IPC `MAX_CONNECTIONS` | 4 | `sandstar-server/src/ipc.rs` | 50 | **Document** — IPC connections served at once, also the IPC command channel capacity. A fifth gets `Error("busy...")` (S-42). | +| IPC `SHUTDOWN_REPLY_WAIT` | 1s | `sandstar-server/src/ipc.rs` | 53 | **Keep** — `Shutdown` waits this long for its reply to be written; kept short for systemd `WatchdogSec=10` (S-42). | +| IPC `ACCEPT_BACKOFF` / `ERROR_REPLY_TIMEOUT` / `LOG_EVERY` | 100ms / 1s / 10s | `sandstar-server/src/ipc.rs` | 56-62 | **Keep** — pause after a failed `accept`; time for a failure reply; one IPC failure log line per kind per period, with a suppressed count (S-42). | +| CLI `IO_TIMEOUT` | 20s | `sandstar-cli/src/client.rs` | 12 | **Keep** — `sandstar-cli` read/write timeout; above the server's own deadlines so its error reply arrives first (S-42). | | `ENGINE_REPLY_TIMEOUT` | 10s | `sandstar-server/src/rest/mod.rs` | 146 | **Document** — max wait for an `EngineHandle` command (send + reply). On timeout the caller gets `engine timeout` (REST: 503); a state-changing command may still run later (R-28, S-20). | | Engine timeout warn interval | 60s | `sandstar-server/src/rest/mod.rs` | 160 | **Keep** — first timeout per 60 s logged at `warn`, the rest at `debug`. | | `HEALTH_ENGINE_TIMEOUT` | 2s | `sandstar-server/src/rest/handlers.rs` | 369 | **Document** — `/health` waits at most this long for the engine; otherwise 503 with `healthy:false` (R-28, S-21). | diff --git a/docs/Progress/OVERVIEW.md b/docs/Progress/OVERVIEW.md index ecd4ec2..0142f11 100644 --- a/docs/Progress/OVERVIEW.md +++ b/docs/Progress/OVERVIEW.md @@ -46,7 +46,7 @@ This is the single-read status tracker for the Sandstar Rust project. It consoli | MQTT driver | ✅ Complete — Project C, 4 phases, live-validated | [IMPLEMENTATION_PLAN_MQTT.md](IMPLEMENTATION_PLAN_MQTT.md), [MQTT_SETUP.md](MQTT_SETUP.md) | | Poll integration (driver → engine channels) | ✅ Complete — shared tick task in rest/mod.rs | [IMPLEMENTATION_PLAN_FILTER_AND_BACNET.md](IMPLEMENTATION_PLAN_FILTER_AND_BACNET.md) Stage 1/2 | | REST API + WebSocket | ✅ 30+ routes (see §3), bearer + SCRAM auth, rate limit, WS push. Since S-31 every HTTP write route is behind the auth layer and since S-32 the editor endpoints (`/live`, `/api/rows`, `/live/sedonaState`) are too (bearer header or session cookie, plus an Origin check). `/roxwarp` on the REST port has no auth and is mounted only with `--cluster-insecure` (S-36) | [ROADMAP_v2.md](ROADMAP_v2.md) §Phase 1, [DRIVER_REST_API.md](DRIVER_REST_API.md) | -| Security hardening | 🟡 Partial. Open: the field service binds `0.0.0.0` with no auth configured; `/roxwarp` outside `check_auth` when `--cluster-insecure` is given (§3, S-36); SIGTERM not handled (no graceful shutdown) | [ROADMAP_v2.md](ROADMAP_v2.md) §Phase 5.7, §Phase 6.5 | +| Security hardening | 🟡 Partial. Open: the packaged unit binds `0.0.0.0` with no auth (the test device turns it on with a drop-in since S-38); `/roxwarp` outside `check_auth` when `--cluster-insecure` is given (§3, S-36); SIGTERM not handled (no graceful shutdown) | [ROADMAP_v2.md](ROADMAP_v2.md) §Phase 5.7, §Phase 6.5 | | Visual DDC editor | 🟡 14.0A REST complete. 14.0B–F were superseded by 14.0G (native backend for the external Vue editor): about 75%, G-6 open, G-7/G-8 partial | [IMPLEMENTATION_PLAN_NATIVE_EDITOR_BACKEND.md](IMPLEMENTATION_PLAN_NATIVE_EDITOR_BACKEND.md) | | Driver Framework v2 (Phase 12) | ✅ All sub-phases complete (12.0A–G + 12.0D.WS). Caveats: MQTT never reconnects; BACnet COV subscriptions never start in production; REST-created drivers get no poll tick; Modbus is not loadable | [IMPLEMENTATION_PLAN_DRIVER_FRAMEWORK.md](IMPLEMENTATION_PLAN_DRIVER_FRAMEWORK.md) | | Clustering — roxWarp (Phase 9) | 🟡 9.0a + 9.0b + 9.0c shipped; 9.0d SkySpark Fantom pod open. The typed binary-Trio format exists in code but is not what goes over the wire | [ROADMAP_v2.md](ROADMAP_v2.md) §Phase 9, [research/16](../research/16_ROXWARP_PROTOCOL.md) | @@ -235,7 +235,7 @@ Router: `router_with_auth` in `crates/sandstar-server/src/rest/mod.rs`, plus rou | `GET /api/sim/outputs` (drains recorded writes), `POST /api/sim/inject`, `POST /api/sim/scenario` | **yes** (S-31) | Only in builds with the `simulator-hal` feature | **Security posture:** -- `--http-bind` defaults to `127.0.0.1`. ⚠ The packaged systemd unit passes `--http-bind 0.0.0.0` and configures no auth, so on the field device every route above is reachable on the LAN without credentials. +- `--http-bind` defaults to `127.0.0.1`. ⚠ The packaged systemd unit passes `--http-bind 0.0.0.0` and configures no auth, so a fresh install answers every route above on the LAN without credentials. Auth is turned on per device with an `EnvironmentFile` drop-in (DEPLOYMENT_CHECKLIST §7a); the test device has it since S-38 (2026-11-23). - Bearer token (`--auth-token` / `SANDSTAR_AUTH_TOKEN`) and SCRAM-SHA-256 (`--auth-user` / `--auth-pass`, `SANDSTAR_AUTH_USER` / `SANDSTAR_AUTH_PASS`). - REST TLS is behind the `tls` cargo feature; the release alias `arm-build-svm` does not enable it. - Filter depth cap 32, watch cap 64, max channels per watch 256, body limit 1 MB, rate limit on by default (100 req/s, one counter shared by all clients). @@ -315,7 +315,7 @@ Host addresses, SSH details and site names are deliberately not written in this Rewritten 2026-11-18. Ranked by risk first, then value. ### 🔴 Security and robustness (field device affected) -1. **Auth in the field configuration.** The unit binds `0.0.0.0` with no auth; and with `--cluster-insecure`, `/roxwarp` bypasses auth (§3, S-36). HTTP write routes are behind it since S-31, the editor endpoints since S-32; the editor itself cannot log in yet (S-32b). +1. **Auth in the field configuration.** The packaged unit binds `0.0.0.0` with no auth; each device needs the auth drop-in (DEPLOYMENT_CHECKLIST §7a; on the test device since S-38). With `--cluster-insecure`, `/roxwarp` bypasses auth (§3, S-36). HTTP write routes are behind it since S-31, the editor endpoints since S-32, and the editor logs in since S-32b. 2. **Panic paths on network input.** Release builds abort on panic; known cases include a short BACnet BVLL frame and some lock-poison `unwrap`s on REST paths. 3. **Graceful shutdown.** Handle SIGTERM and wire `with_graceful_shutdown`. 4. **Numeric output guards.** Not every value leaving the process is checked with `is_finite` (engine outputs, roxWarp feed).