Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion .claude/rules/engine-async.md
Original file line number Diff line number Diff line change
Expand Up @@ -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).
6 changes: 5 additions & 1 deletion crates/sandstar-server/src/ipc.rs
Original file line number Diff line number Diff line change
Expand Up @@ -333,7 +333,11 @@ async fn write_frame<W: AsyncWrite + Unpin>(
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))]
Expand Down
42 changes: 39 additions & 3 deletions crates/sandstar-server/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -114,6 +114,14 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
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)]
{
Expand Down Expand Up @@ -680,6 +688,7 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
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::IpcRequest>(ipc::MAX_CONNECTIONS);
Expand Down Expand Up @@ -1018,15 +1027,27 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
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 {
Expand All @@ -1039,9 +1060,13 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
}
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")]
Expand All @@ -1053,16 +1078,27 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
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

Expand Down
8 changes: 2 additions & 6 deletions crates/sandstar-server/src/pid.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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");
}
}
}
Expand Down
55 changes: 52 additions & 3 deletions crates/sandstar-server/src/signal.rs
Original file line number Diff line number Diff line change
@@ -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.
///
Expand Down Expand Up @@ -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))]
{
Expand All @@ -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<Self> {
#[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;
}
}
}
9 changes: 7 additions & 2 deletions crates/sandstar-server/src/watchdog.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down
152 changes: 152 additions & 0 deletions crates/sandstar-server/tests/sigterm.rs
Original file line number Diff line number Diff line change
@@ -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<Mutex<Vec<String>>>,
readers: Vec<std::thread::JoinHandle<()>>,
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<dyn std::io::Read + Send>| {
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();
}
1 change: 1 addition & 0 deletions docs/Progress/DEPLOYMENT_CHECKLIST.md
Original file line number Diff line number Diff line change
Expand Up @@ -108,6 +108,7 @@ 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`.
Expand Down
Loading