Author SHA1 Message Date
osobhandClaude Sonnet 5 ef02b22b72 Fix dashboard disk usage overstating used space fleet-wide
Build with clawstor cache / Cargo build (clawstor-cached) (pull_request) Failing after 3s
Reported by the operator: dashboard's "used" figure for morpheus
didn't match `df`. Root cause: filesystem_usage() computed
`used = total - f_bavail`. f_bavail is space available to an
*unprivileged* user, which excludes ext4's reserved-blocks-for-root
margin (~5% of the filesystem by default) -- so that formula folded
the entire reserved margin into "used" on every node, not just
morpheus. Worse on bigger disks: this overstated tank's usage by
~1GB less noticeably relative to its 1.9TB size, but the same
absolute-percentage bug applies everywhere.

`df`'s Used column is `total - f_bfree` (raw free blocks, reserved
or not) -- matching that formula is what makes the dashboard agree
with `df` instead of silently running high. `available_bytes` still
reports f_bavail (what's actually writable), unchanged.

Verified against `df -h /` on all three nodes post-fix: tank
93.6GiB vs df's 93G, architect 93.6GiB vs 94G, morpheus 135.5GiB vs
136G -- all now agree within rounding.

Co-Authored-By: Claude Sonnet 5 <[email protected]>
2026-08-02 16:37:07 -07:00
osobh cc26052cfe Merge pull request 'Recover replication baseline from remote when locally pruned' (#113) from fix-replicate-broken-incremental-base into main
Build with clawstor cache / Cargo build (clawstor-cached) (push) Failing after 3s
2026-08-02 20:59:37 +00:00
osobhandClaude Sonnet 5 11a259b762 Recover replication baseline from remote when locally pruned
Build with clawstor cache / Cargo build (clawstor-cached) (pull_request) Failing after 2s
Found during a routine fleet health sweep: tank's daily replication
to architect had silently broken. replicate_to_cold() records the
last-replicated snapshot name in a local state file and reuses it as
the incremental send base next time -- but never handles the case
where local snapshot retention (snapshot_retain_hours = 24) prunes
that exact snapshot before the next replication run. When that
happens it silently falls back to a FULL send, which then hard-fails
against a non-empty destination ("must destroy them to overwrite
it").

Root cause of the timing gap: the daemon's replication tick is a
24-hour interval, same order of magnitude as local retention. Every
claw-store.service restart resets that tick's countdown without
resetting the hourly-snapshot pruning tick, so a day of frequent
restarts (routine during active deployment work) is enough for the
two to drift out of sync -- the recorded baseline ages out locally
before replication ever gets to reuse it.

Fix: when the recorded baseline is gone, query the remote's actual
snapshot list over SSH (new ZfsOps::list_remote_snapshots) and find
the newest snapshot both sides still share by tag, rather than
giving up and attempting a full send. Only truly falls back to full
when no common snapshot exists anywhere. Verified live against tank
-> architect: correctly recovered daily-2026-08-01-0000 as the base
and completed an incremental send.

Added test coverage for all three paths (recorded baseline present,
recovered from remote, no common snapshot found) -- replicate_to_cold
had none before this, since LAST_REPLICATED_PATH was a hardcoded
absolute path with no way to inject a test double. Split into a
public wrapper plus replicate_to_cold_with_state_path() so tests can
use a temp file instead of touching real /var/lib/claw-store state.

Co-Authored-By: Claude Sonnet 5 <[email protected]>
2026-08-02 13:59:24 -07:00
osobh ec24f37d90 Merge pull request 'Fix stdout/stderr ordering in ShutdownPrepCheck' (#112) from fix-shutdown-prep-check-stderr-ordering into main
Build with clawstor cache / Cargo build (clawstor-cached) (push) Failing after 2s
2026-08-01 02:45:42 +00:00
osobhandClaude Sonnet 5 e5fcb8b3f4 Fix stdout/stderr ordering in ShutdownPrepCheck
Build with clawstor cache / Cargo build (clawstor-cached) (pull_request) Failing after 3s
Command::output() captures stdout and stderr as two separate
buffers. check() was concatenating stdout-then-stderr, which throws
away chronological order entirely -- every stderr line (e.g.
"Error: send_to_host not set" from `claw-store replicate` on a node
with no downstream replication target, which is normal and expected
on architect) landed at the very end of the report regardless of
when it actually printed, making a mid-script, already-handled
condition look like a failure that happened after "DRY RUN
COMPLETE".

Fix: invoke via `bash -c "script --dry-run 2>&1"` so stderr merges
into stdout inside the shell, before either stream reaches us --
true chronological order preserved, single buffer to read.

Verified on architect: the send_to_host message now appears exactly
where it happens, inside the "taking final snapshot + replicating"
step, with DRY RUN COMPLETE correctly last.

Co-Authored-By: Claude Sonnet 5 <[email protected]>
2026-07-31 19:45:29 -07:00
osobh 9debd84e95 Merge pull request 'Honor zfs_dataset = "none"; surface shutdown-prep panel from fleet view' (#111) from fix-zfs-none-and-shutdown-panel-discoverability into main
Build with clawstor cache / Cargo build (clawstor-cached) (push) Failing after 3s
2026-08-01 00:03:14 +00:00
osobhandClaude Sonnet 5 f38efc7096 Honor zfs_dataset = "none" instead of erroring; surface shutdown-prep panel from fleet view
Build with clawstor cache / Cargo build (clawstor-cached) (pull_request) Failing after 4s
Two problems surfaced while checking on the fleet after the shutdown-
prep button PR:

1. morpheus is configured with zfs_dataset = "none" (it has no ZFS
   pool -- warm tier is a plain directory on the LVM root volume),
   but nothing in the code actually implemented that as a sentinel.
   cmd_snapshot/cmd_replicate and the daemon's periodic snap/repl
   ticks always tried real zfs/zpool calls regardless, producing
   "zfs: command not found" errors on every hourly tick and in the
   shutdown-prep report. WarmConfig::zfs_enabled() now gates all four
   call sites; a non-ZFS node gets a clean "nothing to
   snapshot/replicate" instead of a raw shell error.

2. safe-shutdown-prep.sh's zpool-health step now checks `command -v
   zpool` first instead of leaking "zpool: command not found" into
   the report.

3. "we don't see the button" turned out to be page confusion: the
   shutdown-prep panel lives on the per-node detail page
   (/v2/nodes/<name>), not the root Fleet Health landing page. Added
   a small "view detail · maintenance & shutdown prep →" hint to the
   bottom of every NodeCard so it's discoverable without already
   knowing to click through.

Verified against tank, architect, and morpheus -- morpheus's
shutdown-prep --dry-run report is now clean (no "command not found"
lines) both when run locally and via cross-node RPC from tank.

Co-Authored-By: Claude Sonnet 5 <[email protected]>
2026-07-31 17:03:02 -07:00
osobh 2d0c225f98 Merge pull request 'Add shutdown-prep button to dashboard-v2 NodeDetail' (#110) from add-shutdown-prep-dashboard-button into main
Build with clawstor cache / Cargo build (clawstor-cached) (push) Failing after 3s
2026-07-31 21:47:09 +00:00
osobhandClaude Sonnet 5 4ea1cbed2e Add shutdown-prep button to dashboard-v2 NodeDetail
Build with clawstor cache / Cargo build (clawstor-cached) (pull_request) Failing after 3s
Wires safe-shutdown-prep.sh into the dashboard so an operator can
prep a node for hardware maintenance from a browser instead of SSH.

New RPC methods (0x20/0x21):
- ShutdownPrepCheck runs `--dry-run` to completion and returns the
  full report. Never stops anything, safe to call repeatedly.
- ShutdownPrepExecute starts the real run detached (`systemd-run
  --user --scope --collect`), placing it in a cgroup outside
  claw-store.service's own -- the script's own step 6 stops that
  service, i.e. the process that would otherwise be running it, so
  it has to survive its own parent dying. Returns immediately with
  a "started" message; full output lands in
  /var/lib/claw-store/shutdown-prep.log for whoever's at the machine
  once it's gone dark, since there's no way to stream a live result
  past the point the daemon stops itself.
- Execute double-checks confirm_node_name against the peer's own
  configured name server-side, on top of the aggregator's own path
  match -- defense in depth for a highly consequential action.

Aggregator endpoints (admin-token gated, AuthedCaller::require_admin):
  POST /api/v2/node/:name/shutdown-prep/check
  POST /api/v2/node/:name/shutdown-prep/execute

Frontend: ShutdownPrepPanel on NodeDetail. Check button always
enabled; the real "stop services" button only unlocks after a ready
check, and additionally requires typing the exact node name to
confirm before it's clickable.

Also fixes a script bug found while testing this against the live
daemon process (not caught in manual interactive-shell testing): the
zpool-detection line parsed raw `mount` output positionally, which
returned the wrong field under the daemon's process context for
reasons that didn't reproduce interactively. Switched to
`df --output=source`, which is stable across both.

Verified end-to-end against tank, architect, and morpheus, including
cross-node targeting (tank's dashboard successfully triggered a
check on morpheus over the fleet RPC layer).

Co-Authored-By: Claude Sonnet 5 <[email protected]>
2026-07-31 14:46:57 -07:00
20 changed files with 901 additions and 26 deletions
+1
View File
@@ -26,6 +26,7 @@ pub mod refs;
pub mod repo_ensure;
pub mod rpc;
pub mod services;
pub mod shutdown_prep;
pub mod snapshot;
pub mod tags;
pub mod tailscale;
+79 -1
View File
@@ -217,6 +217,22 @@ pub enum Method {
/// `payload`: JSON [`crate::cluster::repo_ensure::RepoReleaseRequest`].
/// Reply: JSON [`crate::cluster::repo_ensure::RepoReleaseReply`].
RepoRelease = 0x1f,
/// Runs `safe-shutdown-prep.sh --dry-run` to completion on this
/// node and returns the full report. Never stops anything —
/// dry-run only, safe to call repeatedly.
///
/// `payload`: JSON [`crate::cluster::shutdown_prep::ShutdownPrepCheckRequest`].
/// Reply: JSON [`crate::cluster::shutdown_prep::ShutdownPrepCheckReply`].
ShutdownPrepCheck = 0x20,
/// Starts the real `safe-shutdown-prep.sh` run in a detached
/// systemd scope and returns immediately — the script's own step
/// stops `claw-store.service`, so this RPC connection cannot
/// outlive full completion. See
/// [`crate::cluster::shutdown_prep`] module docs.
///
/// `payload`: JSON [`crate::cluster::shutdown_prep::ShutdownPrepExecuteRequest`].
/// Reply: JSON [`crate::cluster::shutdown_prep::ShutdownPrepExecuteReply`].
ShutdownPrepExecute = 0x21,
}
impl Method {
@@ -255,6 +271,8 @@ impl Method {
0x1d => Some(Method::DashboardStorage),
0x1e => Some(Method::RepoEnsure),
0x1f => Some(Method::RepoRelease),
0x20 => Some(Method::ShutdownPrepCheck),
0x21 => Some(Method::ShutdownPrepExecute),
_ => None,
}
}
@@ -637,6 +655,17 @@ fn decode_nibble(b: u8) -> Option<u8> {
/// statvfs on the given path. Uses libc directly — cheap enough
/// that we don't need to cache. Silent on error (returns None).
///
/// Bug fix 2026-08-02: `used` was computed as `total - f_bavail`.
/// `f_bavail` is space available to an *unprivileged* user, which
/// excludes ext4's reserved-blocks-for-root margin (~5% of the
/// filesystem by default) — so that formula silently folded the
/// entire reserved margin into "used", overstating usage by exactly
/// that amount on every node (worse on bigger disks: ~21GB on a
/// 466GB root, proportionally more on multi-TB ones). `df`'s Used
/// column is `total - f_bfree` (raw free blocks, root-reserved or
/// not) — matching that here is what makes the dashboard agree with
/// `df` instead of silently running high.
fn filesystem_usage(path: &std::path::Path) -> Option<FilesystemUsage> {
let cpath = std::ffi::CString::new(path.as_os_str().to_str()?).ok()?;
// SAFETY: statvfs writes to a zero-initialised struct; we
@@ -649,7 +678,8 @@ fn filesystem_usage(path: &std::path::Path) -> Option<FilesystemUsage> {
let bsize = stat.f_frsize as u64;
let total = stat.f_blocks as u64 * bsize;
let avail = stat.f_bavail as u64 * bsize;
let used = total.saturating_sub(avail);
let free = stat.f_bfree as u64 * bsize;
let used = total.saturating_sub(free);
Some(FilesystemUsage {
mount_point: path.display().to_string(),
total_bytes: total,
@@ -658,6 +688,34 @@ fn filesystem_usage(path: &std::path::Path) -> Option<FilesystemUsage> {
})
}
#[cfg(test)]
mod filesystem_usage_tests {
use super::filesystem_usage;
#[test]
fn used_plus_available_never_exceeds_total() {
// `available` is a subset of the space `used` now excludes
// (used = total - free, and available = f_bavail <= f_bfree),
// so this invariant holds regardless of any root-reserved
// margin -- the regression this guards against is `used`
// being computed as `total - available`, which collapses
// that margin into `used` and can make `used + available`
// overshoot `total` in the other direction (it wouldn't here,
// but the two numbers would silently disagree with `df`).
let fs = filesystem_usage(std::path::Path::new(".")).expect("statvfs on cwd");
assert!(fs.total_bytes > 0);
assert!(fs.used_bytes <= fs.total_bytes);
assert!(fs.available_bytes <= fs.total_bytes.saturating_sub(fs.used_bytes) + 4096,
"available ({}) should fit within total-used ({}) modulo one block; got used={}, total={}",
fs.available_bytes, fs.total_bytes.saturating_sub(fs.used_bytes), fs.used_bytes, fs.total_bytes);
}
#[test]
fn missing_path_returns_none() {
assert!(filesystem_usage(std::path::Path::new("/this/path/does/not/exist/at/all")).is_none());
}
}
/// Query systemd for a user-scope timer's next-fire + last result.
/// Shells out to systemctl. Silent on any failure — dashboards
/// should degrade to "unknown" rather than 500.
@@ -1176,6 +1234,26 @@ impl RpcRouter {
.context("encoding RepoReleaseReply as JSON")?;
Ok(HandlerOutcome::Reply(json))
}
Method::ShutdownPrepCheck => {
let reply = crate::cluster::shutdown_prep::check().await?;
let json = serde_json::to_vec(&reply)
.context("encoding ShutdownPrepCheckReply as JSON")?;
Ok(HandlerOutcome::Reply(json))
}
Method::ShutdownPrepExecute => {
let req: crate::cluster::shutdown_prep::ShutdownPrepExecuteRequest =
match serde_json::from_slice(payload) {
Ok(r) => r,
Err(_) => {
return Ok(HandlerOutcome::Error(ErrorCode::InvalidRequest))
}
};
let reply =
crate::cluster::shutdown_prep::execute(&self.local_name, &req).await?;
let json = serde_json::to_vec(&reply)
.context("encoding ShutdownPrepExecuteReply as JSON")?;
Ok(HandlerOutcome::Reply(json))
}
Method::BlobStat => {
let store = match &self.blob_store {
Some(s) => s,
+39
View File
@@ -229,6 +229,45 @@ pub async fn call_repo_release(
serde_json::from_slice(&reply).context("decoding RepoReleaseReply JSON")
}
/// Convenience wrapper for [`Method::ShutdownPrepCheck`]. Runs
/// `safe-shutdown-prep.sh --dry-run` on the connected peer and waits
/// for the full report. Never stops anything on the peer.
pub async fn call_shutdown_prep_check(
conn: &Connection,
) -> Result<crate::cluster::shutdown_prep::ShutdownPrepCheckReply> {
let req = crate::cluster::shutdown_prep::ShutdownPrepCheckRequest {};
let payload = serde_json::to_vec(&req).context("encoding ShutdownPrepCheckRequest")?;
let reply = rpc_call(conn, Method::ShutdownPrepCheck, &payload).await?;
if reply.len() == 1 {
if let Some(code) = decode_error(reply[0]) {
bail!("peer replied with error: {}", code.describe());
}
}
serde_json::from_slice(&reply).context("decoding ShutdownPrepCheckReply JSON")
}
/// Convenience wrapper for [`Method::ShutdownPrepExecute`]. Starts the
/// real shutdown-prep run on the connected peer (detached — this call
/// returns as soon as the peer confirms it started, not when it
/// finishes, since the peer's own daemon stops itself partway
/// through).
pub async fn call_shutdown_prep_execute(
conn: &Connection,
confirm_node_name: &str,
) -> Result<crate::cluster::shutdown_prep::ShutdownPrepExecuteReply> {
let req = crate::cluster::shutdown_prep::ShutdownPrepExecuteRequest {
confirm_node_name: confirm_node_name.to_string(),
};
let payload = serde_json::to_vec(&req).context("encoding ShutdownPrepExecuteRequest")?;
let reply = rpc_call(conn, Method::ShutdownPrepExecute, &payload).await?;
if reply.len() == 1 {
if let Some(code) = decode_error(reply[0]) {
bail!("peer replied with error: {}", code.describe());
}
}
serde_json::from_slice(&reply).context("decoding ShutdownPrepExecuteReply JSON")
}
/// Recognise a single-byte reply as one of our error codes. Returns
/// `None` for any other single-byte value (which is a valid reply,
/// just an unusually short one).
+174
View File
@@ -0,0 +1,174 @@
//! Peer-side wiring for `deploy/scripts/safe-shutdown-prep.sh`,
//! surfaced through the RPC layer so the dashboard-v2 aggregator can
//! offer a "prepare this node for shutdown" action.
//!
//! Split into two RPCs deliberately:
//!
//! - [`Method::ShutdownPrepCheck`] runs the script's `--dry-run` mode
//! and waits for it to finish. Dry-run never stops this node's own
//! daemon, so the RPC connection survives to deliver the full
//! report — this is the part a browser can meaningfully show.
//! - [`Method::ShutdownPrepExecute`] runs the real script, which (by
//! design) stops `claw-store.service` — i.e. the very process
//! handling this RPC. There is no way to stream a live result past
//! that point, so this RPC detaches the script into its own
//! transient systemd scope (outside this daemon's service cgroup,
//! so `systemctl stop claw-store.service` doesn't take the script
//! down with it) and returns immediately. The full report lands in
//! `SHUTDOWN_PREP_LOG` for whoever is physically at the machine (or
//! over SSH) to read once the node has gone dark.
//!
//! [`Method::ShutdownPrepCheck`]: crate::cluster::rpc::Method::ShutdownPrepCheck
//! [`Method::ShutdownPrepExecute`]: crate::cluster::rpc::Method::ShutdownPrepExecute
use anyhow::{bail, Context, Result};
use serde::{Deserialize, Serialize};
use std::path::PathBuf;
use std::time::Duration;
use tokio::process::Command;
use tokio::time::timeout;
/// Dry-run does a real snapshot + replicate, which can legitimately
/// take a while on a large delta. Generous but bounded so a stuck
/// peer connection doesn't hang the RPC forever.
const CHECK_TIMEOUT: Duration = Duration::from_secs(300);
/// Where the real run's output lands once this node's daemon (and
/// therefore this RPC connection) is gone.
pub const SHUTDOWN_PREP_LOG: &str = "/var/lib/claw-store/shutdown-prep.log";
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct ShutdownPrepCheckRequest {}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct ShutdownPrepCheckReply {
/// True iff the script exited 0 (every guard passed, "SAFE TO
/// POWER OFF" printed for the checked steps).
pub ready: bool,
/// Full combined stdout+stderr from `--dry-run`.
pub output: String,
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct ShutdownPrepExecuteRequest {
/// Defense in depth beyond RPC targeting: the caller must name
/// the exact node it thinks it's shutting down. Checked against
/// this node's own configured name before anything runs.
pub confirm_node_name: String,
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct ShutdownPrepExecuteReply {
pub started: bool,
pub message: String,
pub log_path: String,
}
fn script_path() -> PathBuf {
if let Ok(p) = std::env::var("CLAWSTOR_SHUTDOWN_SCRIPT") {
if !p.is_empty() {
return PathBuf::from(p);
}
}
if let Ok(home) = std::env::var("HOME") {
if !home.is_empty() {
return PathBuf::from(home)
.join("clawstor-deploy/scripts/safe-shutdown-prep.sh");
}
}
PathBuf::from("/usr/local/share/claw-store/safe-shutdown-prep.sh")
}
/// Run `safe-shutdown-prep.sh --dry-run` to completion and report the
/// full output. Never stops anything on this node — safe to call any
/// time, including repeatedly.
pub async fn check() -> Result<ShutdownPrepCheckReply> {
let script = script_path();
if !script.exists() {
bail!("shutdown-prep script not found at {}", script.display());
}
// `2>&1` inside the shell merges stderr into stdout *before*
// either stream is piped back to us, preserving true
// chronological order. Capturing stdout/stderr separately (as
// `Command::output()` does by default) and concatenating them
// after the fact loses interleaving entirely — every stderr line
// lands at the very end regardless of when it was actually
// printed, which makes a mid-script warning (e.g. "replicate not
// configured on this node") look like a failure that happened
// after "DRY RUN COMPLETE".
let run = Command::new("bash")
.arg("-c")
.arg(format!("{} --dry-run 2>&1", script.display()))
.output();
let output = timeout(CHECK_TIMEOUT, run)
.await
.context("shutdown-prep --dry-run timed out")?
.context("spawning shutdown-prep --dry-run")?;
let combined = String::from_utf8_lossy(&output.stdout).into_owned();
Ok(ShutdownPrepCheckReply {
ready: output.status.success(),
output: combined,
})
}
/// Kick off the real (non-dry-run) script in a transient systemd
/// scope detached from this daemon's own service cgroup, then return
/// immediately without waiting for it. The script's own step 6 stops
/// `claw-store.service` — waiting for it to exit here would mean
/// waiting for our own process to be killed.
pub async fn execute(local_node_name: &str, req: &ShutdownPrepExecuteRequest) -> Result<ShutdownPrepExecuteReply> {
if req.confirm_node_name != local_node_name {
bail!(
"confirm_node_name '{}' does not match this node ('{}') — refusing",
req.confirm_node_name,
local_node_name
);
}
let script = script_path();
if !script.exists() {
bail!("shutdown-prep script not found at {}", script.display());
}
let unit = format!(
"clawstor-shutdown-prep-{}",
std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.map(|d| d.as_secs())
.unwrap_or(0)
);
// `--user --scope` places this under the user session's cgroup
// tree (/user.slice/...), a sibling of — not a descendant of —
// /system.slice/claw-store.service. `systemctl stop
// claw-store.service` only tears down its own cgroup, so this
// keeps running (and completes step 6, which stops that very
// service) unaffected.
// Deliberately no --force: the real run re-checks active builds
// and the sync queue itself, even though `check()` may have run
// moments ago — state can change between the two clicks, and
// re-validating is cheap.
let cmd = format!(
"{} >> {} 2>&1",
script.display(),
SHUTDOWN_PREP_LOG
);
let spawn = Command::new("systemd-run")
.arg("--user")
.arg("--scope")
.arg("--collect")
.arg(format!("--unit={unit}"))
.arg("bash")
.arg("-c")
.arg(&cmd)
.spawn();
match spawn {
Ok(_child) => Ok(ShutdownPrepExecuteReply {
started: true,
message: format!(
"shutdown-prep started on {local_node_name} as transient unit {unit}. \
This node's daemon (and dashboard) will go offline as part of the \
process — that is expected. Full output: {SHUTDOWN_PREP_LOG}."
),
log_path: SHUTDOWN_PREP_LOG.to_string(),
}),
Err(e) => Err(e).context("spawning systemd-run for shutdown-prep"),
}
}
+14
View File
@@ -27,12 +27,26 @@ pub struct HotConfig {
#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct WarmConfig {
pub projects_path: PathBuf,
/// Dataset name for `zfs`/`zpool` operations against the warm
/// tier. The literal value `"none"` means this node's warm tier
/// is a plain directory, not ZFS-backed (e.g. a build node with
/// no ZFS pool) — snapshot/replicate become no-ops instead of
/// erroring on a missing `zfs`/`zpool` binary. See
/// [`WarmConfig::zfs_enabled`].
pub zfs_dataset: String,
pub snapshot_retain_hours: u64,
pub snapshot_retain_days: u64,
pub snapshot_retain_weeks: u64,
}
impl WarmConfig {
/// `false` when `zfs_dataset = "none"` — this node's warm tier
/// has no ZFS pool underneath it.
pub fn zfs_enabled(&self) -> bool {
self.zfs_dataset != "none"
}
}
#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct ColdConfig {
pub archive_path: PathBuf,
+16 -10
View File
@@ -188,19 +188,25 @@ pub async fn run(cfg: Config, mut manifest: Manifest) -> Result<()> {
}
}
_ = snap_tick.tick() => {
let ts = chrono::Utc::now().format("%Y-%m-%d-%H%M").to_string();
tracing::info!("taking snapshot {}", ts);
if let Err(e) = snapshot::run_snapshot_cycle(
&zfs, &cfg.warm.zfs_dataset, &ts,
cfg.warm.snapshot_retain_hours as usize,
cfg.warm.snapshot_retain_days as usize,
cfg.warm.snapshot_retain_weeks as usize,
) {
tracing::error!("snapshot failed: {:#}", e);
if !cfg.warm.zfs_enabled() {
tracing::debug!("skipping snapshot tick — zfs_dataset = \"none\" on this node");
} else {
let ts = chrono::Utc::now().format("%Y-%m-%d-%H%M").to_string();
tracing::info!("taking snapshot {}", ts);
if let Err(e) = snapshot::run_snapshot_cycle(
&zfs, &cfg.warm.zfs_dataset, &ts,
cfg.warm.snapshot_retain_hours as usize,
cfg.warm.snapshot_retain_days as usize,
cfg.warm.snapshot_retain_weeks as usize,
) {
tracing::error!("snapshot failed: {:#}", e);
}
}
}
_ = repl_tick.tick() => {
if let Some(rep) = &cfg.replication {
if !cfg.warm.zfs_enabled() {
tracing::debug!("skipping replication tick — zfs_dataset = \"none\" on this node");
} else if let Some(rep) = &cfg.replication {
if let (Some(host), Some(user), Some(dest)) = (
&rep.send_to_host, &rep.send_to_user, &rep.cold_dataset_on_peer
) {
+12
View File
@@ -1502,6 +1502,10 @@ fn cmd_gc(cfg: &Config, manifest: &mut Manifest) -> Result<()> {
}
fn cmd_snapshot(cfg: &Config, zfs: &SystemZfs) -> Result<()> {
if !cfg.warm.zfs_enabled() {
println!("Warm tier is not ZFS-backed on this node (zfs_dataset = \"none\") — nothing to snapshot.");
return Ok(());
}
let ts = chrono::Utc::now().format("%Y-%m-%d-%H%M").to_string();
snapshot::run_snapshot_cycle(
zfs, &cfg.warm.zfs_dataset, &ts,
@@ -1514,6 +1518,10 @@ fn cmd_snapshot(cfg: &Config, zfs: &SystemZfs) -> Result<()> {
}
fn cmd_list_snapshots(cfg: &Config, zfs: &SystemZfs, _project: &str) -> Result<()> {
if !cfg.warm.zfs_enabled() {
println!("Warm tier is not ZFS-backed on this node (zfs_dataset = \"none\").");
return Ok(());
}
let snaps = zfs.list_snapshots(&cfg.warm.zfs_dataset)?;
if snaps.is_empty() { println!("No snapshots found."); return Ok(()); }
for s in &snaps { println!(" {}", s); }
@@ -1531,6 +1539,10 @@ fn cmd_restore(cfg: &Config, zfs: &SystemZfs, project: &str, snap: &str) -> Resu
}
fn cmd_replicate(cfg: &Config, zfs: &SystemZfs) -> Result<()> {
if !cfg.warm.zfs_enabled() {
println!("Warm tier is not ZFS-backed on this node (zfs_dataset = \"none\") — nothing to replicate.");
return Ok(());
}
let rep = cfg.replication.as_ref()
.context("no replication config — this node does not replicate")?;
let host = rep.send_to_host.as_ref().context("send_to_host not set")?;
+108
View File
@@ -570,6 +570,19 @@ impl AuthedCaller {
/// in the request body. Explicit user-supplied workspace is only
/// honored for admin/open — a namespaced caller supplying a
/// mismatched workspace is a forbidden write.
/// Gate for fleet-infrastructure actions (shutdown-prep) that
/// have nothing to do with a tag/repo namespace — a namespaced
/// per-app token has no business stopping a node's services.
pub fn require_admin(&self) -> Result<(), (StatusCode, String)> {
match self {
AuthedCaller::Admin | AuthedCaller::Open => Ok(()),
AuthedCaller::Namespaced { .. } => Err((
StatusCode::FORBIDDEN,
"this action requires an admin token".to_string(),
)),
}
}
pub fn resolve_workspace(&self, requested: Option<&str>) -> Result<String, (StatusCode, String)> {
match self {
AuthedCaller::Admin | AuthedCaller::Open => match requested {
@@ -866,6 +879,93 @@ async fn handle_repos_release(
}))
}
// ── shutdown-prep (targets one specific node, not a fan-out) ──────
#[derive(Serialize)]
pub struct ShutdownPrepCheckResponse {
pub node: String,
pub ready: bool,
pub output: String,
}
async fn handle_shutdown_prep_check(
State(s): State<Arc<V2State>>,
Path(name): Path<String>,
axum::extract::Extension(caller): axum::extract::Extension<AuthedCaller>,
) -> Result<Json<ShutdownPrepCheckResponse>, (StatusCode, String)> {
caller.require_admin()?;
let peer = s
.peers
.iter()
.find(|p| p.name == name)
.cloned()
.ok_or((StatusCode::NOT_FOUND, format!("no peer named {name}")))?;
let conn = s
.dial(&peer)
.await
.map_err(|e| (StatusCode::BAD_GATEWAY, format!("connecting to {name}: {e:#}")))?;
let reply = crate::cluster::rpc::call_shutdown_prep_check(&conn).await;
conn.close(quinn::VarInt::from_u32(0), b"done");
let reply = reply.map_err(|e| (StatusCode::BAD_GATEWAY, format!("{e:#}")))?;
Ok(Json(ShutdownPrepCheckResponse {
node: name,
ready: reply.ready,
output: reply.output,
}))
}
#[derive(Deserialize)]
pub struct ShutdownPrepExecuteBody {
/// Must equal the target node's own name — a second, server-side
/// confirmation beyond "the operator clicked the right button in
/// the UI". Checked again on the peer itself in
/// `shutdown_prep::execute`.
pub confirm_node_name: String,
}
#[derive(Serialize)]
pub struct ShutdownPrepExecuteResponse {
pub node: String,
pub started: bool,
pub message: String,
}
async fn handle_shutdown_prep_execute(
State(s): State<Arc<V2State>>,
Path(name): Path<String>,
axum::extract::Extension(caller): axum::extract::Extension<AuthedCaller>,
Json(body): Json<ShutdownPrepExecuteBody>,
) -> Result<Json<ShutdownPrepExecuteResponse>, (StatusCode, String)> {
caller.require_admin()?;
if body.confirm_node_name != name {
return Err((
StatusCode::BAD_REQUEST,
format!(
"confirm_node_name '{}' does not match target node '{name}'",
body.confirm_node_name
),
));
}
let peer = s
.peers
.iter()
.find(|p| p.name == name)
.cloned()
.ok_or((StatusCode::NOT_FOUND, format!("no peer named {name}")))?;
let conn = s
.dial(&peer)
.await
.map_err(|e| (StatusCode::BAD_GATEWAY, format!("connecting to {name}: {e:#}")))?;
let reply = crate::cluster::rpc::call_shutdown_prep_execute(&conn, &name).await;
conn.close(quinn::VarInt::from_u32(0), b"done");
let reply = reply.map_err(|e| (StatusCode::BAD_GATEWAY, format!("{e:#}")))?;
Ok(Json(ShutdownPrepExecuteResponse {
node: name,
started: reply.started,
message: reply.message,
}))
}
async fn fanout_repo_ensure(
s: &V2State,
req: &crate::cluster::repo_ensure::RepoEnsureRequest,
@@ -1347,6 +1447,14 @@ pub fn build(state: Arc<V2State>) -> Router {
.route("/api/v2/sessions/:id/commit", post(handle_commit_session))
.route("/api/v2/repos/ensure", post(handle_repos_ensure))
.route("/api/v2/repos/release", post(handle_repos_release))
.route(
"/api/v2/node/:name/shutdown-prep/check",
post(handle_shutdown_prep_check),
)
.route(
"/api/v2/node/:name/shutdown-prep/execute",
post(handle_shutdown_prep_execute),
)
.route_layer(axum::middleware::from_fn_with_state(state.clone(), v2_auth))
.with_state(state)
}
+146 -4
View File
@@ -66,6 +66,23 @@ pub fn replicate_to_cold(
remote_user: &str,
remote_host: &str,
remote_dataset: &str,
) -> Result<()> {
replicate_to_cold_with_state_path(
zfs, dataset, remote_user, remote_host, remote_dataset,
std::path::Path::new(LAST_REPLICATED_PATH),
)
}
/// Same as [`replicate_to_cold`] with the state-file path injectable
/// -- lets tests exercise the baseline-recovery logic against a temp
/// file instead of the real `/var/lib/claw-store/...` path.
pub fn replicate_to_cold_with_state_path(
zfs: &dyn ZfsOps,
dataset: &str,
remote_user: &str,
remote_host: &str,
remote_dataset: &str,
state_path: &std::path::Path,
) -> Result<()> {
let snaps = zfs.list_snapshots(dataset)?;
let latest = match snaps.last().cloned() {
@@ -77,12 +94,64 @@ pub fn replicate_to_cold(
};
// Use the last successfully replicated snapshot as the incremental base.
// Only valid if it still exists in the current snapshot list.
let prev = std::fs::read_to_string(LAST_REPLICATED_PATH)
// Only valid if it still exists in the current snapshot list -- local
// retention (snapshot_retain_hours) can prune it out from under us
// between replication runs (e.g. a daemon restart resets the
// replication tick's 24h timer without resetting the hourly-snapshot
// pruning tick, so a slow/interrupted replication cadence can let the
// recorded snapshot age out locally before it's ever used again).
let recorded = std::fs::read_to_string(state_path)
.ok()
.map(|s| s.trim().to_string())
.filter(|s| !s.is_empty() && snaps.contains(s));
// Recorded snapshot is gone -- don't give up and fall back to a full
// send (which fails outright against a non-empty destination, as
// opposed to just being wasteful). Ask the remote what it actually
// has and find the newest snapshot both sides still share, by tag
// (the `@kind-timestamp` suffix -- dataset paths differ between
// source and destination, e.g. slab/projects vs
// data/archive/tank-projects, but tags are written identically).
let prev = match recorded {
Some(p) => Some(p),
None => {
match zfs.list_remote_snapshots(remote_user, remote_host, remote_dataset) {
Ok(remote_snaps) => {
let remote_tags: std::collections::HashSet<&str> = remote_snaps
.iter()
.filter_map(|s| s.split_once('@').map(|(_, tag)| tag))
.collect();
let fallback = snaps
.iter()
.rev()
.skip(1) // exclude `latest` itself
.find(|s| {
s.split_once('@')
.map(|(_, tag)| remote_tags.contains(tag))
.unwrap_or(false)
})
.cloned();
if let Some(f) = &fallback {
tracing::warn!(
"recorded replication baseline was pruned locally; \
recovered a common snapshot from the remote instead: {}",
f
);
}
fallback
}
Err(e) => {
tracing::warn!(
error = %e,
"could not query remote snapshots to recover a replication baseline; \
falling back to full send"
);
None
}
}
}
};
if prev.as_deref() == Some(latest.as_str()) {
tracing::info!("replication already up to date ({})", latest);
return Ok(());
@@ -99,10 +168,10 @@ pub fn replicate_to_cold(
zfs.send_to_remote(&latest, prev.as_deref(), remote_user, remote_host, remote_dataset)?;
// Record this snapshot as the new baseline for the next incremental send.
if let Some(parent) = std::path::Path::new(LAST_REPLICATED_PATH).parent() {
if let Some(parent) = state_path.parent() {
let _ = std::fs::create_dir_all(parent);
}
std::fs::write(LAST_REPLICATED_PATH, &latest)?;
std::fs::write(state_path, &latest)?;
Ok(())
}
@@ -177,4 +246,77 @@ mod tests {
assert!(!is_sunday_midnight("2026-06-29-0000")); // Monday
assert!(!is_sunday_midnight("2026-06-28-0100")); // Sunday but not midnight
}
/// Unique temp path per test so parallel test runs don't clobber
/// each other's replication-baseline state file.
fn temp_state_path(name: &str) -> std::path::PathBuf {
std::env::temp_dir().join(format!("clawstor-test-last-replicated-{name}-{}", std::process::id()))
}
#[test]
fn replicate_uses_recorded_baseline_when_still_present() {
let zfs = MockZfs::default();
zfs.snapshot("slab/projects", "hourly-1").unwrap();
zfs.snapshot("slab/projects", "hourly-2").unwrap();
let state = temp_state_path("recorded-present");
std::fs::write(&state, "slab/projects@hourly-1").unwrap();
replicate_to_cold_with_state_path(
&zfs, "slab/projects", "user", "host", "remote/ds", &state,
).unwrap();
let sends = zfs.sends();
assert_eq!(sends.len(), 1);
assert_eq!(sends[0].0, "slab/projects@hourly-2");
assert_eq!(sends[0].1.as_deref(), Some("slab/projects@hourly-1"));
let _ = std::fs::remove_file(&state);
}
#[test]
fn replicate_recovers_baseline_from_remote_when_recorded_one_was_pruned() {
let zfs = MockZfs::default();
// Local retention already pruned hourly-1 -- only hourly-2 and
// hourly-3 remain locally. The remote, however, still has
// hourly-2 (it just hasn't received hourly-3 yet).
zfs.snapshot("slab/projects", "hourly-2").unwrap();
zfs.snapshot("slab/projects", "hourly-3").unwrap();
zfs.set_remote_snapshots(vec![
"remote/ds@hourly-1".to_string(),
"remote/ds@hourly-2".to_string(),
]);
let state = temp_state_path("recovers-from-remote");
// Recorded baseline (hourly-1) no longer exists locally.
std::fs::write(&state, "slab/projects@hourly-1").unwrap();
replicate_to_cold_with_state_path(
&zfs, "slab/projects", "user", "host", "remote/ds", &state,
).unwrap();
let sends = zfs.sends();
assert_eq!(sends.len(), 1);
assert_eq!(sends[0].0, "slab/projects@hourly-3");
// Recovered hourly-2 as the base by matching tags against the
// remote's actual snapshot list, NOT a full send.
assert_eq!(sends[0].1.as_deref(), Some("slab/projects@hourly-2"));
let _ = std::fs::remove_file(&state);
}
#[test]
fn replicate_falls_back_to_full_send_when_truly_no_common_snapshot() {
let zfs = MockZfs::default();
zfs.snapshot("slab/projects", "hourly-9").unwrap();
zfs.set_remote_snapshots(vec!["remote/ds@hourly-1".to_string()]);
let state = temp_state_path("no-common-snapshot");
let _ = std::fs::remove_file(&state); // no recorded baseline at all
replicate_to_cold_with_state_path(
&zfs, "slab/projects", "user", "host", "remote/ds", &state,
).unwrap();
let sends = zfs.sends();
assert_eq!(sends.len(), 1);
assert_eq!(sends[0].0, "slab/projects@hourly-9");
assert_eq!(sends[0].1, None, "no common tag exists -- must fall back to full send");
let _ = std::fs::remove_file(&state);
}
}
+50 -1
View File
@@ -13,6 +13,12 @@ pub trait ZfsOps: Send + Sync {
remote_user: &str, remote_host: &str,
remote_dataset: &str) -> Result<()>;
fn clone_snapshot(&self, snapshot: &str, dest_dataset: &str) -> Result<()>;
/// List snapshot names (full `dataset@tag` form, remote-side
/// naming) currently on a remote dataset over SSH. Used to find a
/// real incremental base when the locally-recorded one has been
/// pruned -- see `snapshot::replicate_to_cold`.
fn list_remote_snapshots(&self, remote_user: &str, remote_host: &str,
remote_dataset: &str) -> Result<Vec<String>>;
}
pub struct SystemZfs;
@@ -89,11 +95,48 @@ impl ZfsOps for SystemZfs {
}
Ok(())
}
fn list_remote_snapshots(&self, remote_user: &str, remote_host: &str,
remote_dataset: &str) -> Result<Vec<String>> {
let out = std::process::Command::new("ssh")
.args([
&format!("{remote_user}@{remote_host}"),
"zfs", "list", "-H", "-t", "snapshot", "-o", "name", "-r", remote_dataset,
])
.output()
.context("running ssh zfs list on remote")?;
if !out.status.success() {
bail!("remote zfs list failed: {}", String::from_utf8_lossy(&out.stderr));
}
Ok(String::from_utf8_lossy(&out.stdout)
.lines()
.filter(|l| !l.is_empty())
.map(String::from)
.collect())
}
}
#[derive(Default, Clone)]
pub struct MockZfs {
snapshots: Arc<Mutex<Vec<String>>>,
/// Configurable via `set_remote_snapshots` -- what
/// `list_remote_snapshots` returns, for exercising the
/// baseline-recovery path in `snapshot::replicate_to_cold`.
remote_snapshots: Arc<Mutex<Vec<String>>>,
/// Every `send_to_remote` call, recorded as `(snapshot,
/// incremental_from)`, so tests can assert which base was
/// actually used.
sends: Arc<Mutex<Vec<(String, Option<String>)>>>,
}
impl MockZfs {
pub fn set_remote_snapshots(&self, snaps: Vec<String>) {
*self.remote_snapshots.lock().unwrap() = snaps;
}
pub fn sends(&self) -> Vec<(String, Option<String>)> {
self.sends.lock().unwrap().clone()
}
}
impl ZfsOps for MockZfs {
@@ -115,8 +158,9 @@ impl ZfsOps for MockZfs {
Ok(())
}
fn send_to_remote(&self, _snap: &str, _incr: Option<&str>,
fn send_to_remote(&self, snap: &str, incr: Option<&str>,
_user: &str, _host: &str, _dest: &str) -> Result<()> {
self.sends.lock().unwrap().push((snap.to_string(), incr.map(String::from)));
Ok(())
}
@@ -125,6 +169,11 @@ impl ZfsOps for MockZfs {
.push(format!("{} -> {}", snapshot, dest_dataset));
Ok(())
}
fn list_remote_snapshots(&self, _remote_user: &str, _remote_host: &str,
_remote_dataset: &str) -> Result<Vec<String>> {
Ok(self.remote_snapshots.lock().unwrap().clone())
}
}
#[cfg(test)]
+1 -1
View File
@@ -24,7 +24,7 @@ export function NodeCard({ node }) {
border,
].join(' '), children: [_jsxs("div", { className: "flex items-center justify-between", children: [_jsxs("div", { className: "flex items-center gap-2", children: [_jsx("span", { className: `inline-block w-2.5 h-2.5 rounded-full ${dot}` }), _jsx("span", { className: "text-lg font-semibold text-slate-100", children: node.node_name })] }), _jsx("span", { className: "text-xs text-slate-500 font-mono", children: node.zone || '—' })] }), !node.online && (_jsx("div", { className: "text-sm text-red-400 break-words", children: node.error ?? 'offline' })), node.online && (_jsxs(_Fragment, { children: [node.filesystem && (_jsx(StorageBar, { label: "disk", used: node.filesystem.used_bytes, total: node.filesystem.total_bytes })), node.hot && node.hot.max_bytes > 0 && (_jsx(StorageBar, { label: "hot tier", used: node.hot.used_bytes, total: node.hot.max_bytes, pinned: node.hot.pinned_bytes ?? undefined })), _jsxs("div", { className: "grid grid-cols-2 gap-y-1 text-sm", children: [_jsx("span", { className: "text-slate-500", children: "mount" }), _jsx("span", { className: "text-right font-mono text-xs", children: node.mount?.active ? (_jsx("span", { className: "text-emerald-300", children: "\u2713 mounted" })) : (_jsx("span", { className: "text-slate-500", children: "not mounted" })) }), _jsx("span", { className: "text-slate-500", children: "cache hit rate" }), _jsx("span", { className: "text-right font-mono text-xs", children: node.cache && node.cache.hits + node.cache.misses > 0
? `${Math.round(node.cache.hit_rate * 100)}%`
: _jsx("span", { className: "text-slate-500", children: "idle" }) }), _jsx("span", { className: "text-slate-500", children: "next scheduled job" }), _jsx("span", { className: "text-right font-mono text-xs", children: nextTimer(node) })] })] }))] }) }));
: _jsx("span", { className: "text-slate-500", children: "idle" }) }), _jsx("span", { className: "text-slate-500", children: "next scheduled job" }), _jsx("span", { className: "text-right font-mono text-xs", children: nextTimer(node) })] })] })), _jsx("div", { className: "pt-1 border-t border-slate-800 text-xs text-slate-500", children: "view detail \u00B7 maintenance & shutdown prep \u2192" })] }) }));
}
function healthOf(n) {
if (!n.online)
+4
View File
@@ -95,6 +95,10 @@ export function NodeCard({ node }: Props) {
</div>
</>
)}
<div className="pt-1 border-t border-slate-800 text-xs text-slate-500">
view detail · maintenance & shutdown prep →
</div>
</a>
</Link>
);
@@ -0,0 +1,44 @@
import { jsx as _jsx, jsxs as _jsxs, Fragment as _Fragment } from "react/jsx-runtime";
import { useState } from 'react';
import { api } from '../lib/api';
/**
* Node-maintenance panel: runs `safe-shutdown-prep.sh --dry-run` on
* demand (safe, read-mostly, never stops anything) and — only once
* that comes back ready — unlocks a type-to-confirm button that
* starts the real run.
*
* The real run is fire-and-forget by necessity: its own steps stop
* this node's daemon, which is what's serving this very page, so
* there is no way to stream a live result past that point. Once
* started, the UI says so plainly and points at the on-disk log for
* the full report.
*/
export function ShutdownPrepPanel({ name }) {
const [check, setCheck] = useState({ phase: 'idle' });
const [exec, setExec] = useState({ phase: 'idle' });
const [confirmText, setConfirmText] = useState('');
const runCheck = () => {
setCheck({ phase: 'checking' });
setExec({ phase: 'idle' });
setConfirmText('');
api
.shutdownPrepCheck(name)
.then((r) => setCheck({ phase: 'done', ready: r.ready, output: r.output }))
.catch((e) => setCheck({ phase: 'error', message: String(e) }));
};
const runExecute = () => {
if (confirmText !== name)
return;
setExec({ phase: 'starting' });
api
.shutdownPrepExecute(name, confirmText)
.then((r) => setExec({ phase: 'started', message: r.message }))
.catch((e) => setExec({ phase: 'error', message: String(e) }));
};
const ready = check.phase === 'done' && check.ready;
return (_jsxs("div", { className: "rounded border border-slate-800 bg-slate-900/40 p-4 text-sm space-y-3", children: [_jsxs("div", { className: "flex items-center justify-between", children: [_jsx("div", { className: "text-slate-500 uppercase text-xs tracking-wider", children: "shutdown prep" }), _jsx("button", { onClick: runCheck, disabled: check.phase === 'checking', className: "px-3 py-1.5 rounded bg-slate-800 hover:bg-slate-700 text-slate-200 text-xs disabled:opacity-50", children: check.phase === 'checking' ? 'checking…' : 'check readiness for shutdown' })] }), _jsxs("p", { className: "text-xs text-slate-500", children: ["Runs a dry-run of the pre-shutdown checklist on ", _jsx("span", { className: "font-mono", children: name }), ' ', "\u2014 active builds, pending peer sync, a final snapshot + replicate to cold. Nothing is stopped or unmounted by this check."] }), check.phase === 'error' && (_jsx("div", { className: "rounded border border-red-800 bg-red-950/40 p-3 text-red-300 text-xs", children: check.message })), check.phase === 'done' && (_jsxs(_Fragment, { children: [_jsx("div", { className: `rounded border p-3 text-xs ${check.ready
? 'border-emerald-800 bg-emerald-950/40 text-emerald-300'
: 'border-amber-800 bg-amber-950/40 text-amber-300'}`, children: check.ready
? '✓ ready — safe to start the real shutdown-prep run'
: '! not ready — see output below (active build or un-synced changes are the usual cause)' }), _jsx("pre", { className: "max-h-72 overflow-auto rounded bg-slate-950 border border-slate-800 p-3 text-[11px] leading-relaxed text-slate-300 whitespace-pre-wrap", children: check.output })] })), ready && exec.phase !== 'started' && (_jsxs("div", { className: "rounded border border-red-900 bg-red-950/30 p-3 space-y-2", children: [_jsxs("div", { className: "text-red-300 text-xs", children: ["This starts the real run: stops maintenance timers, the dashboard, the storage daemon (gossip announces departure to peers), and unmounts FUSE on", ' ', _jsx("span", { className: "font-mono", children: name }), ". The node's dashboard connection will drop partway through \u2014 that's expected, not an error. It does ", _jsx("strong", { children: "not" }), " power the machine off; do that yourself once it's gone dark."] }), _jsxs("div", { className: "flex items-center gap-2", children: [_jsx("input", { value: confirmText, onChange: (e) => setConfirmText(e.target.value), placeholder: `type "${name}" to confirm`, className: "flex-1 rounded bg-slate-900 border border-slate-700 px-2 py-1.5 text-xs font-mono text-slate-200 placeholder:text-slate-600" }), _jsx("button", { onClick: runExecute, disabled: confirmText !== name || exec.phase === 'starting', className: "px-3 py-1.5 rounded bg-red-900 hover:bg-red-800 text-red-100 text-xs disabled:opacity-40 disabled:cursor-not-allowed whitespace-nowrap", children: exec.phase === 'starting' ? 'starting…' : `stop services on ${name}` })] })] })), exec.phase === 'error' && (_jsx("div", { className: "rounded border border-red-800 bg-red-950/40 p-3 text-red-300 text-xs", children: exec.message })), exec.phase === 'started' && (_jsx("div", { className: "rounded border border-sky-800 bg-sky-950/30 p-3 text-sky-300 text-xs", children: exec.message }))] }));
}
@@ -0,0 +1,144 @@
import { useState } from 'react';
import { api } from '../lib/api';
interface Props {
name: string;
}
type CheckState =
| { phase: 'idle' }
| { phase: 'checking' }
| { phase: 'done'; ready: boolean; output: string }
| { phase: 'error'; message: string };
type ExecState =
| { phase: 'idle' }
| { phase: 'starting' }
| { phase: 'started'; message: string }
| { phase: 'error'; message: string };
/**
* Node-maintenance panel: runs `safe-shutdown-prep.sh --dry-run` on
* demand (safe, read-mostly, never stops anything) and — only once
* that comes back ready — unlocks a type-to-confirm button that
* starts the real run.
*
* The real run is fire-and-forget by necessity: its own steps stop
* this node's daemon, which is what's serving this very page, so
* there is no way to stream a live result past that point. Once
* started, the UI says so plainly and points at the on-disk log for
* the full report.
*/
export function ShutdownPrepPanel({ name }: Props) {
const [check, setCheck] = useState<CheckState>({ phase: 'idle' });
const [exec, setExec] = useState<ExecState>({ phase: 'idle' });
const [confirmText, setConfirmText] = useState('');
const runCheck = () => {
setCheck({ phase: 'checking' });
setExec({ phase: 'idle' });
setConfirmText('');
api
.shutdownPrepCheck(name)
.then((r) => setCheck({ phase: 'done', ready: r.ready, output: r.output }))
.catch((e) => setCheck({ phase: 'error', message: String(e) }));
};
const runExecute = () => {
if (confirmText !== name) return;
setExec({ phase: 'starting' });
api
.shutdownPrepExecute(name, confirmText)
.then((r) => setExec({ phase: 'started', message: r.message }))
.catch((e) => setExec({ phase: 'error', message: String(e) }));
};
const ready = check.phase === 'done' && check.ready;
return (
<div className="rounded border border-slate-800 bg-slate-900/40 p-4 text-sm space-y-3">
<div className="flex items-center justify-between">
<div className="text-slate-500 uppercase text-xs tracking-wider">
shutdown prep
</div>
<button
onClick={runCheck}
disabled={check.phase === 'checking'}
className="px-3 py-1.5 rounded bg-slate-800 hover:bg-slate-700 text-slate-200 text-xs disabled:opacity-50"
>
{check.phase === 'checking' ? 'checking…' : 'check readiness for shutdown'}
</button>
</div>
<p className="text-xs text-slate-500">
Runs a dry-run of the pre-shutdown checklist on <span className="font-mono">{name}</span>{' '}
— active builds, pending peer sync, a final snapshot + replicate to cold. Nothing is
stopped or unmounted by this check.
</p>
{check.phase === 'error' && (
<div className="rounded border border-red-800 bg-red-950/40 p-3 text-red-300 text-xs">
{check.message}
</div>
)}
{check.phase === 'done' && (
<>
<div
className={`rounded border p-3 text-xs ${
check.ready
? 'border-emerald-800 bg-emerald-950/40 text-emerald-300'
: 'border-amber-800 bg-amber-950/40 text-amber-300'
}`}
>
{check.ready
? '✓ ready — safe to start the real shutdown-prep run'
: '! not ready — see output below (active build or un-synced changes are the usual cause)'}
</div>
<pre className="max-h-72 overflow-auto rounded bg-slate-950 border border-slate-800 p-3 text-[11px] leading-relaxed text-slate-300 whitespace-pre-wrap">
{check.output}
</pre>
</>
)}
{ready && exec.phase !== 'started' && (
<div className="rounded border border-red-900 bg-red-950/30 p-3 space-y-2">
<div className="text-red-300 text-xs">
This starts the real run: stops maintenance timers, the dashboard, the storage
daemon (gossip announces departure to peers), and unmounts FUSE on{' '}
<span className="font-mono">{name}</span>. The node's dashboard connection will drop
partway through — that's expected, not an error. It does <strong>not</strong> power
the machine off; do that yourself once it's gone dark.
</div>
<div className="flex items-center gap-2">
<input
value={confirmText}
onChange={(e) => setConfirmText(e.target.value)}
placeholder={`type "${name}" to confirm`}
className="flex-1 rounded bg-slate-900 border border-slate-700 px-2 py-1.5 text-xs font-mono text-slate-200 placeholder:text-slate-600"
/>
<button
onClick={runExecute}
disabled={confirmText !== name || exec.phase === 'starting'}
className="px-3 py-1.5 rounded bg-red-900 hover:bg-red-800 text-red-100 text-xs disabled:opacity-40 disabled:cursor-not-allowed whitespace-nowrap"
>
{exec.phase === 'starting' ? 'starting…' : `stop services on ${name}`}
</button>
</div>
</div>
)}
{exec.phase === 'error' && (
<div className="rounded border border-red-800 bg-red-950/40 p-3 text-red-300 text-xs">
{exec.message}
</div>
)}
{exec.phase === 'started' && (
<div className="rounded border border-sky-800 bg-sky-950/30 p-3 text-sky-300 text-xs">
{exec.message}
</div>
)}
</div>
);
}
+17
View File
@@ -23,6 +23,19 @@ async function get(path) {
}
return resp.json();
}
async function post(path, body) {
const full = `${API_BASE}${path}`;
const resp = await fetch(full, {
method: 'POST',
headers: { Accept: 'application/json', 'Content-Type': 'application/json' },
body: body === undefined ? undefined : JSON.stringify(body),
});
if (!resp.ok) {
const text = await resp.text().catch(() => '');
throw new Error(`${full} → ${resp.status} ${resp.statusText}${text ? `: ${text}` : ''}`);
}
return resp.json();
}
export const api = {
fleet: () => get('/v2/fleet'),
projects: () => get('/v2/projects'),
@@ -32,6 +45,10 @@ export const api = {
refs: (limit = 200, offset = 0) => get(`/v2/storage/refs?limit=${limit}&offset=${offset}`),
snapshots: () => get('/v2/storage/snapshots'),
refTracking: (repo = '') => get(`/v2/storage/ref-tracking?repo=${encodeURIComponent(repo)}`),
shutdownPrepCheck: (name) => post(`/v2/node/${name}/shutdown-prep/check`),
shutdownPrepExecute: (name, confirmNodeName) => post(`/v2/node/${name}/shutdown-prep/execute`, {
confirm_node_name: confirmNodeName,
}),
};
/** Format bytes as MB / GB / TB as needed. */
export function fmtBytes(n) {
+32
View File
@@ -119,6 +119,20 @@ async function get<T>(path: string): Promise<T> {
return resp.json();
}
async function post<T>(path: string, body?: unknown): Promise<T> {
const full = `${API_BASE}${path}`;
const resp = await fetch(full, {
method: 'POST',
headers: { Accept: 'application/json', 'Content-Type': 'application/json' },
body: body === undefined ? undefined : JSON.stringify(body),
});
if (!resp.ok) {
const text = await resp.text().catch(() => '');
throw new Error(`${full} → ${resp.status} ${resp.statusText}${text ? `: ${text}` : ''}`);
}
return resp.json();
}
// All paths are relative to API_BASE. E.g. '/v2/fleet' becomes
// '/api/v2/fleet' locally or '/clawstor/api/v2/fleet' via Tailscale.
export interface ProjectRow {
@@ -145,8 +159,26 @@ export const api = {
snapshots: () => get<SnapshotSummary[]>('/v2/storage/snapshots'),
refTracking: (repo = '') =>
get<RefTrackingItem[]>(`/v2/storage/ref-tracking?repo=${encodeURIComponent(repo)}`),
shutdownPrepCheck: (name: string) =>
post<ShutdownPrepCheckResponse>(`/v2/node/${name}/shutdown-prep/check`),
shutdownPrepExecute: (name: string, confirmNodeName: string) =>
post<ShutdownPrepExecuteResponse>(`/v2/node/${name}/shutdown-prep/execute`, {
confirm_node_name: confirmNodeName,
}),
};
export interface ShutdownPrepCheckResponse {
node: string;
ready: boolean;
output: string;
}
export interface ShutdownPrepExecuteResponse {
node: string;
started: boolean;
message: string;
}
/** Format bytes as MB / GB / TB as needed. */
export function fmtBytes(n: number): string {
if (n < 1024) return `${n} B`;
+2 -1
View File
@@ -3,6 +3,7 @@ import { useEffect, useState } from 'react';
import { Link } from 'wouter';
import { api, fmtBytes } from '../lib/api';
import { StatTile } from '../components/StatTile';
import { ShutdownPrepPanel } from '../components/ShutdownPrepPanel';
export function NodeDetail({ name }) {
const [status, setStatus] = useState(null);
const [err, setErr] = useState(null);
@@ -15,5 +16,5 @@ export function NodeDetail({ name }) {
})
.catch((e) => setErr(String(e)));
}, [name]);
return (_jsxs("div", { className: "space-y-6", children: [_jsxs("div", { children: [_jsx(Link, { href: "/", children: _jsx("a", { className: "text-sm text-slate-500 hover:text-slate-300", children: "\u2190 fleet" }) }), _jsx("h1", { className: "text-2xl font-semibold text-slate-100 mt-2", children: name })] }), err && (_jsxs("div", { className: "rounded border border-amber-800 bg-amber-950/40 p-3 text-amber-300 text-sm", children: [err, _jsxs("div", { className: "mt-2 text-xs text-slate-400", children: ["Cross-node lookup lands in a follow-on PR. Until then this page shows detail only when you're already viewing the dashboard hosted by ", name, ". Try opening", ' ', _jsxs("span", { className: "font-mono", children: ["http://", name, ":7700/v2/#/nodes/", name] }), ' ', "directly."] })] })), status && (_jsxs(_Fragment, { children: [_jsxs("div", { className: "grid grid-cols-2 sm:grid-cols-3 lg:grid-cols-6 gap-3", children: [_jsx(StatTile, { label: "blobs", value: status.blob_count.toLocaleString(), color: "ok" }), _jsx(StatTile, { label: "tags", value: status.tag_count, color: "ok" }), _jsx(StatTile, { label: "refs", value: status.ref_count, color: "ok" }), _jsx(StatTile, { label: "snapshots", value: status.snapshot_count, color: "ok" }), _jsx(StatTile, { label: "ref-tracking", value: status.ref_tracking_count, color: "ok" }), _jsx(StatTile, { label: "store size", value: fmtBytes(status.blob_store_bytes), color: "ok" })] }), _jsxs("div", { className: "rounded border border-slate-800 bg-slate-900/40 p-4 text-sm", children: [_jsx("div", { className: "text-slate-500 uppercase text-xs tracking-wider", children: "blob store root" }), _jsx("div", { className: "font-mono mt-1", children: status.blob_store_root ?? '—' })] })] }))] }));
return (_jsxs("div", { className: "space-y-6", children: [_jsxs("div", { children: [_jsx(Link, { href: "/", children: _jsx("a", { className: "text-sm text-slate-500 hover:text-slate-300", children: "\u2190 fleet" }) }), _jsx("h1", { className: "text-2xl font-semibold text-slate-100 mt-2", children: name })] }), err && (_jsxs("div", { className: "rounded border border-amber-800 bg-amber-950/40 p-3 text-amber-300 text-sm", children: [err, _jsxs("div", { className: "mt-2 text-xs text-slate-400", children: ["Cross-node lookup lands in a follow-on PR. Until then this page shows detail only when you're already viewing the dashboard hosted by ", name, ". Try opening", ' ', _jsxs("span", { className: "font-mono", children: ["http://", name, ":7700/v2/#/nodes/", name] }), ' ', "directly."] })] })), status && (_jsxs(_Fragment, { children: [_jsxs("div", { className: "grid grid-cols-2 sm:grid-cols-3 lg:grid-cols-6 gap-3", children: [_jsx(StatTile, { label: "blobs", value: status.blob_count.toLocaleString(), color: "ok" }), _jsx(StatTile, { label: "tags", value: status.tag_count, color: "ok" }), _jsx(StatTile, { label: "refs", value: status.ref_count, color: "ok" }), _jsx(StatTile, { label: "snapshots", value: status.snapshot_count, color: "ok" }), _jsx(StatTile, { label: "ref-tracking", value: status.ref_tracking_count, color: "ok" }), _jsx(StatTile, { label: "store size", value: fmtBytes(status.blob_store_bytes), color: "ok" })] }), _jsxs("div", { className: "rounded border border-slate-800 bg-slate-900/40 p-4 text-sm", children: [_jsx("div", { className: "text-slate-500 uppercase text-xs tracking-wider", children: "blob store root" }), _jsx("div", { className: "font-mono mt-1", children: status.blob_store_root ?? '—' })] }), _jsx(ShutdownPrepPanel, { name: name })] }))] }));
}
+3
View File
@@ -2,6 +2,7 @@ import { useEffect, useState } from 'react';
import { Link } from 'wouter';
import { api, NodeStatusV2, fmtBytes } from '../lib/api';
import { StatTile } from '../components/StatTile';
import { ShutdownPrepPanel } from '../components/ShutdownPrepPanel';
interface Props {
name: string;
@@ -67,6 +68,8 @@ export function NodeDetail({ name }: Props) {
</div>
<div className="font-mono mt-1">{status.blob_store_root ?? '—'}</div>
</div>
<ShutdownPrepPanel name={name} />
</>
)}
</div>
+1 -1
View File
@@ -1 +1 @@
{"root":["./src/App.tsx","./src/main.tsx","./src/components/NodeCard.tsx","./src/components/ProjectsPanel.tsx","./src/components/StatTile.tsx","./src/components/StorageBar.tsx","./src/lib/api.ts","./src/pages/CommandCenter.tsx","./src/pages/NodeDetail.tsx","./src/pages/RefTrackingPage.tsx","./src/pages/StorageBrowser.tsx"],"version":"6.0.3"}
{"root":["./src/App.tsx","./src/main.tsx","./src/components/NodeCard.tsx","./src/components/ProjectsPanel.tsx","./src/components/ShutdownPrepPanel.tsx","./src/components/StatTile.tsx","./src/components/StorageBar.tsx","./src/lib/api.ts","./src/pages/CommandCenter.tsx","./src/pages/NodeDetail.tsx","./src/pages/RefTrackingPage.tsx","./src/pages/StorageBrowser.tsx"],"version":"6.0.3"}
+14 -7
View File
@@ -211,13 +211,20 @@ step "flushing filesystem buffers"
sync
ok "sync complete"
POOL=$(mount | awk '/on \/slab / {print $1}')
if [ -n "$POOL" ]; then
step "zpool health check ($POOL)"
zpool status -x "$POOL" 2>&1 | sed 's/^/ /'
if [ "$EXPORT_ZPOOL" -eq 1 ]; then
step "exporting $POOL (--export-zpool)"
run sudo zpool export "$POOL" && ok "exported — remember: zpool import $POOL after reboot" || fail "export failed"
step "zpool health check"
if ! command -v zpool >/dev/null 2>&1; then
ok "no zpool binary on this node — warm tier is not ZFS-backed here, nothing to check"
else
POOL=$(df --output=source /slab 2>/dev/null | tail -1 | tr -d '[:space:]')
if [ -n "$POOL" ] && [ "$POOL" != "none" ]; then
echo " pool: $POOL"
zpool status -x "$POOL" 2>&1 | sed 's/^/ /'
if [ "$EXPORT_ZPOOL" -eq 1 ]; then
step "exporting $POOL (--export-zpool)"
run sudo zpool export "$POOL" && ok "exported — remember: zpool import $POOL after reboot" || fail "export failed"
fi
else
warn "zpool present but /slab isn't a recognizable ZFS mount"
fi
fi