diff --git a/crates/metadb-raft/src/group_host.rs b/crates/metadb-raft/src/group_host.rs index 7147af7..1ed72c4 100644 --- a/crates/metadb-raft/src/group_host.rs +++ b/crates/metadb-raft/src/group_host.rs @@ -42,8 +42,12 @@ where configs.into_iter().flatten().collect() } -/// Tuning parameters for OpenRaft timers and snapshot policies. -#[derive(Debug, Clone)] +/// Tuning parameters for OpenRaft timers and the segmented log. +/// +/// Loaded from the `[raft]` table. Unknown keys in that table fail parsing. +/// The values are read once at process start and are not reloaded while Raft is running. +#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(deny_unknown_fields, default)] pub struct RaftNodeOptions { pub heartbeat_interval_ms: u64, pub election_timeout_min_ms: u64, @@ -64,6 +68,63 @@ impl Default for RaftNodeOptions { } } +impl RaftNodeOptions { + /// Checks the same OpenRaft timer inequalities `ShardRaftGroup::start` applies, + /// plus a non-zero segment size. A zero segment would open a new file on every append. + pub fn validate(&self) -> Result<()> { + if self.max_segment_bytes == 0 { + return Err(MetaDbError::CodecError( + "invalid [raft] options: max_segment_bytes must be at least 1".to_string(), + )); + } + Config { + cluster_name: "metadb-raft-options".to_string(), + heartbeat_interval: self.heartbeat_interval_ms, + election_timeout_min: self.election_timeout_min_ms, + election_timeout_max: self.election_timeout_max_ms, + max_in_snapshot_log_to_keep: self.max_in_snapshot_log_to_keep, + purge_batch_size: 256, + ..Default::default() + } + .validate() + .map(|_| ()) + .map_err(|error| { + MetaDbError::CodecError(format!( + "invalid [raft] options: {error}. election_timeout_min_ms must be greater than heartbeat_interval_ms and less than election_timeout_max_ms" + )) + }) + } +} + +/// `replay_state` values stored on a shard group. +pub(crate) const REPLAY_NOT_REQUIRED: u8 = 0; +pub(crate) const REPLAY_CAUGHT_UP: u8 = 1; +pub(crate) const REPLAY_WAITING: u8 = 2; + +/// Startup replay is still incomplete when the wait timed out and the state +/// machine has not applied the committed or purged index captured at open. +pub fn replay_still_pending(state: u8, target: u64, applied_index: Option) -> bool { + if state != REPLAY_WAITING { + return false; + } + match applied_index { + Some(index) => index < target, + None => true, + } +} + +/// Facts a readiness probe may use. No addresses, paths, or log payloads. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct ShardServeView { + pub leader_known: bool, + pub applied: bool, + pub voter: bool, + pub recovery_pending: bool, + pub storage_unrecoverable: bool, + pub stopped: bool, + pub fatal: bool, +} + /// Parks `client_write` callers inside `propose` until a failure test releases them. /// /// Production leaves the gate unarmed, so `enter` returns immediately. A test arms it, @@ -174,6 +235,9 @@ pub struct ShardRaftGroup { testing_epoch_mismatch: std::sync::atomic::AtomicU32, testing_log_discarded: std::sync::atomic::AtomicU32, testing_read_quorum: std::sync::atomic::AtomicU32, + replay_state: std::sync::atomic::AtomicU8, + replay_target: std::sync::atomic::AtomicU64, + stopped: AtomicBool, } impl ShardRaftGroup { @@ -238,9 +302,28 @@ impl ShardRaftGroup { // Replay a committed tail into the WAL-less memtable before serving. // A fresh log has no committed entry, and the recovery condition stays // false until initialize, so waiting here only burns the timeout. - if log_store.has_committed_entries() { + // A timeout does not fail open: the group records the target index and + // stays unready until apply catches it. + let replay_target = log_store.committed_or_purged_index(); + let replay_state = if let Some(target) = replay_target { + match raft.wait_for_recovery(Some(Duration::from_secs(5))).await { + Ok(_) => REPLAY_CAUGHT_UP, + Err(error) => { + tracing::warn!( + shard_id, + target, + error = %error, + "raft startup replay did not finish; this shard stays unready until the applied index catches the startup commit" + ); + REPLAY_WAITING + } + } + } else if log_store.has_committed_entries() { let _ = raft.wait_for_recovery(Some(Duration::from_secs(5))).await; - } + REPLAY_NOT_REQUIRED + } else { + REPLAY_NOT_REQUIRED + }; if let Some(reason) = state_machine.storage_unrecoverable() { return Err(MetaDbError::StorageIoError(format!( @@ -266,6 +349,9 @@ impl ShardRaftGroup { testing_epoch_mismatch: std::sync::atomic::AtomicU32::new(0), testing_log_discarded: std::sync::atomic::AtomicU32::new(0), testing_read_quorum: std::sync::atomic::AtomicU32::new(0), + replay_state: std::sync::atomic::AtomicU8::new(replay_state), + replay_target: std::sync::atomic::AtomicU64::new(replay_target.unwrap_or(0)), + stopped: AtomicBool::new(false), }); router.register_local_proposer(shard_id, group.clone()); Ok(group) @@ -396,6 +482,32 @@ impl ShardRaftGroup { &self.state_machine } + /// Local facts for a readiness probe. The strings on an unrecoverable + /// snapshot stay inside the process; the view only carries a boolean. + pub fn serve_view(&self) -> ShardServeView { + let metrics = self.raft.metrics(); + let snapshot = metrics.borrow_watched(); + let applied_index = snapshot.last_applied.as_ref().map(|id| id.index); + let voter = snapshot + .membership_config + .membership() + .voter_ids() + .any(|id| id == self.node_id); + ShardServeView { + leader_known: snapshot.current_leader.is_some(), + applied: applied_index.is_some(), + voter, + recovery_pending: replay_still_pending( + self.replay_state.load(Ordering::Acquire), + self.replay_target.load(Ordering::Acquire), + applied_index, + ), + storage_unrecoverable: self.storage_unrecoverable().is_some(), + stopped: self.stopped.load(Ordering::Acquire), + fatal: snapshot.running_state.is_err(), + } + } + /// `Some` when this process must not be reported as a live voter. pub fn storage_unrecoverable(&self) -> Option { self.state_machine.storage_unrecoverable() @@ -881,6 +993,7 @@ impl ShardRaftGroup { } pub async fn shutdown(&self) -> Result<()> { + self.stopped.store(true, Ordering::Release); self.raft .shutdown() .await @@ -1161,4 +1274,42 @@ mod tests { let kept = normalize_discarded_legacy(&enveloped, discarded); assert!(kept.is_retryable_write_consensus(), "{kept}"); } + + #[test] + fn replay_pending_tracks_the_startup_commit_only() { + assert!(!replay_still_pending(REPLAY_NOT_REQUIRED, 10, None)); + assert!(!replay_still_pending(REPLAY_CAUGHT_UP, 10, None)); + assert!(replay_still_pending(REPLAY_WAITING, 10, None)); + assert!(replay_still_pending(REPLAY_WAITING, 10, Some(9))); + assert!(!replay_still_pending(REPLAY_WAITING, 10, Some(10))); + assert!(!replay_still_pending(REPLAY_WAITING, 10, Some(11))); + } + + #[test] + fn default_raft_options_match_the_openraft_inequalities() { + let options = RaftNodeOptions::default(); + options.validate().expect("built-in defaults must start"); + assert_eq!(options.heartbeat_interval_ms, 150); + assert_eq!(options.election_timeout_min_ms, 450); + assert_eq!(options.election_timeout_max_ms, 900); + assert_eq!(options.max_in_snapshot_log_to_keep, 0); + assert_eq!(options.max_segment_bytes, 64 * 1024 * 1024); + } + + #[test] + fn raft_option_bounds_fail_before_a_group_starts() { + let mut options = RaftNodeOptions::default(); + options.max_segment_bytes = 0; + assert!(options.validate().is_err()); + + options = RaftNodeOptions::default(); + options.heartbeat_interval_ms = 450; + let heartbeat = options.validate().unwrap_err().to_string(); + assert!(heartbeat.contains("invalid [raft] options"), "{heartbeat}"); + + options = RaftNodeOptions::default(); + options.election_timeout_min_ms = 900; + options.election_timeout_max_ms = 900; + assert!(options.validate().is_err()); + } } diff --git a/crates/metadb-raft/src/lib.rs b/crates/metadb-raft/src/lib.rs index f58a522..36569a3 100644 --- a/crates/metadb-raft/src/lib.rs +++ b/crates/metadb-raft/src/lib.rs @@ -15,7 +15,8 @@ pub use backup::{ }; pub use conf_change::{ConfChangeOrchestrator, DEFAULT_LEARNER_CATCHUP_THRESHOLD_ENTRIES}; pub use group_host::{ - ProposalShutdownGate, RaftNodeOptions, RegistryShardState, ShardGroupHost, ShardRaftGroup, + replay_still_pending, ProposalShutdownGate, RaftNodeOptions, RegistryShardState, + ShardGroupHost, ShardRaftGroup, ShardServeView, }; pub use log_store::SegmentedRaftLogStore; pub use network::{ diff --git a/crates/metadb-raft/src/log_store.rs b/crates/metadb-raft/src/log_store.rs index 9ec26bd..0bbc48a 100644 --- a/crates/metadb-raft/src/log_store.rs +++ b/crates/metadb-raft/src/log_store.rs @@ -789,6 +789,25 @@ impl SegmentedRaftLogStore { || !guard.entries.is_empty() } + /// Commit or purge index that startup replay must apply before the shard can serve. + /// + /// `None` when the store has neither. A non-empty uncommitted tail does not + /// count: those entries are not yet a committed prefix the state machine must replay. + pub fn committed_or_purged_index(&self) -> Option { + let guard = self.inner.lock().unwrap(); + let committed = guard.hard_state.committed.as_ref().map(|id| id.index); + let purged = guard + .hard_state + .last_purged_log_id + .as_ref() + .map(|id| id.index); + match (committed, purged) { + (None, None) => None, + (Some(index), None) | (None, Some(index)) => Some(index), + (Some(committed), Some(purged)) => Some(committed.max(purged)), + } + } + /// Test hook. The next `n` append fsyncs fail and roll the in-memory log back. pub fn testing_fail_next_syncs(&self, n: u32) { self.inner.lock().unwrap().fail_syncs = n; diff --git a/crates/metadb-server/src/config.rs b/crates/metadb-server/src/config.rs index afeffe3..4cbe8d2 100644 --- a/crates/metadb-server/src/config.rs +++ b/crates/metadb-server/src/config.rs @@ -185,7 +185,11 @@ pub struct ServerTomlConfig { pub sharding: ShardingSection, pub security: SecuritySection, pub cluster: ClusterSection, - #[serde(skip)] + /// OpenRaft timers and the segmented-log size. The TOML table is `[raft]`. + /// + /// Field names are not secret or TLS keys, so the security-key walk in + /// `from_toml_str` does not treat this table as an auth setting. + #[serde(default, rename = "raft")] pub raft_options: RaftNodeOptions, /// Overrides the 45-second join budget. `None` keeps that budget. /// Not read from TOML; tests use it so a refused seed returns without waiting. @@ -198,8 +202,11 @@ impl ServerTomlConfig { let value: toml::Value = toml::from_str(s) .map_err(|e| MetaDbError::CodecError(format!("invalid TOML config: {e}")))?; reject_unsupported_security_keys(&value)?; - ServerTomlConfig::deserialize(value) - .map_err(|e| MetaDbError::CodecError(format!("invalid TOML config: {e}"))) + let parsed = ServerTomlConfig::deserialize(value) + .map_err(|e| MetaDbError::CodecError(format!("invalid TOML config: {e}")))?; + // Timer checks only. This does not read or rewrite [security]. + parsed.raft_options.validate()?; + Ok(parsed) } pub fn from_toml_file(path: impl AsRef) -> Result { diff --git a/crates/metadb-server/src/lib.rs b/crates/metadb-server/src/lib.rs index aa508a5..e432cfd 100644 --- a/crates/metadb-server/src/lib.rs +++ b/crates/metadb-server/src/lib.rs @@ -13,6 +13,7 @@ pub mod simulation; pub mod stress; mod metrics_http; +mod operability; use std::collections::BTreeSet; use std::fs::OpenOptions; @@ -169,6 +170,7 @@ use metadb_tx::{ pub use config::{ServerRole, ServerTomlConfig}; pub use grpc_services::MetaDbGrpcService; pub use metrics::{collect_cluster_metrics, render_prometheus_metrics, ClusterMetricsSnapshot}; +pub use operability::{evaluate_readiness, ProcessPhase, ReadinessReport, ShardGate}; /// Result returned from executing a lightweight metadata SQL statement through `MetaDbEngine`. #[derive(Debug, Clone, PartialEq, Eq)] @@ -546,6 +548,7 @@ pub struct PersistentMetaDbCluster { shutdown_tx: watch::Sender, task_handles: tokio::sync::Mutex>>, metrics_addr: OnceLock, + operability: Arc, } impl PersistentMetaDbCluster { @@ -563,6 +566,7 @@ impl PersistentMetaDbCluster { config.node.role ))); } + config.raft_options.validate()?; config.reject_unauthenticated_bind(&config.node.grpc_listen_addr)?; if let Some(metrics_addr) = &config.node.metrics_listen_addr { config.reject_unauthenticated_bind(metrics_addr)?; @@ -685,12 +689,22 @@ impl PersistentMetaDbCluster { ); let proxy_router = Arc::new(StatelessProxyRouter::new(tx_router.clone())); let (shutdown_tx, shutdown_rx) = watch::channel(false); - let grpc_svc = MetaDbGrpcService::new( - global_manager.clone(), - tx_router.clone(), - proxy_router.clone(), - ); - let shared_secret = config.security.shared_secret.clone(); + let operability = operability::Operability::starting(); + let cluster = Arc::new(Self { + config, + clock, + id_buffer, + host, + cell_manager, + global_manager, + tx_router, + proxy_router, + shutdown_tx, + task_handles: tokio::sync::Mutex::new(Vec::new()), + metrics_addr: OnceLock::new(), + operability, + }); + let shared_secret = cluster.config.security.shared_secret.clone(); if shared_secret.is_empty() { tracing::warn!( listen = %bound_addr, @@ -698,39 +712,54 @@ impl PersistentMetaDbCluster { This process does not terminate TLS. Non-loopback binds are still refused." ); } + let grpc_svc = MetaDbGrpcService::new( + cluster.global_manager.clone(), + cluster.tx_router.clone(), + cluster.proxy_router.clone(), + ); let grpc_handle = spawn_grpc_server(listener, grpc_svc, shared_secret, raft_router, shutdown_rx); + cluster.task_handles.lock().await.push(grpc_handle); + // The probe listener is up before join so a scrape observes `starting` + // instead of a later 200 that only means the socket is bound. + if let Err(error) = spawn_metrics_listener(&cluster).await { + cluster.operability.fail(); + let _ = cluster.shutdown_without_flush().await; + return Err(error); + } if join_fresh { // Raft RPCs from the leader arrive on this listener while membership is proposed. wait_until_accepting(&bound_addr).await; - if let Err(error) = join_existing_raft_group(&config, &cell_manager, &bound_addr).await + if let Err(error) = + join_existing_raft_group(cluster.config(), cluster.cell_manager(), &bound_addr) + .await { - shutdown_failed_startup(shutdown_tx, grpc_handle, &host).await; + cluster.operability.fail(); + let _ = cluster.shutdown_without_flush().await; return Err(error); } } // A joined replica already has the root directory in the replicated state machine. - if !cell_manager.joined_existing() && tx_router.dirstat(ROOT_INODE_ID).await.is_err() { - let _ = tx_router + if !cluster.cell_manager().joined_existing() + && cluster.tx_router().dirstat(ROOT_INODE_ID).await.is_err() + { + let _ = cluster + .tx_router() .init_dir_attr(ROOT_INODE_ID, ROOT_INODE_ID, 0, 0o755) .await; } - - let cluster = Arc::new(Self { - config, - clock, - id_buffer, - host, - cell_manager, - global_manager, - tx_router, - proxy_router, - shutdown_tx, - task_handles: tokio::sync::Mutex::new(vec![grpc_handle]), - metrics_addr: OnceLock::new(), - }); + cluster.operability.mark_startup_finished(); + let raft = &cluster.config.raft_options; + tracing::info!( + heartbeat_ms = raft.heartbeat_interval_ms, + election_min_ms = raft.election_timeout_min_ms, + election_max_ms = raft.election_timeout_max_ms, + max_in_snapshot_log_to_keep = raft.max_in_snapshot_log_to_keep, + max_segment_bytes = raft.max_segment_bytes, + "applied raft options" + ); // Background maintenance task (`AuxDispatcher` + `TxnRecoveryWorker` every 250ms). let bg_cluster = Arc::downgrade(&cluster); @@ -759,44 +788,8 @@ impl PersistentMetaDbCluster { }); cluster.task_handles.lock().await.push(bg_handle); - if let Some(metrics_listen) = cluster.config.node.metrics_listen_addr.clone() { - let metrics_listener = match TcpListener::bind(&metrics_listen).await { - Ok(listener) => listener, - Err(error) => { - let _ = cluster.shutdown().await; - return Err(error.into()); - } - }; - let metrics_bound = match metrics_listener.local_addr() { - Ok(addr) => addr.to_string(), - Err(error) => { - let _ = cluster.shutdown().await; - return Err(error.into()); - } - }; - if let Err(error) = cluster.config.reject_unauthenticated_bind(&metrics_bound) { - drop(metrics_listener); - let _ = cluster.shutdown().await; - return Err(error); - } - let _ = cluster.metrics_addr.set(metrics_bound.clone()); - tracing::info!( - metrics_addr = %metrics_bound, - "Prometheus metrics endpoint listening" - ); - let metrics_cluster = Arc::downgrade(&cluster); - let metrics_secret = cluster.config.security.shared_secret.clone(); - let metrics_shutdown = cluster.shutdown_tx.subscribe(); - let metrics_handle = tokio::spawn(metrics_http::serve( - metrics_listener, - metrics_cluster, - metrics_secret, - metrics_shutdown, - )); - cluster.task_handles.lock().await.push(metrics_handle); - } - - // Publish only after bootstrap or join has finished, so readers know the port is serving. + // Publish only after bootstrap or join has finished. The file means the + // gRPC port is accepting; `/readyz` is the traffic gate. std::fs::write( cluster.config().node.data_dir.join("GRPC_ADDR"), &bound_addr, @@ -929,8 +922,35 @@ impl PersistentMetaDbCluster { Ok(()) } + pub fn readiness(&self) -> ReadinessReport { + evaluate_readiness(self.operability.phase(), &self.shard_gates()) + } + + fn shard_gates(&self) -> Vec { + self.host + .all_groups() + .iter() + .map(|group| { + let view = group.serve_view(); + ShardGate { + leader_known: view.leader_known, + applied: view.applied, + voter: view.voter, + recovery_pending: view.recovery_pending, + storage_unrecoverable: view.storage_unrecoverable, + stopped: view.stopped, + fatal: view.fatal, + } + }) + .collect() + } + pub fn metrics_snapshot(&self) -> ClusterMetricsSnapshot { - collect_cluster_metrics(&self.global_manager) + let gates = self.shard_gates(); + let report = evaluate_readiness(self.operability.phase(), &gates); + let mut snap = collect_cluster_metrics(&self.global_manager); + snap.apply_operability(&report, &gates, &self.config.raft_options); + snap } /// Bound Prometheus address, when `node.metrics_listen_addr` was set. @@ -944,6 +964,7 @@ impl PersistentMetaDbCluster { /// so a stuck drain cannot pin process exit. Committed entries that are not in the /// memtable flush stay in the Raft log and replay on the next open. pub async fn shutdown(&self) -> Result<()> { + self.operability.begin_shutdown(); self.stop_tasks().await; match tokio::time::timeout(Duration::from_secs(10), self.flush_all()).await { Ok(result) => result?, @@ -972,6 +993,7 @@ impl PersistentMetaDbCluster { /// This is the in-process crash used by failure-under-load tests: the LSM `LOCK` is /// released, but the memtable is not checkpointed first. pub async fn shutdown_without_flush(&self) -> Result<()> { + self.operability.begin_shutdown(); self.stop_tasks().await; let result = self.host.shutdown_all_no_flush().await; backup::unregister_runtime(&self.config.node.data_dir); @@ -1120,6 +1142,29 @@ pub fn check_backup_tree(root: &Path) -> Result<()> { Ok(()) } +async fn spawn_metrics_listener(cluster: &Arc) -> Result<()> { + let Some(metrics_listen) = cluster.config.node.metrics_listen_addr.clone() else { + return Ok(()); + }; + let listener = TcpListener::bind(&metrics_listen).await?; + let bound = listener.local_addr()?.to_string(); + // Recheck the address the socket actually bound, including port 0. + cluster.config.reject_unauthenticated_bind(&bound)?; + let _ = cluster.metrics_addr.set(bound.clone()); + tracing::info!( + metrics_addr = %bound, + "Prometheus metrics endpoint listening" + ); + let handle = tokio::spawn(metrics_http::serve( + listener, + Arc::downgrade(cluster), + cluster.config.security.shared_secret.clone(), + cluster.shutdown_tx.subscribe(), + )); + cluster.task_handles.lock().await.push(handle); + Ok(()) +} + fn spawn_grpc_server( listener: TcpListener, grpc_svc: MetaDbGrpcService, @@ -1223,21 +1268,7 @@ fn listen_port_is_ephemeral(addr: &str) -> bool { /// /// Transient membership and transport errors are retried. A conflicting cluster or node /// identity is returned immediately. A failed attempt does not abort the process by itself; -/// the caller shuts the listeners down and returns the error. -/// Stops the listener and local Raft groups after startup cannot finish. -/// -/// The error is returned to the caller. `metadbd` then ends because `main` -/// returned that error. A join attempt does not abort the process itself. -async fn shutdown_failed_startup( - shutdown_tx: watch::Sender, - grpc_handle: tokio::task::JoinHandle<()>, - host: &ShardGroupHost, -) { - let _ = shutdown_tx.send(true); - let _ = grpc_handle.await; - let _ = host.shutdown_all().await; -} - +/// the caller marks startup failed, shuts the listeners down, and returns the error. async fn join_existing_raft_group( config: &ServerTomlConfig, cell_manager: &DurableCellManager, diff --git a/crates/metadb-server/src/metrics.rs b/crates/metadb-server/src/metrics.rs index af8cd76..9165742 100644 --- a/crates/metadb-server/src/metrics.rs +++ b/crates/metadb-server/src/metrics.rs @@ -1,6 +1,12 @@ //! Prometheus exposition formatter for shard, storage, MVCC, compaction, and Raft metrics. +//! +//! Operability series are unlabeled gauges. Shard ids, peer addresses, and +//! paths are not labels and are not values. use metadb_cluster::DurableGlobalManager; +use metadb_raft::RaftNodeOptions; + +use crate::operability::{ReadinessReport, ShardGate}; #[derive(Debug, Clone, Default, PartialEq, Eq)] pub struct ClusterMetricsSnapshot { @@ -13,6 +19,53 @@ pub struct ClusterMetricsSnapshot { pub tombstones_traversed_on_scans_total: u64, pub locality_compactions_total: u64, pub min_raft_safe_purge_index: u64, + pub ready: u64, + pub live: u64, + /// `ProcessPhase` numeric code: 0 starting, 1 serving, 2 shutting down, 3 failed. + pub process_phase: u64, + pub shards_leader_known: u64, + pub shards_leader_unknown: u64, + pub shards_recovery_pending: u64, + pub shards_log_not_applied: u64, + pub shards_not_voter: u64, + pub shards_storage_unrecoverable: u64, + pub shards_raft_stopped: u64, + pub shards_raft_fatal: u64, + pub raft_heartbeat_interval_ms: u64, + pub raft_election_timeout_min_ms: u64, + pub raft_election_timeout_max_ms: u64, + pub raft_max_in_snapshot_log_to_keep: u64, + pub raft_max_segment_bytes: u64, +} + +impl ClusterMetricsSnapshot { + pub(crate) fn apply_operability( + &mut self, + report: &ReadinessReport, + gates: &[ShardGate], + raft: &RaftNodeOptions, + ) { + self.ready = u64::from(report.ready); + self.live = u64::from(report.live); + self.process_phase = report.phase.code(); + self.shards_leader_known = count(gates, |gate| gate.leader_known); + self.shards_leader_unknown = count(gates, |gate| !gate.leader_known); + self.shards_recovery_pending = count(gates, |gate| gate.recovery_pending); + self.shards_log_not_applied = count(gates, |gate| !gate.applied); + self.shards_not_voter = count(gates, |gate| !gate.voter); + self.shards_storage_unrecoverable = count(gates, |gate| gate.storage_unrecoverable); + self.shards_raft_stopped = count(gates, |gate| gate.stopped); + self.shards_raft_fatal = count(gates, |gate| gate.fatal); + self.raft_heartbeat_interval_ms = raft.heartbeat_interval_ms; + self.raft_election_timeout_min_ms = raft.election_timeout_min_ms; + self.raft_election_timeout_max_ms = raft.election_timeout_max_ms; + self.raft_max_in_snapshot_log_to_keep = raft.max_in_snapshot_log_to_keep; + self.raft_max_segment_bytes = raft.max_segment_bytes; + } +} + +fn count(gates: &[ShardGate], pred: impl Fn(&ShardGate) -> bool) -> u64 { + gates.iter().filter(|gate| pred(gate)).count() as u64 } pub fn collect_cluster_metrics(gm: &DurableGlobalManager) -> ClusterMetricsSnapshot { @@ -63,6 +116,38 @@ pub fn render_prometheus_metrics(m: &ClusterMetricsSnapshot) -> String { "metadb_locality_compactions_total {}\n", "# TYPE metadb_min_raft_safe_purge_index gauge\n", "metadb_min_raft_safe_purge_index {}\n", + "# TYPE metadb_ready gauge\n", + "metadb_ready {}\n", + "# TYPE metadb_live gauge\n", + "metadb_live {}\n", + "# TYPE metadb_process_phase gauge\n", + "metadb_process_phase {}\n", + "# TYPE metadb_shards_leader_known gauge\n", + "metadb_shards_leader_known {}\n", + "# TYPE metadb_shards_leader_unknown gauge\n", + "metadb_shards_leader_unknown {}\n", + "# TYPE metadb_shards_recovery_pending gauge\n", + "metadb_shards_recovery_pending {}\n", + "# TYPE metadb_shards_log_not_applied gauge\n", + "metadb_shards_log_not_applied {}\n", + "# TYPE metadb_shards_not_voter gauge\n", + "metadb_shards_not_voter {}\n", + "# TYPE metadb_shards_storage_unrecoverable gauge\n", + "metadb_shards_storage_unrecoverable {}\n", + "# TYPE metadb_shards_raft_stopped gauge\n", + "metadb_shards_raft_stopped {}\n", + "# TYPE metadb_shards_raft_fatal gauge\n", + "metadb_shards_raft_fatal {}\n", + "# TYPE metadb_raft_heartbeat_interval_ms gauge\n", + "metadb_raft_heartbeat_interval_ms {}\n", + "# TYPE metadb_raft_election_timeout_min_ms gauge\n", + "metadb_raft_election_timeout_min_ms {}\n", + "# TYPE metadb_raft_election_timeout_max_ms gauge\n", + "metadb_raft_election_timeout_max_ms {}\n", + "# TYPE metadb_raft_max_in_snapshot_log_to_keep gauge\n", + "metadb_raft_max_in_snapshot_log_to_keep {}\n", + "# TYPE metadb_raft_max_segment_bytes gauge\n", + "metadb_raft_max_segment_bytes {}\n", ), m.cells_total, m.shards_total, @@ -73,5 +158,53 @@ pub fn render_prometheus_metrics(m: &ClusterMetricsSnapshot) -> String { m.tombstones_traversed_on_scans_total, m.locality_compactions_total, m.min_raft_safe_purge_index, + m.ready, + m.live, + m.process_phase, + m.shards_leader_known, + m.shards_leader_unknown, + m.shards_recovery_pending, + m.shards_log_not_applied, + m.shards_not_voter, + m.shards_storage_unrecoverable, + m.shards_raft_stopped, + m.shards_raft_fatal, + m.raft_heartbeat_interval_ms, + m.raft_election_timeout_min_ms, + m.raft_election_timeout_max_ms, + m.raft_max_in_snapshot_log_to_keep, + m.raft_max_segment_bytes, ) } + +#[cfg(test)] +mod tests { + use super::*; + use crate::operability::{evaluate_readiness, ProcessPhase, ShardGate}; + + #[test] + fn operability_series_are_unlabeled_and_follow_readiness() { + let gates = [ShardGate::servable()]; + let report = evaluate_readiness(ProcessPhase::Serving, &gates); + let mut snap = ClusterMetricsSnapshot::default(); + snap.apply_operability(&report, &gates, &RaftNodeOptions::default()); + let text = render_prometheus_metrics(&snap); + assert!(text.contains("metadb_ready 1\n"), "{text}"); + assert!(text.contains("metadb_live 1\n"), "{text}"); + assert!(text.contains("metadb_process_phase 1\n"), "{text}"); + assert!( + text.contains("metadb_raft_heartbeat_interval_ms 150\n"), + "{text}" + ); + assert!(text.contains("metadb_shards_total"), "{text}"); + assert!(!text.contains('{'), "series must not grow labels: {text}"); + assert!(!text.contains("secret"), "{text}"); + + let starting = evaluate_readiness(ProcessPhase::Starting, &gates); + snap.apply_operability(&starting, &gates, &RaftNodeOptions::default()); + let text = render_prometheus_metrics(&snap); + assert!(text.contains("metadb_ready 0\n"), "{text}"); + assert!(text.contains("metadb_process_phase 0\n"), "{text}"); + assert!(text.contains("metadb_shards_leader_known 1\n"), "{text}"); + } +} diff --git a/crates/metadb-server/src/metrics_http.rs b/crates/metadb-server/src/metrics_http.rs index defbf18..7382544 100644 --- a/crates/metadb-server/src/metrics_http.rs +++ b/crates/metadb-server/src/metrics_http.rs @@ -15,6 +15,7 @@ use tokio::task::JoinSet; use crate::bearer_header_matches; use crate::classify_secret; +use crate::operability::{health_body, live_body, ready_body, unavailable_report, ReadinessReport}; use crate::render_prometheus_metrics; use crate::PersistentMetaDbCluster; use crate::SecretMaterial; @@ -61,7 +62,17 @@ async fn metrics_connection( let cluster = cluster.clone(); let shared_secret = shared_secret.clone(); async move { - let (status, body, prometheus) = metrics_decision(&request, &cluster, &shared_secret); + let authorization = request + .headers() + .get(hyper::header::AUTHORIZATION) + .and_then(|value| value.to_str().ok()); + let (status, body, prometheus) = metrics_decision( + request.method(), + request.uri().path(), + authorization, + &cluster, + &shared_secret, + ); let mut response = Response::new(Full::new(Bytes::from(body))); *response.status_mut() = status; let content_type = if prometheus { @@ -97,46 +108,217 @@ async fn metrics_connection( } fn metrics_decision( - request: &Request, + method: &Method, + path: &str, + authorization: Option<&str>, cluster: &Weak, shared_secret: &str, ) -> (StatusCode, String, bool) { + // Whitespace is not a credential. Do not fall through to an exact bearer + // compare: `Authorization: Bearer ` must still be 401. match classify_secret(shared_secret) { SecretMaterial::Absent => {} SecretMaterial::WhitespaceOnly => { return (StatusCode::UNAUTHORIZED, "unauthorized\n".to_owned(), false); } SecretMaterial::Configured => { - let presented = request - .headers() - .get(hyper::header::AUTHORIZATION) - .and_then(|value| value.to_str().ok()) - .unwrap_or(""); - if !bearer_header_matches(presented, shared_secret) { + if !bearer_header_matches(authorization.unwrap_or(""), shared_secret) { return (StatusCode::UNAUTHORIZED, "unauthorized\n".to_owned(), false); } } } - if request.method() != Method::GET { + if method != Method::GET { return ( StatusCode::METHOD_NOT_ALLOWED, "method not allowed\n".to_owned(), false, ); } - if request.uri().path() != "/metrics" { - return (StatusCode::NOT_FOUND, "not found\n".to_owned(), false); - } let Some(cluster) = cluster.upgrade() else { + return route_probe(path, None, ""); + }; + let report = cluster.readiness(); + let metrics = render_prometheus_metrics(&cluster.metrics_snapshot()); + route_probe(path, Some(&report), &metrics) +} + +/// Routes an authenticated GET. `/metrics` stays 200 while the process is not +/// ready so a scrape can see `metadb_ready 0`. `/healthz` and `/readyz` do not. +fn route_probe( + path: &str, + report: Option<&ReadinessReport>, + metrics: &str, +) -> (StatusCode, String, bool) { + let Some(report) = report else { return ( StatusCode::SERVICE_UNAVAILABLE, - "unavailable\n".to_owned(), + format!("not live: {}\n", unavailable_report().reason), false, ); }; - ( - StatusCode::OK, - render_prometheus_metrics(&cluster.metrics_snapshot()), - true, - ) + match path { + "/metrics" => (StatusCode::OK, metrics.to_owned(), true), + "/livez" => { + let status = if report.live { + StatusCode::OK + } else { + StatusCode::SERVICE_UNAVAILABLE + }; + (status, live_body(report), false) + } + "/readyz" => { + let status = if report.ready { + StatusCode::OK + } else { + StatusCode::SERVICE_UNAVAILABLE + }; + (status, ready_body(report), false) + } + "/healthz" => { + let status = if report.ready { + StatusCode::OK + } else { + StatusCode::SERVICE_UNAVAILABLE + }; + (status, health_body(report), false) + } + _ => (StatusCode::NOT_FOUND, "not found\n".to_owned(), false), + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::operability::{evaluate_readiness, ProcessPhase, ShardGate}; + use std::sync::Weak; + + #[test] + fn probes_do_not_echo_tokens_or_treat_a_bound_listener_as_ready() { + let secret = "super-secret-token"; + let (status, body, prometheus) = metrics_decision( + &Method::GET, + "/readyz", + Some("Bearer wrong-token"), + &Weak::new(), + secret, + ); + assert_eq!(status, StatusCode::UNAUTHORIZED); + assert_eq!(body, "unauthorized\n"); + assert!(!prometheus); + assert!(!body.contains(secret)); + assert!(!body.contains("wrong-token")); + + let (status, body, _) = metrics_decision( + &Method::GET, + "/healthz", + Some(&format!("Bearer {secret}")), + &Weak::new(), + secret, + ); + assert_eq!(status, StatusCode::SERVICE_UNAVAILABLE); + assert_eq!(body, "not live: unavailable\n"); + assert!(!body.contains(secret)); + + let starting = evaluate_readiness(ProcessPhase::Starting, &[ShardGate::servable()]); + let (ready_status, ready_body, ready_prom) = + route_probe("/readyz", Some(&starting), "metrics"); + assert_eq!(ready_status, StatusCode::SERVICE_UNAVAILABLE); + assert_eq!(ready_body, "not ready: starting\n"); + assert!(!ready_prom); + + let (health_status, health_text, _) = route_probe("/healthz", Some(&starting), "metrics"); + assert_eq!(health_status, StatusCode::SERVICE_UNAVAILABLE); + assert!(health_text.contains("ready=0")); + assert!(health_text.contains("live=1")); + + let (live_status, live_text, _) = route_probe("/livez", Some(&starting), "metrics"); + assert_eq!(live_status, StatusCode::OK); + assert_eq!(live_text, "live\n"); + + let (metrics_status, metrics_body, metrics_prom) = + route_probe("/metrics", Some(&starting), "metadb_ready 0\n"); + assert_eq!(metrics_status, StatusCode::OK); + assert!(metrics_prom); + assert_eq!(metrics_body, "metadb_ready 0\n"); + + let serving = evaluate_readiness(ProcessPhase::Serving, &[ShardGate::servable()]); + let (status, body, _) = route_probe("/readyz", Some(&serving), ""); + assert_eq!(status, StatusCode::OK); + assert_eq!(body, "ready\n"); + let (status, _, _) = route_probe("/healthz", Some(&serving), ""); + assert_eq!(status, StatusCode::OK); + + let (status, body, prom) = route_probe("/status", Some(&serving), "secret-metrics"); + assert_eq!(status, StatusCode::NOT_FOUND); + assert_eq!(body, "not found\n"); + assert!(!prom); + assert!(!body.contains("secret-metrics")); + } + + #[test] + fn whitespace_secret_rejects_probes_even_when_the_bearer_matches() { + let secret = " \t "; + let exact = format!("Bearer {secret}"); + for path in ["/metrics", "/livez", "/readyz", "/healthz"] { + for presented in [None, Some(exact.as_str()), Some("Bearer secret")] { + let (status, body, prometheus) = + metrics_decision(&Method::GET, path, presented, &Weak::new(), secret); + assert_eq!(status, StatusCode::UNAUTHORIZED, "{path} {presented:?}"); + assert_eq!(body, "unauthorized\n"); + assert!(!prometheus); + assert!(!body.contains("Bearer")); + } + } + } + + #[test] + fn default_empty_config_is_not_an_opt_in_and_absent_secret_does_not_challenge_probes() { + use crate::config::ServerTomlConfig; + + let cfg = ServerTomlConfig::from_toml_str( + r#" + [node] + metrics_listen_addr = "127.0.0.1:9100" + [raft] + heartbeat_interval_ms = 80 + election_timeout_min_ms = 250 + election_timeout_max_ms = 450 + "#, + ) + .unwrap(); + assert!(cfg.security.shared_secret.is_empty()); + assert!(!cfg.security.allow_unauthenticated); + assert_eq!(cfg.raft_options.heartbeat_interval_ms, 80); + let startup = cfg + .reject_unauthenticated_bind("127.0.0.1:9100") + .unwrap_err() + .to_string(); + assert!( + startup.contains("allow_unauthenticated"), + "default empty secret must not start: {startup}" + ); + + let whitespace = ServerTomlConfig::from_toml_str( + r#" + [security] + shared_secret = " " + allow_unauthenticated = true + "#, + ) + .unwrap(); + let whitespace_err = whitespace + .security + .validate_for_startup() + .unwrap_err() + .to_string(); + assert!( + whitespace_err.contains("whitespace-only"), + "{whitespace_err}" + ); + + let (status, body, _) = metrics_decision(&Method::GET, "/readyz", None, &Weak::new(), ""); + assert_eq!(status, StatusCode::SERVICE_UNAVAILABLE); + assert_eq!(body, "not live: unavailable\n"); + assert!(!body.contains("unauthorized")); + } } diff --git a/crates/metadb-server/src/operability.rs b/crates/metadb-server/src/operability.rs new file mode 100644 index 0000000..9ddb093 --- /dev/null +++ b/crates/metadb-server/src/operability.rs @@ -0,0 +1,407 @@ +//! Process phase and readiness decision. +//! +//! The HTTP listener being bound is not an input. Readiness is false until +//! startup has finished, every local shard can accept or forward a client +//! request, and shutdown has not started. gRPC stays up while a probe says +//! not ready, so Raft peers can still reach a starting or recovering voter. + +use std::sync::atomic::{AtomicU8, Ordering}; +use std::sync::Arc; + +/// Stored lifecycle. Shard recovery is not a separate stored value: a serving +/// process with a pending replay reports `raft_recovery_pending` and is not ready. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +#[repr(u8)] +pub enum ProcessPhase { + Starting = 0, + Serving = 1, + ShuttingDown = 2, + Failed = 3, +} + +impl ProcessPhase { + pub fn code(self) -> u64 { + self as u8 as u64 + } + + pub fn as_str(self) -> &'static str { + match self { + Self::Starting => "starting", + Self::Serving => "serving", + Self::ShuttingDown => "shutting_down", + Self::Failed => "failed", + } + } + + fn from_code(code: u8) -> Self { + match code { + 1 => Self::Serving, + 2 => Self::ShuttingDown, + 3 => Self::Failed, + _ => Self::Starting, + } + } +} + +/// One local Raft group, reduced to flags a probe is allowed to publish. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct ShardGate { + pub leader_known: bool, + pub applied: bool, + pub voter: bool, + pub recovery_pending: bool, + pub storage_unrecoverable: bool, + pub stopped: bool, + pub fatal: bool, +} + +impl ShardGate { + pub fn servable() -> Self { + Self { + leader_known: true, + applied: true, + voter: true, + recovery_pending: false, + storage_unrecoverable: false, + stopped: false, + fatal: false, + } + } +} + +/// Result of one readiness evaluation. `reason` is a fixed token, never a path, +/// address, or secret. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct ReadinessReport { + pub live: bool, + pub ready: bool, + pub phase: ProcessPhase, + pub reason: &'static str, +} + +/// Shared phase flag. Shutdown does not clear `Failed`, so a startup failure +/// is not reported as a live graceful stop. +#[derive(Debug)] +pub struct Operability { + phase: AtomicU8, +} + +impl Operability { + pub fn starting() -> Arc { + Arc::new(Self { + phase: AtomicU8::new(ProcessPhase::Starting as u8), + }) + } + + pub fn phase(&self) -> ProcessPhase { + ProcessPhase::from_code(self.phase.load(Ordering::Acquire)) + } + + pub fn mark_startup_finished(&self) { + let _ = self.phase.compare_exchange( + ProcessPhase::Starting as u8, + ProcessPhase::Serving as u8, + Ordering::AcqRel, + Ordering::Acquire, + ); + } + + pub fn fail(&self) { + self.phase + .store(ProcessPhase::Failed as u8, Ordering::Release); + } + + pub fn begin_shutdown(&self) { + let mut current = self.phase.load(Ordering::Acquire); + while current != ProcessPhase::Failed as u8 && current != ProcessPhase::ShuttingDown as u8 { + match self.phase.compare_exchange_weak( + current, + ProcessPhase::ShuttingDown as u8, + Ordering::AcqRel, + Ordering::Acquire, + ) { + Ok(_) => return, + Err(observed) => current = observed, + } + } + } +} + +/// Decides liveness and readiness. +/// +/// While `phase` is `Serving`, the first failing shard condition wins, in this +/// order: storage unrecoverable, Raft fatal, stopped, startup replay pending, +/// this node is not an applied voter, no applied log, leader unknown. +/// An empty shard list is not ready. A healthy shard list does not override +/// `Starting`, `ShuttingDown`, or `Failed`. +pub fn evaluate_readiness(phase: ProcessPhase, shards: &[ShardGate]) -> ReadinessReport { + let blocked = |reason: &'static str| ReadinessReport { + live: phase != ProcessPhase::Failed, + ready: false, + phase, + reason, + }; + match phase { + ProcessPhase::Failed => ReadinessReport { + live: false, + ready: false, + phase, + reason: "failed", + }, + ProcessPhase::ShuttingDown => blocked("shutting_down"), + ProcessPhase::Starting => blocked("starting"), + ProcessPhase::Serving => { + if shards.is_empty() { + return blocked("no_local_shards"); + } + if shards.iter().any(|shard| shard.storage_unrecoverable) { + return blocked("storage_unrecoverable"); + } + if shards.iter().any(|shard| shard.fatal) { + return blocked("raft_fatal"); + } + if shards.iter().any(|shard| shard.stopped) { + return blocked("raft_stopped"); + } + if shards.iter().any(|shard| shard.recovery_pending) { + return blocked("raft_recovery_pending"); + } + if shards.iter().any(|shard| !shard.voter) { + return blocked("not_voter"); + } + if shards.iter().any(|shard| !shard.applied) { + return blocked("raft_log_not_applied"); + } + if shards.iter().any(|shard| !shard.leader_known) { + return blocked("leader_unknown"); + } + ReadinessReport { + live: true, + ready: true, + phase, + reason: "ready", + } + } + } +} + +pub fn unavailable_report() -> ReadinessReport { + ReadinessReport { + live: false, + ready: false, + phase: ProcessPhase::Failed, + reason: "unavailable", + } +} + +pub fn live_body(report: &ReadinessReport) -> String { + if report.live { + "live\n".to_owned() + } else { + format!("not live: {}\n", report.reason) + } +} + +pub fn ready_body(report: &ReadinessReport) -> String { + if report.ready { + "ready\n".to_owned() + } else { + format!("not ready: {}\n", report.reason) + } +} + +/// Diagnostic line. Callers that use the HTTP status as a traffic gate must +/// treat 200 as `report.ready`, not as "the listener accepted the socket". +pub fn health_body(report: &ReadinessReport) -> String { + format!( + "live={} ready={} phase={} reason={}\n", + u8::from(report.live), + u8::from(report.ready), + report.phase.as_str(), + report.reason, + ) +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::config::ServerTomlConfig; + + #[test] + fn listener_facts_do_not_make_a_starting_process_ready() { + let report = evaluate_readiness(ProcessPhase::Starting, &[ShardGate::servable()]); + assert!(report.live); + assert!(!report.ready); + assert_eq!(report.reason, "starting"); + assert_eq!(ready_body(&report), "not ready: starting\n"); + assert_eq!(live_body(&report), "live\n"); + let health = health_body(&report); + assert!(health.contains("ready=0")); + assert!(health.contains("phase=starting")); + } + + #[test] + fn serving_requires_every_local_shard_to_be_able_to_take_traffic() { + let ready = evaluate_readiness( + ProcessPhase::Serving, + &[ShardGate::servable(), ShardGate::servable()], + ); + assert!(ready.ready); + assert_eq!(ready.reason, "ready"); + assert_eq!(ready_body(&ready), "ready\n"); + + let mut leaderless = ShardGate::servable(); + leaderless.leader_known = false; + let report = + evaluate_readiness(ProcessPhase::Serving, &[ShardGate::servable(), leaderless]); + assert!(!report.ready); + assert_eq!(report.reason, "leader_unknown"); + + let mut replaying = ShardGate::servable(); + replaying.recovery_pending = true; + replaying.leader_known = true; + let report = evaluate_readiness(ProcessPhase::Serving, &[replaying]); + assert_eq!(report.reason, "raft_recovery_pending"); + + let mut learner = ShardGate::servable(); + learner.voter = false; + assert_eq!( + evaluate_readiness(ProcessPhase::Serving, &[learner]).reason, + "not_voter" + ); + + let mut unapplied = ShardGate::servable(); + unapplied.applied = false; + assert_eq!( + evaluate_readiness(ProcessPhase::Serving, &[unapplied]).reason, + "raft_log_not_applied" + ); + + assert_eq!( + evaluate_readiness(ProcessPhase::Serving, &[]).reason, + "no_local_shards" + ); + } + + #[test] + fn shutdown_is_not_ready_and_failure_is_not_live() { + let stopping = evaluate_readiness(ProcessPhase::ShuttingDown, &[ShardGate::servable()]); + assert!(stopping.live); + assert!(!stopping.ready); + assert_eq!(stopping.reason, "shutting_down"); + + let failed = evaluate_readiness(ProcessPhase::Failed, &[ShardGate::servable()]); + assert!(!failed.live); + assert!(!failed.ready); + assert_eq!(failed.reason, "failed"); + assert_eq!(live_body(&failed), "not live: failed\n"); + + let ops = Operability::starting(); + ops.fail(); + ops.begin_shutdown(); + assert_eq!(ops.phase(), ProcessPhase::Failed); + ops.mark_startup_finished(); + assert_eq!(ops.phase(), ProcessPhase::Failed); + + let ops = Operability::starting(); + ops.mark_startup_finished(); + ops.begin_shutdown(); + assert_eq!(ops.phase(), ProcessPhase::ShuttingDown); + ops.mark_startup_finished(); + assert_eq!(ops.phase(), ProcessPhase::ShuttingDown); + } + + #[test] + fn probe_text_has_no_place_to_carry_a_secret() { + let secret = "super-secret-token"; + for phase in [ + ProcessPhase::Starting, + ProcessPhase::Serving, + ProcessPhase::ShuttingDown, + ProcessPhase::Failed, + ] { + let mut shard = ShardGate::servable(); + shard.storage_unrecoverable = true; + let report = evaluate_readiness(phase, &[shard]); + let text = format!( + "{}{}{}", + live_body(&report), + ready_body(&report), + health_body(&report) + ); + assert!(!text.contains(secret), "{text}"); + assert!(!text.contains('/'), "{text}"); + assert!(!text.contains("Bearer"), "{text}"); + } + } + + #[test] + fn raft_table_is_loaded_and_rejected_keys_still_fail_closed() { + let cfg = ServerTomlConfig::from_toml_str( + r#" + [raft] + heartbeat_interval_ms = 80 + election_timeout_min_ms = 250 + election_timeout_max_ms = 450 + max_in_snapshot_log_to_keep = 4 + max_segment_bytes = 1048576 + "#, + ) + .unwrap(); + assert_eq!(cfg.raft_options.heartbeat_interval_ms, 80); + assert_eq!(cfg.raft_options.election_timeout_min_ms, 250); + assert_eq!(cfg.raft_options.election_timeout_max_ms, 450); + assert_eq!(cfg.raft_options.max_in_snapshot_log_to_keep, 4); + assert_eq!(cfg.raft_options.max_segment_bytes, 1_048_576); + + let partial = ServerTomlConfig::from_toml_str( + r#" + [raft] + heartbeat_interval_ms = 100 + "#, + ) + .unwrap(); + assert_eq!(partial.raft_options.heartbeat_interval_ms, 100); + assert_eq!(partial.raft_options.election_timeout_min_ms, 450); + + let omitted = ServerTomlConfig::from_toml_str("[node]\nnode_id = 3\n").unwrap(); + assert_eq!(omitted.node.node_id, 3); + assert_eq!(omitted.raft_options.heartbeat_interval_ms, 150); + + let typo = ServerTomlConfig::from_toml_str( + r#" + [raft] + heartbit_interval_ms = 80 + "#, + ); + let typo_err = typo.unwrap_err().to_string(); + assert!( + typo_err.contains("heartbit_interval_ms"), + "a misspelled raft key must not be ignored: {typo_err}" + ); + + let too_fast = ServerTomlConfig::from_toml_str( + r#" + [raft] + heartbeat_interval_ms = 900 + "#, + ); + assert!(too_fast + .unwrap_err() + .to_string() + .contains("invalid [raft] options")); + + let tls = ServerTomlConfig::from_toml_str( + r#" + [security] + shared_secret = "secret" + tls_cert = "/tmp/cert.pem" + "#, + ); + let tls_err = tls.unwrap_err().to_string(); + assert!( + tls_err.contains("does not terminate TLS"), + "raft parsing must not skip the security-key rejection: {tls_err}" + ); + } +} diff --git a/docs/en/README.md b/docs/en/README.md index 1cd8459..bcc73f9 100644 --- a/docs/en/README.md +++ b/docs/en/README.md @@ -32,6 +32,7 @@ Shard splits, dual-mode `(PID, name)` splits, and jumbo route flags do run insid | [Build and run](./build-and-run.md) | Toolchain, binaries, embedded library, shutdown | | [Configuration](./configuration.md) | TOML fields, defaults, and fields the process does not apply | | [Operations](./operations.md) | `metadb-ctl`, metrics, scale-out, splits, limitations, documentation gaps | +| [Operability](./operability.md) | `/livez`, `/readyz`, `/healthz`, phase codes, and the `[raft]` table | | [Tests and benches](./testing.md) | `cargo test`, what each suite actually exercises, `metadb-ctl bench` | | [Simulation testing](./simulation-testing.md) | Seeded workload catalog, and how it relates to FoundationDB's testing design | diff --git a/docs/en/architecture.md b/docs/en/architecture.md index 08b6f3b..5583f08 100644 --- a/docs/en/architecture.md +++ b/docs/en/architecture.md @@ -15,7 +15,7 @@ This page follows the code in `crates/`. It does not describe a multi-process Ce 5. Opens or bootstraps `DurableCellManager` at `/cell_`. 6. Registers that one cell on `DurableGlobalManager` for the key range `[0x01, 0x04)`. 7. Ensures root directory inode `1` (`ROOT_INODE_ID`) has an attribute record. -8. Serves four gRPC services on the same listener. All four take the same bearer interceptor. When `metrics_listen_addr` is set, `GET /metrics` on that address requires the same secret. A secret that contains a non-whitespace character rejects a missing or wrong bearer. An empty secret listens only when `allow_unauthenticated` is set, and only on loopback. A whitespace-only secret does not reach this step. This process does not terminate TLS. +8. Serves four gRPC services on the same listener. All four take the same bearer interceptor. When `metrics_listen_addr` is set, `GET /metrics`, `GET /livez`, `GET /readyz`, and `GET /healthz` use `classify_secret`. A secret that contains a non-whitespace character rejects a missing or wrong bearer. A whitespace-only secret is 401 on those paths and does not match `Bearer` plus the same spaces. An empty secret listens only when `allow_unauthenticated` is set, and only for a literal loopback IP. The bound metrics address is checked again after that socket binds. This process does not terminate TLS. 9. Spawns a maintenance task on a 250 ms interval. `metadbd` is a thin wrapper: it loads TOML, applies CLI overrides, calls `open_and_serve`, optionally calls `RegisterNode` on `--cell-manager`, and on Ctrl-C calls `shutdown`. Metrics, when configured, are served inside `open_and_serve`. @@ -86,7 +86,7 @@ MVCC versions live in memory for `storage.mvcc_retention_ms` (default 5,000). A ## Raft -Each local shard is an `openraft` 0.10 group. The log is a segmented CRC32C file under `.../shards//raft`. Default options, which are **not** loaded from TOML (`raft_options` is `#[serde(skip)]`): +Each local shard is an `openraft` 0.10 group. The log is a segmented CRC32C file under `.../shards//raft`. Defaults, loaded from `[raft]` when that table or a field is omitted: | Field | Default | | :--- | :--- | diff --git a/docs/en/build-and-run.md b/docs/en/build-and-run.md index ffb2aed..a516a0d 100644 --- a/docs/en/build-and-run.md +++ b/docs/en/build-and-run.md @@ -67,7 +67,7 @@ cargo run -p metadb-server --bin metadbd -- --config ./standalone.toml Logs use `tracing-subscriber`'s `EnvFilter`. The default filter is `info`. Override it with the standard `RUST_LOG` variable, for example `RUST_LOG=debug`. -An empty `security.shared_secret` does not start the process. The default bind is `127.0.0.1`, and loopback is not an implicit exception. Local development without credentials sets `allow_unauthenticated = true` and keeps every listener on a literal loopback IP (`127.0.0.1` or `::1`). The hostname `localhost` is not accepted for that opt-in. A wildcard or other non-loopback address still refuses to listen. A whitespace-only secret is rejected. A non-empty `[security].shared_secret` requires the same bearer on metadata, transaction, control-plane, Raft transport, and `GET /metrics`. The process does not terminate TLS. A TLS, certificate, anonymous, or insecure key in the config fails startup instead of serving plaintext. Keep an opted-in listener on a trusted network, or put every service behind a proxy that authenticates clients and block direct access to this process. +An empty `security.shared_secret` does not start the process. The default bind is `127.0.0.1`, and loopback is not an implicit exception. Local development without credentials sets `allow_unauthenticated = true` and keeps every listener on a literal loopback IP (`127.0.0.1` or `::1`). The hostname `localhost` is not accepted for that opt-in. After each socket binds, the bound IP is checked again. A wildcard or other non-loopback address still refuses to listen. A whitespace-only secret is rejected, including on `/livez`, `/readyz`, `/healthz`, and `/metrics`. A secret that contains a non-whitespace character requires the same bearer on metadata, transaction, control-plane, Raft transport, and every request on the metrics listener. `/readyz` is not 200 just because that listener is bound. See [Operability](./operability.md). The process does not terminate TLS. A TLS, certificate, anonymous, or insecure key in the config fails startup instead of serving plaintext. Keep an opted-in listener on a trusted network, or put every service behind a proxy that authenticates clients and block direct access to this process. Ctrl-C flushes shard state and stops the OpenRaft groups (`cluster.shutdown()`). diff --git a/docs/en/configuration.md b/docs/en/configuration.md index f90639a..f661195 100644 --- a/docs/en/configuration.md +++ b/docs/en/configuration.md @@ -2,7 +2,7 @@ [Overview](./README.md) · [Français](../fr/configuration.md) · [Deutsch](../de/configuration.md) · [日本語](../ja/configuration.md) · [简体中文](../zh/configuration.md) -`metadbd --config` and `ServerTomlConfig::from_toml_file` / `from_toml_str` read TOML (`crates/metadb-server/src/config.rs`). Unknown keys that do not name a secret, authentication, or TLS setting are ignored. A misspelled `shared_secret`, a token, password, anonymous, or insecure key, or any TLS or certificate key is rejected and startup does not proceed, including those keys nested in tables or arrays. The only accepted keys directly under the root `[security]` table are `shared_secret` and `allow_unauthenticated`. Every known section is optional. Omitted fields take the defaults below. +`metadbd --config` and `ServerTomlConfig::from_toml_file` / `from_toml_str` read TOML (`crates/metadb-server/src/config.rs`). Unknown keys that do not name a secret, authentication, or TLS setting are ignored, except inside `[raft]`: an unknown key there fails parsing. A misspelled `shared_secret`, a token, password, anonymous, or insecure key, or any TLS or certificate key is rejected and startup does not proceed, including those keys nested in tables or arrays. The only accepted keys directly under the root `[security]` table are `shared_secret` and `allow_unauthenticated`. Every known section is optional. Omitted fields take the defaults below. ## Defaults @@ -24,10 +24,15 @@ | `storage.locality_tombstone_ratio` | `0.50` | Yes. Multiplied by 1000, clamped to 1..=1000, stored as `tombstone_min_ratio_permille` | | `sharding.bootstrap_table_shards` | `true` | Yes. `true` creates shards 1, 2, and 3. `false` creates shard 1 over `[0x01, 0x04)` | | `sharding.shard_split_threshold_bytes` | `4294967296` (4 GiB) | Yes. Split check uses approximate shard size | -| `security.shared_secret` | `""` | Yes. Empty does not start a listener. A non-empty value requires the same bearer on gRPC and metrics. Whitespace-only is rejected | +| `security.shared_secret` | `""` | Yes. Empty does not start a listener. A value with a non-whitespace character requires the same bearer on gRPC and the metrics listener. Whitespace-only is rejected | | `security.allow_unauthenticated` | `false` | Yes. Explicit loopback-only development opt-in. It does not allow a non-loopback bind, and it cannot be combined with a usable secret | +| `raft.heartbeat_interval_ms` | `150` | Yes, when each local Raft group starts. Not reloaded while the process runs | +| `raft.election_timeout_min_ms` | `450` | Yes. Must be greater than the heartbeat and less than the maximum | +| `raft.election_timeout_max_ms` | `900` | Yes. Must be greater than the minimum | +| `raft.max_in_snapshot_log_to_keep` | `0` | Yes. Passed to OpenRaft | +| `raft.max_segment_bytes` | `67108864` (64 MiB) | Yes, for new segment rotation. `0` is rejected. Existing segment files are not rewritten | -There is no `[raft]` table. `ServerTomlConfig.raft_options` is skipped by serde and stays at `RaftNodeOptions::default()` (heartbeat 150 ms, election 450–900 ms, snapshot log keep 0, segment 64 MiB). +`[raft]` is loaded. A missing table keeps `RaftNodeOptions::default()`. Unknown keys inside `[raft]` fail parsing. The inequalities are the same ones OpenRaft checks at group start. See [Operability](./operability.md). `to_lsm_config` always sets `auto_locality_compaction: true`. @@ -62,6 +67,13 @@ shard_split_threshold_bytes = 4294967296 [security] shared_secret = "replace-with-a-long-random-string" + +[raft] +heartbeat_interval_ms = 150 +election_timeout_min_ms = 450 +election_timeout_max_ms = 900 +max_in_snapshot_log_to_keep = 0 +max_segment_bytes = 67108864 ``` Role strings are kebab-case: `all-in-one`, `be`, `proxy`, `cell-manager`, `global-manager`. @@ -72,18 +84,18 @@ CLI flags override the file after it is parsed: `--node-id`, `--cell-id`, `--rol This process does not terminate TLS. There is no certificate configuration that turns on native TLS. If the file contains a TLS, SSL, or certificate key, parsing fails and the process does not serve plaintext. Terminate TLS in an external proxy, and do not leave a TLS key in this file. -When `shared_secret` contains a non-whitespace character, `MetadataService`, `TransactionService`, `ControlPlaneService`, and `RaftTransportService` require `authorization` to equal `Bearer ` exactly. `GET /metrics` on `metrics_listen_addr` requires the same `Authorization` header. A missing header, an empty bearer, a prefix, or a longer token is rejected. The metrics failure body is not Prometheus text. Raft peers send the same bearer. `metadb-ctl --auth-token` (environment variable `METADB_AUTH_TOKEN`) and `metadbd --join` / `--cell-manager` send it. `metadb-ctl cluster status` calls `GetRoutes` and is covered by that interceptor. The client interceptor rejects a whitespace-only token instead of sending it. +When `shared_secret` contains a non-whitespace character, `MetadataService`, `TransactionService`, `ControlPlaneService`, and `RaftTransportService` require `authorization` to equal `Bearer ` exactly. Every request on `metrics_listen_addr`, including `GET /metrics`, `GET /livez`, `GET /readyz`, and `GET /healthz`, requires the same `Authorization` header. A missing header, an empty bearer, a prefix, or a longer token is rejected. The failure body is `unauthorized` and is not Prometheus text. It does not echo the token. A whitespace-only secret does not take that exact-match path: metrics and probes return 401 even when `Authorization` is `Bearer` plus those same spaces. Raft peers send the same bearer when the secret is usable. `metadb-ctl --auth-token` (environment variable `METADB_AUTH_TOKEN`) and `metadbd --join` / `--cell-manager` send it. `metadb-ctl cluster status` calls `GetRoutes` and is covered by that interceptor. The client interceptor rejects a whitespace-only token instead of sending it. An empty `shared_secret` does not start the process, including when every address is loopback. That is a compatibility change from the previous loopback default. Local development without credentials must set `allow_unauthenticated = true` and keep `grpc_listen_addr` and `metrics_listen_addr` (if set) on a literal loopback IP (`127.0.0.0/8` or `::1`). The hostname `localhost` is not accepted for this opt-in and is not resolved, including through a hosts file. A usable secret may still bind a hostname. Compatibility: an opted-in config that used `localhost` no longer starts. A wildcard (`0.0.0.0`, `::`) or any other address still refuses to listen. A whitespace-only secret is rejected even with that flag. Setting both a usable secret and `allow_unauthenticated` is rejected. The listeners are still plaintext. Keep an opted-in listener on a trusted network, or put every service behind a proxy that authenticates the client and block direct access to this process. `empty_secret_on_loopback_does_not_listen` and `whitespace_secret_on_loopback_does_not_listen` cover those refusals. `explicit_unauthenticated_loopback_serves_without_credentials` covers the opt-in. A configured secret on loopback still rejects a missing header, `Authorization: Basic ...`, a lowercase `bearer` scheme, and a wrong bearer, and the rejected create is not visible afterwards. -A key fails parsing when its normalized form (lowercase, hyphens become underscores) contains one of these substrings, including inside nested tables and arrays: `secret`, `password`, `passwd`, `token`, `credential`, `auth`, `anonymous`, `anon`, `insecure`, `api_key`, `apikey`, `bearer`, `jwt`, `private_key`, `privatekey`, `encryption`, `encrypt`, `tls`, `ssl`, `cert`, `x509`, `mtls`, `cipher`, `keystore`, `https`, `ca_file`, `cafile`, or it starts with `secur`. The only exceptions are the direct keys `[security].shared_secret` and `[security].allow_unauthenticated`. This is not a rejection of every unknown key. `bloom_bits_per_key` and a misspelled `grpc_listen_addr` or storage key are still ignored. Unknown keys that do not name a secret, authentication, or TLS setting are still ignored. `unknown_toml_keys_are_ignored_and_loopback_still_serves` parses `grpc_listen_addrr`, `memtable_size_bytez`, and `joinn`, keeps those defaults, and serves only because that fixture also sets `allow_unauthenticated`. Closing the remaining unknown-key hole means rejecting those keys, not teaching the server a new spelling. +A key fails parsing when its normalized form (lowercase, hyphens become underscores) contains one of these substrings, including inside nested tables and arrays: `secret`, `password`, `passwd`, `token`, `credential`, `auth`, `anonymous`, `anon`, `insecure`, `api_key`, `apikey`, `bearer`, `jwt`, `private_key`, `privatekey`, `encryption`, `encrypt`, `tls`, `ssl`, `cert`, `x509`, `mtls`, `cipher`, `keystore`, `https`, `ca_file`, `cafile`, or it starts with `secur`. The only exceptions are the direct keys `[security].shared_secret` and `[security].allow_unauthenticated`. This is not a rejection of every unknown key. `bloom_bits_per_key` and a misspelled `grpc_listen_addr` or storage key are still ignored. Unknown keys inside `[raft]` fail parsing even when they do not match those substrings. `unknown_toml_keys_are_ignored_and_loopback_still_serves` parses `grpc_listen_addrr`, `memtable_size_bytez`, and `joinn`, keeps those defaults, and serves only because that fixture also sets `allow_unauthenticated`. Closing the remaining unknown-key hole means rejecting those keys, not teaching the server a new spelling. ## What you cannot configure - Per-role subsystem trimming. The role field is an allow/deny switch, not a feature set. - A voter list in TOML. The first process bootstraps alone. A later all-in-one process joins with `[cluster] join = "host:port"` (or `--join` / `--cell-manager`) pointing at the current leader, and only when its data directory does not already own a cell. The leader must be reached directly; a follower does not forward the membership change. That join is the same cell, not a second cell. See [Operations](./operations.md). - A second cell's key range. `RegisterCell` returns an error and stores nothing. -- Raft timers or locality-compaction on/off. +- Locality-compaction on/off. `to_lsm_config` always enables it. Raft timers are the `[raft]` table; see [Operability](./operability.md). - Native TLS certificates. A TLS key in this file is rejected. Termination belongs in an external proxy. diff --git a/docs/en/operability.md b/docs/en/operability.md new file mode 100644 index 0000000..2b56450 --- /dev/null +++ b/docs/en/operability.md @@ -0,0 +1,141 @@ +# Operability + +[Overview](./README.md) · [Configuration](./configuration.md) · [Operations](./operations.md) + +This page is the exact contract for health probes, readiness, the low-cardinality metrics added with them, and the `[raft]` table. It describes the process that results from this change. It is not a first-ship acceptance test and it is not a trillion-scale operations guide. + +`[raft]` is loaded. `ServerTomlConfig.raft_options` is not `#[serde(skip)]`. The authentication rules in the next paragraph are the ones on `main` at `9b152ae4f820fa5f8e6971eab0862d23e5ca385f`. + +`allow_unauthenticated` accepts only a literal loopback IP (`127.0.0.0/8` or `::1`). The hostname `localhost` is not accepted and is not resolved. After the gRPC socket and the metrics socket bind, the bound address is checked again. A whitespace-only secret is rejected by `classify_secret` before any bearer compare. + +Locale configuration and architecture pages other than this English page still say `raft_options` is skipped. Those pages are not edited here. Aligning them with `[raft]` loading is a separate documentation change. + +## Where the probes live + +`node.metrics_listen_addr` is the only HTTP listener. When it is unset, this process has no `/livez`, `/readyz`, `/healthz`, or `/metrics`. There is no gRPC health RPC. `GRPC_ADDR` is written after bootstrap or join returns. It means the gRPC port is accepting. It does not mean `/readyz` is 200. + +The metrics listener uses `classify_secret`, the same classification as gRPC. The body of a rejection is `unauthorized`. It does not contain the presented token or the configured secret, and it is not Prometheus text. + +- `Absent`: the secret string is empty. The request is not challenged. `open_and_serve` reaches that state only when `[security].allow_unauthenticated = true` and every listener is loopback. A default config leaves the secret empty and the flag false, so startup refuses it. That default does not become this probe state. +- `WhitespaceOnly`: the secret is spaces or other whitespace and contains no other character. `/metrics`, `/livez`, `/readyz`, and `/healthz` return HTTP 401. That includes a request whose `Authorization` value is exactly `Bearer` plus the same whitespace. Startup rejects this secret even when `allow_unauthenticated` is set. The probe does not compare it as a configured bearer. +- `Configured`: the secret contains a non-whitespace character. `Authorization` must equal `Bearer ` exactly. A missing, empty, or different value is HTTP 401. + +`allow_unauthenticated` still refuses a wildcard or any other non-loopback address. This listener does not terminate TLS. + +Only `GET` is accepted. Any other method is HTTP 405. The route is the URI path, so a query string does not select another check and cannot ask for a dump. `GET /readyz?verbose=1` is the same probe as `GET /readyz`. There is no POST, no reload, and no shutdown URL. The probes are not a management API. + +`/metrics` returns HTTP 200 with Prometheus text even when the process is not ready, so a scrape can see `metadb_ready 0`. Do not use `/metrics` as a traffic gate. + +## Phase + +`metadb_process_phase` is one unlabeled gauge: + +| Value | Name | Meaning | +| :--- | :--- | :--- | +| 0 | `starting` | `open_and_serve` has not finished bootstrap, join, or the root-directory attempt | +| 1 | `serving` | That startup sequence returned. Shard conditions below still decide readiness | +| 2 | `shutting_down` | `shutdown` or `shutdown_without_flush` has started, and the process had not already failed | +| 3 | `failed` | Metrics bind or join failed. Shutdown does not overwrite this with `shutting_down` | + +The metrics listener is bound before join, while the phase is still `starting`. A probe during join gets a response instead of "connection refused means not ready". + +## Liveness and readiness + +| Path | HTTP 200 | HTTP 503 | +| :--- | :--- | :--- | +| `GET /livez` | The phase is not `failed` and the handler can still answer. This includes `starting` and `shutting_down` | Phase is `failed`, or the cluster handle is already gone (`not live: unavailable`) | +| `GET /readyz` | Startup finished, shutdown has not started, and every local Raft group passes the shard checks | Anything else. The body is `not ready: ` | +| `GET /healthz` | Same status as `/readyz` | Same status as `/readyz` | + +`/healthz` is not a second readiness rule. Its status matches `/readyz`, so a caller that treats HTTP 200 as "send traffic" does not get a 200 merely because the socket is open. The body is one line: + +```text +live=<0|1> ready=<0|1> phase= reason= +``` + +`/livez` is the restart probe. Do not point a restart probe at `/readyz` or `/healthz`. A leader election sets `leader_unknown` and those two paths return 503 on every replica that does not currently know a leader. Restarting the process for that would drop voters during the election. + +`/livez` stays 200 during graceful shutdown so a restart probe does not kill the process while it flushes. The listener then closes, and later connections fail. A failed startup is `failed`: `/livez` is 503, and the process exits with the startup error. + +gRPC is not closed when `/readyz` is 503. A starting or recovering voter must still accept `RaftTransportService`. The probe tells clients not to send metadata traffic. It does not fence the replica. + +## When `/readyz` is 200 + +All of the following are required. The listener is not one of them. + +1. Phase is `serving`. +2. At least one local Raft group is registered. +3. Every local group has all of: + - storage is not marked unrecoverable + - OpenRaft `running_state` is not a fatal error + - the group has not entered `shutdown` + - startup replay is not pending + - this node is an applied voter + - `last_applied` is set + - `current_leader` is set + +The first failing condition is the `reason` token, in that order: `no_local_shards`, `storage_unrecoverable`, `raft_fatal`, `raft_stopped`, `raft_recovery_pending`, `not_voter`, `raft_log_not_applied`, `leader_unknown`. Phase failures use `failed`, `shutting_down`, or `starting` and do not look at shards. A healthy shard list does not override those phases. + +`current_leader` may be this node or a peer. Ready means this process can apply a client request or forward it to a known leader. It does not mean this process is the leader. A follower that does not know a leader is not ready, matching the RPC behavior that returns `NotLeader` in that case. + +Startup replay is the committed or purged Raft index captured when the group opens. `ShardRaftGroup::start` waits up to 5 seconds for OpenRaft recovery. Success records the shard caught up. A timeout does not fail the process open and does not make the shard ready. The shard stays `raft_recovery_pending` until `last_applied` reaches that index. A fresh log with no committed or purged index does not wait and does not block readiness. An uncommitted tail alone does not block readiness. + +`open_or_bootstrap` still runs incomplete-split recovery before it returns. A failure there aborts startup. That path is a startup error, not a 503 from a live process. + +## What readiness does not cover + +These stay out of the probe on purpose. Treating them as ready would be a broader claim than the code makes. + +- The 250 ms `TxnRecoveryWorker` pass. Expired 2PC intents are not required to be drained before `/readyz` returns 200. The first pass runs after the phase flips to `serving`, and a failed pass is ignored by that loop. +- Backup holds, online backup copies, and restore. Those are a separate operator path. +- A second cell, Jumbo file movement, RDMA, and heartbeats. `StoreHeartbeat` still has no sender in `metadbd`. +- Disk space, clock health, and "this node can reach a quorum right now" beyond the leader id OpenRaft has published. `leader_unknown` is the check this process can make without starting a proposal. +- Per-shard series. Gauges below are counts. A shard id is not a label. + +The shard gauges count flags independently. One group can increment both `metadb_shards_recovery_pending` and `metadb_shards_leader_unknown`. They are not a partition of `metadb_shards_total`. `metadb_shards_total` still counts shard handles registered on the cell. The `metadb_shards_*` operability gauges count local Raft groups. During shutdown those groups are removed from the host map, so the counts can drop to 0 while `metadb_process_phase` is `2` or `3`. + +## Metrics + +Existing series are unchanged: `metadb_cells_total`, `metadb_shards_total`, `metadb_in_memory_mvcc_writes_total`, `metadb_pruned_mvcc_versions_total`, `metadb_persistent_kv_writes_total`, `metadb_active_physical_tombstones`, `metadb_tombstones_traversed_on_scans_total`, `metadb_locality_compactions_total`, `metadb_min_raft_safe_purge_index`. + +Unlabeled gauges added for operators: + +| Name | Meaning | +| :--- | :--- | +| `metadb_ready` | 1 only when `/readyz` would be 200 | +| `metadb_live` | 1 when `/livez` would be 200 | +| `metadb_process_phase` | The table above | +| `metadb_shards_leader_known` | Local groups whose OpenRaft metrics have `current_leader` | +| `metadb_shards_leader_unknown` | Local groups that do not | +| `metadb_shards_recovery_pending` | Local groups still replaying the startup commit | +| `metadb_shards_log_not_applied` | Local groups with no `last_applied` | +| `metadb_shards_not_voter` | Local groups where this node is not an applied voter | +| `metadb_shards_storage_unrecoverable` | Local groups whose snapshot cannot be rebuilt | +| `metadb_shards_raft_stopped` | Local groups whose `shutdown` has started | +| `metadb_shards_raft_fatal` | Local groups whose OpenRaft `running_state` is an error | +| `metadb_raft_heartbeat_interval_ms` | Configured heartbeat. Not a measured RTT | +| `metadb_raft_election_timeout_min_ms` | Configured minimum election timeout | +| `metadb_raft_election_timeout_max_ms` | Configured maximum election timeout | +| `metadb_raft_max_in_snapshot_log_to_keep` | Configured OpenRaft snapshot-log retention | +| `metadb_raft_max_segment_bytes` | Configured segment size for new segment rotation | + +No series carries a secret, a peer address, a data-directory path, or a user key. The storage-unrecoverable detail string stays in the process log and is not copied into the probe body. + +## `[raft]` + +```toml +[raft] +heartbeat_interval_ms = 150 +election_timeout_min_ms = 450 +election_timeout_max_ms = 900 +max_in_snapshot_log_to_keep = 0 +max_segment_bytes = 67108864 +``` + +Omitted fields use those defaults. An omitted table uses all of them. Unknown keys inside `[raft]` fail parsing. The same OpenRaft check used at group start rejects the table when `election_timeout_min_ms` is not greater than `heartbeat_interval_ms`, or when it is not less than `election_timeout_max_ms`. `max_segment_bytes = 0` is rejected because rotation would open a file on every append. `max_in_snapshot_log_to_keep = 0` remains valid. + +The values are applied when each `ShardRaftGroup` starts. They are not reloaded from a changed file. A later edit requires a process restart. `max_segment_bytes` affects rotation of the active segment. It does not rewrite segments already on disk. The five numbers are logged once at info when startup finishes (`applied raft options`) and are the gauges above. The log line does not include the shared secret. + +`join_timeout` is still not a TOML field. + +Other unknown keys outside `[raft]` and outside the security-key rejection are still ignored. That fail-open hole is unchanged. `[security]` parsing is unchanged: a TLS key, a misspelled `shared_secret`, and a secret outside `[security]` still refuse to start. diff --git a/docs/en/operations.md b/docs/en/operations.md index bea2185..481c97d 100644 --- a/docs/en/operations.md +++ b/docs/en/operations.md @@ -73,7 +73,7 @@ The separate prefix-load harness (100 prefixes × 10,000 creates, then 100,000 ` ## Metrics -Set `node.metrics_listen_addr` (for example `127.0.0.1:9100`). `open_and_serve` accepts TCP connections on that address. `GET /metrics` returns Prometheus text. Any other path returns 404, and any other method returns 405. When `[security].shared_secret` contains a non-whitespace character, every request on this listener must send `Authorization: Bearer `. A missing, empty, or wrong bearer returns HTTP 401 and a body that is not the metric text, including a request for `/status`. An empty secret refuses to start on every address, including loopback, unless `allow_unauthenticated` is set. That flag still refuses a non-loopback metrics address. A whitespace-only secret refuses to start even when the flag is set. This listener does not terminate TLS. +Set `node.metrics_listen_addr` (for example `127.0.0.1:9100`). `open_and_serve` accepts TCP connections on that address before join finishes, so a probe can observe `starting`. `GET /metrics` returns Prometheus text even when the process is not ready. `GET /livez` is liveness. `GET /readyz` and `GET /healthz` are readiness: HTTP 200 only when startup has finished, shutdown has not started, and every local shard has recovered its committed prefix, applied a log entry, is a voter, and knows a leader. A bound socket is not enough. Any other path returns 404, and any other method returns 405. When `[security].shared_secret` contains a non-whitespace character, every request on this listener must send `Authorization: Bearer `. A missing, empty, or wrong bearer returns HTTP 401 and a body that is not the metric text, including a request for `/status` or `/readyz`. A whitespace-only secret is rejected before that compare, so a bearer that repeats the spaces is still 401. An empty secret refuses to start on every address, including loopback, unless `allow_unauthenticated` is set. That flag still refuses a non-loopback metrics address. A whitespace-only secret refuses to start even when the flag is set. This listener does not terminate TLS. The exact reason tokens and the checks that are intentionally omitted are in [Operability](./operability.md). Gauges and counters from `render_prometheus_metrics`: @@ -88,8 +88,24 @@ Gauges and counters from `render_prometheus_metrics`: | `metadb_tombstones_traversed_on_scans_total` | counter | | `metadb_locality_compactions_total` | counter | | `metadb_min_raft_safe_purge_index` | gauge | - -There is no `metadb_raft_watermark_lag_entries` series. `metadb_cells_total` counts cells registered inside this process, which `open_and_serve` sets to one. +| `metadb_ready` | gauge, 1 only when `/readyz` is 200 | +| `metadb_live` | gauge, 1 when `/livez` is 200 | +| `metadb_process_phase` | gauge, 0 starting, 1 serving, 2 shutting down, 3 failed | +| `metadb_shards_leader_known` | gauge, local groups with a known leader | +| `metadb_shards_leader_unknown` | gauge | +| `metadb_shards_recovery_pending` | gauge | +| `metadb_shards_log_not_applied` | gauge | +| `metadb_shards_not_voter` | gauge | +| `metadb_shards_storage_unrecoverable` | gauge | +| `metadb_shards_raft_stopped` | gauge | +| `metadb_shards_raft_fatal` | gauge | +| `metadb_raft_heartbeat_interval_ms` | gauge, configured value | +| `metadb_raft_election_timeout_min_ms` | gauge, configured value | +| `metadb_raft_election_timeout_max_ms` | gauge, configured value | +| `metadb_raft_max_in_snapshot_log_to_keep` | gauge, configured value | +| `metadb_raft_max_segment_bytes` | gauge, configured value | + +There is no `metadb_raft_watermark_lag_entries` series and no per-shard label. `metadb_cells_total` counts cells registered inside this process, which `open_and_serve` sets to one. `metadb_process_phase 1` does not by itself mean `metadb_ready 1`. ## Scale-out @@ -141,8 +157,8 @@ Variants are defined in `crates/metadb-core/src/error.rs`. gRPC methods usually - Quota cursor rows are written after the outbox lock is released, so a flush that already holds the memtable lock can still take the outbox lock. - Jumbo isolation is a route flag plus a node id chosen from the local node map. It does not evict other shards from a disk. - Heartbeats are an RPC with no sender in `metadbd`. `StoreHeartbeat` does not persist. -- A non-empty shared secret authenticates Raft, the other three gRPC services, and the metrics listener with the same bearer. An empty secret does not start the process. `allow_unauthenticated = true` is the explicit exception for literal loopback IPs (`127.0.0.0/8` or `::1`) and still refuses a wildcard bind. The hostname `localhost` is not accepted for that exception. A whitespace-only secret is rejected. The process does not terminate TLS. -- `memtable_size_bytes` seals and flushes the active memtable. `max_imm_memtables` caps queued immutable tables. Raft timer fields do not change runtime behavior through TOML. +- A secret that contains a non-whitespace character authenticates Raft, the other three gRPC services, and the metrics listener, including `/livez`, `/readyz`, and `/healthz`, with the same bearer. An empty secret does not start the process. `allow_unauthenticated = true` is the explicit exception for literal loopback IPs (`127.0.0.0/8` or `::1`) and still refuses a wildcard bind. The hostname `localhost` is not accepted for that exception. The bound socket is checked again after listen. A whitespace-only secret is rejected and is not compared as a bearer. The process does not terminate TLS. +- `memtable_size_bytes` seals and flushes the active memtable. `max_imm_memtables` caps queued immutable tables. `[raft]` timers and `max_segment_bytes` apply when a group starts. They are not reloaded from a changed file, and the segment size does not rewrite segments already on disk. - `metadb-ctl bench` for `hotspot-create` and `bulk-ttl-delete` prints JSON lines: a header with `bench_pid`, then phase reports with attempted, succeeded, failed, and latency percentiles. The process exits non-zero unless every requested operation succeeds. `--workload mixed` or `--embedded` runs the in-process stress harness. `sql` prints the response as JSON and exits non-zero on an application error. ## Backup and restore @@ -198,5 +214,5 @@ These items are missing from the product, so this guide cannot describe a proced 2. A second Cell. `RegisterCell` stays an error. Join reaches only the current leader; a follower does not forward it. 3. Placing a jumbo shard on its own machine and moving other shards off that machine. 4. Native TLS. This process does not terminate TLS. Config keys that ask for TLS or a certificate are rejected instead of serving plaintext. Put termination in an external proxy. Raft and metrics use the same bearer as the other services when a secret is set; that bearer is not mutual TLS. A heartbeat-driven control loop is not implemented. -5. A Raft timer that operators can set and observe. +5. A gRPC health RPC, probes when `metrics_listen_addr` is unset, and per-shard Prometheus series. `/readyz` does not wait for the 250 ms 2PC recovery pass. See [Operability](./operability.md). 6. A checked-in service-level result for `metadb-ctl bench`. The command prints numbers for the machine you run it on. This repository does not record one. See [Tests and benches](./testing.md). diff --git a/docs/guides/en/deployment.md b/docs/guides/en/deployment.md index 3170894..e8ced38 100644 --- a/docs/guides/en/deployment.md +++ b/docs/guides/en/deployment.md @@ -55,7 +55,7 @@ metadbd --config /etc/metadb/standalone.toml `MetadataService`, `TransactionService`, `ControlPlaneService`, `RaftTransportService`, and the metrics listener do **not** terminate TLS. An empty `[security].shared_secret` does not start the process, including on the default `127.0.0.1:7800` bind. Set `allow_unauthenticated = true` only for development on a literal loopback IP such as `127.0.0.1`. The hostname `localhost` is not accepted for that flag. A wildcard or other non-loopback address without a non-empty secret still refuses to start. A TLS, certificate, anonymous, or insecure key in this file is rejected rather than served as plaintext. -To require `authorization: Bearer ` on metadata, transaction, control-plane, Raft transport, and `GET /metrics`, replace the `[security]` table above. Do not leave `allow_unauthenticated` in the file. A whitespace-only `shared_secret` is rejected even if that flag remains. Peer Raft clients propagate the same token. `metadb-ctl --auth-token` (or `METADB_AUTH_TOKEN`) and `metadbd --cell-manager` send that header: +To require `authorization: Bearer ` on metadata, transaction, control-plane, Raft transport, and every metrics-listener request (`GET /metrics`, `/livez`, `/readyz`, `/healthz`), replace the `[security]` table above. Do not leave `allow_unauthenticated` in the file. A whitespace-only `shared_secret` is rejected even if that flag remains, and it is not accepted as the bearer on those probes. `/readyz` reports traffic readiness, not merely that the port is open. See [Operability](../../en/operability.md). Peer Raft clients propagate the same token. `metadb-ctl --auth-token` (or `METADB_AUTH_TOKEN`) and `metadbd --cell-manager` send that header: ```toml [security] diff --git a/docs/guides/en/operations-and-tuning.md b/docs/guides/en/operations-and-tuning.md index 9278239..0721432 100644 --- a/docs/guides/en/operations-and-tuning.md +++ b/docs/guides/en/operations-and-tuning.md @@ -87,4 +87,4 @@ cargo test -p metadb-server --test topology_distributed three_voter_leader_loss_ * *Fix*: Handled automatically by `metadb-proxy` and the Rust SDK via `MetaCache` refresh + retry. Persistent occurrences indicate an unreachable `CellLocalManager`. * **Growing `.raftlog` Disk Usage**: * *Cause*: `safe_purge_index = min(state_flushed_index, aux_outbox_durable_index, last_snapshot_index)` is pinned by stalled L0 disk I/O or a blocked snapshot transfer. (Note: unreachable remote `QuotaTable` shards do **not** pin `.raftlog` indefinitely because overdue `AuxOutbox` tasks spill to local `[0x07]` SSTables on L0 flush.) - * *Fix*: Inspect NVMe write latency and the exposed `metadb_min_raft_safe_purge_index` metric (`:9100/metrics`). Compare per-shard logs during diagnosis; no per-shard watermark-lag metric is currently exported. + * *Fix*: Inspect NVMe write latency and the exposed `metadb_min_raft_safe_purge_index` metric (`:9100/metrics`). Compare per-shard logs during diagnosis; no per-shard watermark-lag metric is currently exported. `metadb_ready` and `metadb_shards_leader_unknown` are unlabeled process gauges. See [Operability](../../en/operability.md).