1use crate::consensus::ConsensusManager;
7use crate::discovery::DiscoveryService;
8use crate::error::{ClusterError, Result};
9use crate::health_monitor::{HealthMonitor, NodeHealth};
10use crate::raft::OxirsNodeId;
11use crate::replication::ReplicationManager;
12use serde::{Deserialize, Serialize};
13use std::collections::HashMap;
14use std::net::SocketAddr;
15use std::sync::Arc;
16use std::time::{Duration, SystemTime, UNIX_EPOCH};
17use tokio::sync::{Mutex, RwLock};
18use tokio::time::{interval, timeout};
19use tracing::{debug, error, info, warn};
20
21#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
23pub enum NodeState {
24 Starting,
26 Active,
28 Degraded,
30 Suspended,
32 Draining,
34 Leaving,
36 Left,
38 Failed,
40 Suspected,
42}
43
44impl NodeState {
45 pub fn is_operational(self) -> bool {
47 matches!(self, NodeState::Active | NodeState::Degraded)
48 }
49
50 pub fn is_consensus_eligible(self) -> bool {
52 matches!(
53 self,
54 NodeState::Active | NodeState::Degraded | NodeState::Draining
55 )
56 }
57
58 pub fn is_healthy(self) -> bool {
60 matches!(self, NodeState::Active)
61 }
62}
63
64#[derive(Debug, Clone, Serialize, Deserialize)]
66pub enum LifecycleEvent {
67 NodeJoining {
69 node_id: OxirsNodeId,
70 address: SocketAddr,
71 metadata: NodeMetadata,
72 },
73 NodeJoined {
75 node_id: OxirsNodeId,
76 timestamp: u64,
77 },
78 NodeStateChanged {
80 node_id: OxirsNodeId,
81 old_state: NodeState,
82 new_state: NodeState,
83 reason: String,
84 timestamp: u64,
85 },
86 NodeLeaving {
88 node_id: OxirsNodeId,
89 reason: String,
90 graceful: bool,
91 },
92 NodeLeft {
94 node_id: OxirsNodeId,
95 timestamp: u64,
96 },
97 NodeEvicted {
99 node_id: OxirsNodeId,
100 reason: String,
101 timestamp: u64,
102 },
103 MembershipChanged {
105 added_nodes: Vec<OxirsNodeId>,
106 removed_nodes: Vec<OxirsNodeId>,
107 timestamp: u64,
108 },
109}
110
111#[derive(Debug, Clone, Serialize, Deserialize)]
113pub struct NodeMetadata {
114 pub capabilities: Vec<String>,
116 pub datacenter: Option<String>,
118 pub rack: Option<String>,
120 pub version: String,
122 pub tags: HashMap<String, String>,
124 pub capacity: ResourceCapacity,
126}
127
128impl Default for NodeMetadata {
129 fn default() -> Self {
130 Self {
131 capabilities: vec!["raft".to_string(), "rdf".to_string()],
132 datacenter: None,
133 rack: None,
134 version: env!("CARGO_PKG_VERSION").to_string(),
135 tags: HashMap::new(),
136 capacity: ResourceCapacity::default(),
137 }
138 }
139}
140
141#[derive(Debug, Clone, Serialize, Deserialize)]
143pub struct ResourceCapacity {
144 pub cpu_cores: u32,
146 pub memory_bytes: u64,
148 pub disk_bytes: u64,
150 pub network_bandwidth: u64,
152 pub max_connections: u32,
154}
155
156impl Default for ResourceCapacity {
157 fn default() -> Self {
158 Self {
159 cpu_cores: std::thread::available_parallelism()
160 .map(|n| n.get())
161 .unwrap_or(1) as u32,
162 memory_bytes: 8 * 1024 * 1024 * 1024, disk_bytes: 100 * 1024 * 1024 * 1024, network_bandwidth: 1_000_000_000, max_connections: 10000,
166 }
167 }
168}
169
170#[derive(Debug, Clone, Serialize, Deserialize)]
172pub struct LifecycleConfig {
173 pub health_check_interval: Duration,
175 pub failure_timeout: Duration,
177 pub graceful_shutdown_timeout: Duration,
179 pub removal_grace_period: Duration,
181 pub enable_auto_failure_detection: bool,
183 pub enable_auto_recovery: bool,
185 pub min_cluster_size: usize,
187 pub join_timeout: Duration,
189 pub enable_byzantine_detection: bool,
191}
192
193impl Default for LifecycleConfig {
194 fn default() -> Self {
195 Self {
196 health_check_interval: Duration::from_secs(30),
197 failure_timeout: Duration::from_secs(120),
198 graceful_shutdown_timeout: Duration::from_secs(300),
199 removal_grace_period: Duration::from_secs(600),
200 enable_auto_failure_detection: true,
201 enable_auto_recovery: true,
202 min_cluster_size: 3,
203 join_timeout: Duration::from_secs(60),
204 enable_byzantine_detection: true,
205 }
206 }
207}
208
209#[derive(Debug, Clone, Serialize, Deserialize)]
211pub struct NodeStatus {
212 pub node_id: OxirsNodeId,
214 pub state: NodeState,
216 pub address: SocketAddr,
218 pub metadata: NodeMetadata,
220 pub last_seen: u64,
222 pub health: NodeHealth,
224 pub joined_at: u64,
226 pub state_history: Vec<(NodeState, u64, String)>,
228 pub performance_score: f64,
230 pub failure_count: u32,
232}
233
234impl NodeStatus {
235 pub fn new(node_id: OxirsNodeId, address: SocketAddr, metadata: NodeMetadata) -> Self {
237 let now = SystemTime::now()
238 .duration_since(UNIX_EPOCH)
239 .expect("system time should be after UNIX_EPOCH")
240 .as_secs();
241
242 Self {
243 node_id,
244 state: NodeState::Starting,
245 address,
246 metadata,
247 last_seen: now,
248 health: NodeHealth::default(),
249 joined_at: now,
250 state_history: vec![(NodeState::Starting, now, "Initial state".to_string())],
251 performance_score: 1.0,
252 failure_count: 0,
253 }
254 }
255
256 pub fn update_state(&mut self, new_state: NodeState, reason: String) {
258 let now = SystemTime::now()
259 .duration_since(UNIX_EPOCH)
260 .expect("system time should be after UNIX_EPOCH")
261 .as_secs();
262
263 self.state_history.push((new_state, now, reason));
265
266 if self.state_history.len() > 10 {
268 self.state_history.remove(0);
269 }
270
271 self.state = new_state;
272 self.last_seen = now;
273
274 if matches!(new_state, NodeState::Active) {
276 self.failure_count = 0;
277 }
278 }
279
280 pub fn update_health(&mut self, health: NodeHealth) {
282 self.health = health;
283 self.last_seen = SystemTime::now()
284 .duration_since(UNIX_EPOCH)
285 .expect("system time should be after UNIX_EPOCH")
286 .as_secs();
287
288 self.performance_score = self.calculate_performance_score();
290 }
291
292 fn calculate_performance_score(&self) -> f64 {
294 let mut score: f64 = 1.0;
295
296 if self.health.system_metrics.cpu_usage > 0.8 {
298 score *= 0.7;
299 } else if self.health.system_metrics.cpu_usage > 0.6 {
300 score *= 0.9;
301 }
302
303 if self.health.system_metrics.memory_usage > 0.9 {
305 score *= 0.6;
306 } else if self.health.system_metrics.memory_usage > 0.7 {
307 score *= 0.8;
308 }
309
310 if self.health.response_time > Duration::from_millis(1000) {
312 score *= 0.7;
313 } else if self.health.response_time > Duration::from_millis(500) {
314 score *= 0.9;
315 }
316
317 if self.failure_count > 5 {
319 score *= 0.5;
320 } else if self.failure_count > 2 {
321 score *= 0.8;
322 }
323
324 score.clamp(0.0, 1.0)
325 }
326
327 pub fn is_stale(&self, timeout: Duration) -> bool {
329 let now = SystemTime::now()
330 .duration_since(UNIX_EPOCH)
331 .expect("system time should be after UNIX_EPOCH")
332 .as_secs();
333 now.saturating_sub(self.last_seen) > timeout.as_secs()
334 }
335
336 pub fn record_failure(&mut self) {
338 self.failure_count += 1;
339 self.performance_score = self.calculate_performance_score();
340 }
341}
342
343pub struct NodeLifecycleManager {
345 local_node_id: OxirsNodeId,
347 config: LifecycleConfig,
349 consensus: Arc<ConsensusManager>,
351 discovery: Arc<DiscoveryService>,
353 health_monitor: Arc<HealthMonitor>,
355 replication: Arc<ReplicationManager>,
357 node_status: Arc<RwLock<HashMap<OxirsNodeId, NodeStatus>>>,
359 event_listeners: Arc<RwLock<Vec<tokio::sync::mpsc::UnboundedSender<LifecycleEvent>>>>,
361 task_handle: Arc<Mutex<Option<tokio::task::JoinHandle<()>>>>,
363}
364
365impl NodeLifecycleManager {
366 pub fn new(
368 local_node_id: OxirsNodeId,
369 config: LifecycleConfig,
370 consensus: Arc<ConsensusManager>,
371 discovery: Arc<DiscoveryService>,
372 health_monitor: Arc<HealthMonitor>,
373 replication: Arc<ReplicationManager>,
374 ) -> Self {
375 Self {
376 local_node_id,
377 config,
378 consensus,
379 discovery,
380 health_monitor,
381 replication,
382 node_status: Arc::new(RwLock::new(HashMap::new())),
383 event_listeners: Arc::new(RwLock::new(Vec::new())),
384 task_handle: Arc::new(Mutex::new(None)),
385 }
386 }
387
388 pub async fn start(&self) -> Result<()> {
390 info!(
391 "Starting node lifecycle manager for node {}",
392 self.local_node_id
393 );
394
395 let task_handle = {
397 let manager = self.clone();
398 tokio::spawn(async move {
399 manager.monitoring_loop().await;
400 })
401 };
402
403 let mut handle = self.task_handle.lock().await;
404 *handle = Some(task_handle);
405
406 Ok(())
407 }
408
409 pub async fn stop(&self) -> Result<()> {
411 info!("Stopping node lifecycle manager");
412
413 let mut handle = self.task_handle.lock().await;
414 if let Some(task) = handle.take() {
415 task.abort();
416 }
417
418 Ok(())
419 }
420
421 pub async fn add_node(
423 &self,
424 node_id: OxirsNodeId,
425 address: SocketAddr,
426 metadata: NodeMetadata,
427 ) -> Result<()> {
428 info!("Adding node {} at {} to cluster", node_id, address);
429
430 {
432 let nodes = self.node_status.read().await;
433 if nodes.contains_key(&node_id) {
434 return Err(ClusterError::Config(format!(
435 "Node {node_id} already exists"
436 )));
437 }
438 }
439
440 let node_status = NodeStatus::new(node_id, address, metadata.clone());
442
443 self.emit_event(LifecycleEvent::NodeJoining {
445 node_id,
446 address,
447 metadata,
448 })
449 .await;
450
451 let join_result = timeout(
453 self.config.join_timeout,
454 self.perform_node_join(node_id, address, node_status),
455 )
456 .await;
457
458 match join_result {
459 Ok(Ok(())) => {
460 info!("Successfully added node {} to cluster", node_id);
461
462 self.emit_event(LifecycleEvent::NodeJoined {
464 node_id,
465 timestamp: SystemTime::now()
466 .duration_since(UNIX_EPOCH)
467 .expect("system time should be after UNIX_EPOCH")
468 .as_secs(),
469 })
470 .await;
471
472 Ok(())
473 }
474 Ok(Err(e)) => {
475 error!("Failed to add node {}: {}", node_id, e);
476 self.cleanup_failed_join(node_id).await;
477 Err(e)
478 }
479 Err(_) => {
480 error!("Node join timed out for node {}", node_id);
481 self.cleanup_failed_join(node_id).await;
482 Err(ClusterError::Other("Node join timed out".to_string()))
483 }
484 }
485 }
486
487 async fn perform_node_join(
489 &self,
490 node_id: OxirsNodeId,
491 address: SocketAddr,
492 mut node_status: NodeStatus,
493 ) -> Result<()> {
494 node_status.update_state(NodeState::Active, "Successfully joined cluster".to_string());
508
509 {
511 let mut nodes = self.node_status.write().await;
512 nodes.insert(node_id, node_status);
513 }
514
515 self.health_monitor
517 .start_monitoring(node_id, address.to_string())
518 .await;
519
520 Ok(())
521 }
522
523 async fn cleanup_failed_join(&self, node_id: OxirsNodeId) {
525 warn!("Cleaning up failed join for node {}", node_id);
526
527 let mut nodes = self.node_status.write().await;
537 nodes.remove(&node_id);
538 }
539
540 pub async fn remove_node(&self, node_id: OxirsNodeId, graceful: bool) -> Result<()> {
542 info!(
543 "Removing node {} from cluster (graceful: {})",
544 node_id, graceful
545 );
546
547 let node_exists = {
549 let nodes = self.node_status.read().await;
550 nodes.contains_key(&node_id)
551 };
552
553 if !node_exists {
554 return Err(ClusterError::Config(format!("Node {node_id} not found")));
555 }
556
557 self.emit_event(LifecycleEvent::NodeLeaving {
559 node_id,
560 reason: if graceful {
561 "Graceful shutdown"
562 } else {
563 "Forced removal"
564 }
565 .to_string(),
566 graceful,
567 })
568 .await;
569
570 if graceful {
571 self.perform_graceful_removal(node_id).await?;
573 } else {
574 self.perform_immediate_removal(node_id).await?;
576 }
577
578 self.emit_event(LifecycleEvent::NodeLeft {
580 node_id,
581 timestamp: SystemTime::now()
582 .duration_since(UNIX_EPOCH)
583 .expect("system time should be after UNIX_EPOCH")
584 .as_secs(),
585 })
586 .await;
587
588 info!("Successfully removed node {} from cluster", node_id);
589 Ok(())
590 }
591
592 async fn perform_graceful_removal(&self, node_id: OxirsNodeId) -> Result<()> {
594 {
596 let mut nodes = self.node_status.write().await;
597 if let Some(node_status) = nodes.get_mut(&node_id) {
598 node_status.update_state(
599 NodeState::Draining,
600 "Graceful removal initiated".to_string(),
601 );
602 }
603 }
604
605 tokio::time::sleep(Duration::from_secs(5)).await;
607
608 self.perform_immediate_removal(node_id).await
610 }
611
612 async fn perform_immediate_removal(&self, node_id: OxirsNodeId) -> Result<()> {
614 self.health_monitor.stop_monitoring(node_id).await;
624
625 {
627 let mut nodes = self.node_status.write().await;
628 if let Some(node_status) = nodes.get_mut(&node_id) {
629 node_status.update_state(NodeState::Left, "Removed from cluster".to_string());
630 }
631 }
632
633 let nodes = Arc::clone(&self.node_status);
635 tokio::spawn(async move {
636 tokio::time::sleep(Duration::from_secs(300)).await; let mut nodes = nodes.write().await;
638 nodes.remove(&node_id);
639 });
640
641 Ok(())
642 }
643
644 pub async fn force_evict_node(&self, node_id: OxirsNodeId, reason: String) -> Result<()> {
646 warn!("Force evicting node {}: {}", node_id, reason);
647
648 {
650 let mut nodes = self.node_status.write().await;
651 if let Some(node_status) = nodes.get_mut(&node_id) {
652 node_status.update_state(NodeState::Failed, reason.clone());
653 }
654 }
655
656 self.emit_event(LifecycleEvent::NodeEvicted {
658 node_id,
659 reason: reason.clone(),
660 timestamp: SystemTime::now()
661 .duration_since(UNIX_EPOCH)
662 .expect("system time should be after UNIX_EPOCH")
663 .as_secs(),
664 })
665 .await;
666
667 self.perform_immediate_removal(node_id).await?;
669
670 info!("Successfully evicted node {}", node_id);
671 Ok(())
672 }
673
674 pub async fn get_node_status(&self, node_id: OxirsNodeId) -> Option<NodeStatus> {
676 let nodes = self.node_status.read().await;
677 nodes.get(&node_id).cloned()
678 }
679
680 pub async fn get_all_node_statuses(&self) -> HashMap<OxirsNodeId, NodeStatus> {
682 let nodes = self.node_status.read().await;
683 nodes.clone()
684 }
685
686 pub async fn get_healthy_nodes(&self) -> Vec<OxirsNodeId> {
688 let nodes = self.node_status.read().await;
689 nodes
690 .values()
691 .filter(|status| status.state.is_healthy())
692 .map(|status| status.node_id)
693 .collect()
694 }
695
696 pub async fn get_operational_nodes(&self) -> Vec<OxirsNodeId> {
698 let nodes = self.node_status.read().await;
699 nodes
700 .values()
701 .filter(|status| status.state.is_operational())
702 .map(|status| status.node_id)
703 .collect()
704 }
705
706 pub async fn check_cluster_health(&self) -> ClusterHealthStatus {
708 let nodes = self.node_status.read().await;
709 let total_nodes = nodes.len();
710 let healthy_nodes = nodes.values().filter(|s| s.state.is_healthy()).count();
711 let operational_nodes = nodes.values().filter(|s| s.state.is_operational()).count();
712 let failed_nodes = nodes
713 .values()
714 .filter(|s| matches!(s.state, NodeState::Failed))
715 .count();
716
717 let health_ratio = if total_nodes > 0 {
718 healthy_nodes as f64 / total_nodes as f64
719 } else {
720 1.0
721 };
722
723 let status = if health_ratio >= 0.8 {
724 ClusterHealth::Healthy
725 } else if health_ratio >= 0.6 {
726 ClusterHealth::Degraded
727 } else if operational_nodes >= self.config.min_cluster_size {
728 ClusterHealth::Unstable
729 } else {
730 ClusterHealth::Critical
731 };
732
733 ClusterHealthStatus {
734 status,
735 total_nodes,
736 healthy_nodes,
737 operational_nodes,
738 failed_nodes,
739 health_ratio,
740 min_cluster_size: self.config.min_cluster_size,
741 }
742 }
743
744 async fn monitoring_loop(&self) {
746 let mut interval = interval(self.config.health_check_interval);
747
748 loop {
749 interval.tick().await;
750
751 if let Err(e) = self.perform_health_check().await {
752 error!("Health check failed: {}", e);
753 }
754
755 if self.config.enable_auto_failure_detection {
756 if let Err(e) = self.detect_and_handle_failures().await {
757 error!("Failure detection failed: {}", e);
758 }
759 }
760
761 if self.config.enable_byzantine_detection {
762 if let Err(e) = self.detect_byzantine_behavior().await {
763 error!("Byzantine detection failed: {}", e);
764 }
765 }
766 }
767 }
768
769 async fn perform_health_check(&self) -> Result<()> {
771 debug!("Performing health check on all nodes");
772
773 let node_ids: Vec<OxirsNodeId> = {
774 let nodes = self.node_status.read().await;
775 nodes.keys().copied().collect()
776 };
777
778 for node_id in node_ids {
779 if let Some(health_status) = self.health_monitor.get_node_health(node_id).await {
780 let mut nodes = self.node_status.write().await;
781 if let Some(node_status) = nodes.get_mut(&node_id) {
782 node_status.update_health(health_status.health);
783
784 let new_state = if node_status.health.status
786 == crate::health_monitor::NodeHealthLevel::Healthy
787 {
788 NodeState::Active
789 } else if node_status.health.system_metrics.cpu_usage > 0.9
790 || node_status.health.system_metrics.memory_usage > 0.95
791 {
792 NodeState::Degraded
793 } else {
794 node_status.state };
796
797 if new_state != node_status.state {
798 let old_state = node_status.state;
799 node_status
800 .update_state(new_state, "Health check state change".to_string());
801
802 self.emit_event(LifecycleEvent::NodeStateChanged {
804 node_id,
805 old_state,
806 new_state,
807 reason: "Health check state change".to_string(),
808 timestamp: SystemTime::now()
809 .duration_since(UNIX_EPOCH)
810 .expect("system time should be after UNIX_EPOCH")
811 .as_secs(),
812 })
813 .await;
814 }
815 }
816 }
817 }
818
819 Ok(())
820 }
821
822 async fn detect_and_handle_failures(&self) -> Result<()> {
824 debug!("Detecting node failures");
825
826 let failed_nodes: Vec<OxirsNodeId> = {
827 let nodes = self.node_status.read().await;
828 nodes
829 .values()
830 .filter(|status| {
831 status.is_stale(self.config.failure_timeout)
832 && !matches!(status.state, NodeState::Failed | NodeState::Left)
833 })
834 .map(|status| status.node_id)
835 .collect()
836 };
837
838 for node_id in failed_nodes {
839 warn!("Detected failed node: {}", node_id);
840
841 {
843 let mut nodes = self.node_status.write().await;
844 if let Some(node_status) = nodes.get_mut(&node_id) {
845 let old_state = node_status.state;
846 node_status
847 .update_state(NodeState::Failed, "Node failure detected".to_string());
848 node_status.record_failure();
849
850 self.emit_event(LifecycleEvent::NodeStateChanged {
852 node_id,
853 old_state,
854 new_state: NodeState::Failed,
855 reason: "Node failure detected".to_string(),
856 timestamp: SystemTime::now()
857 .duration_since(UNIX_EPOCH)
858 .expect("system time should be after UNIX_EPOCH")
859 .as_secs(),
860 })
861 .await;
862 }
863 }
864
865 if self.config.enable_auto_recovery {
867 let manager = self.clone();
869 tokio::spawn(async move {
870 tokio::time::sleep(manager.config.removal_grace_period).await;
871
872 if let Some(status) = manager.get_node_status(node_id).await {
874 if matches!(status.state, NodeState::Failed) {
875 if let Err(e) = manager
876 .force_evict_node(node_id, "Auto-recovery eviction".to_string())
877 .await
878 {
879 error!("Failed to auto-evict node {}: {}", node_id, e);
880 }
881 }
882 }
883 });
884 }
885 }
886
887 Ok(())
888 }
889
890 async fn detect_byzantine_behavior(&self) -> Result<()> {
892 debug!("Checking for Byzantine behavior");
897
898 let suspected_nodes: Vec<OxirsNodeId> = {
899 let nodes = self.node_status.read().await;
900 nodes
901 .values()
902 .filter(|status| {
903 status.failure_count > 10 || status.performance_score < 0.2 })
906 .map(|status| status.node_id)
907 .collect()
908 };
909
910 for node_id in suspected_nodes {
911 warn!("Suspected Byzantine behavior from node: {}", node_id);
912
913 {
915 let mut nodes = self.node_status.write().await;
916 if let Some(node_status) = nodes.get_mut(&node_id) {
917 let old_state = node_status.state;
918 node_status.update_state(
919 NodeState::Suspected,
920 "Byzantine behavior detected".to_string(),
921 );
922
923 self.emit_event(LifecycleEvent::NodeStateChanged {
925 node_id,
926 old_state,
927 new_state: NodeState::Suspected,
928 reason: "Byzantine behavior detected".to_string(),
929 timestamp: SystemTime::now()
930 .duration_since(UNIX_EPOCH)
931 .expect("system time should be after UNIX_EPOCH")
932 .as_secs(),
933 })
934 .await;
935 }
936 }
937
938 }
941
942 Ok(())
943 }
944
945 async fn emit_event(&self, event: LifecycleEvent) {
947 let listeners = self.event_listeners.read().await;
948 for listener in listeners.iter() {
949 if listener.send(event.clone()).is_err() {
950 }
952 }
953 }
954
955 pub async fn subscribe_events(&self) -> tokio::sync::mpsc::UnboundedReceiver<LifecycleEvent> {
957 let (sender, receiver) = tokio::sync::mpsc::unbounded_channel();
958 let mut listeners = self.event_listeners.write().await;
959 listeners.push(sender);
960 receiver
961 }
962
963 pub async fn transfer_leadership(&self, target_node: Option<OxirsNodeId>) -> Result<()> {
965 info!("Transferring leadership before shutdown");
966
967 if let Some(target) = target_node {
968 self.consensus
970 .transfer_leadership(target)
971 .await
972 .map_err(|e| ClusterError::Other(format!("Leadership transfer failed: {e}")))?;
973 } else {
974 let healthy_nodes = self.get_healthy_nodes().await;
976 if let Some(&target) = healthy_nodes.first() {
977 if target != self.local_node_id {
978 self.consensus
979 .transfer_leadership(target)
980 .await
981 .map_err(|e| {
982 ClusterError::Other(format!("Leadership transfer failed: {e}"))
983 })?;
984 }
985 }
986 }
987
988 info!("Leadership transfer completed");
989 Ok(())
990 }
991
992 pub async fn graceful_shutdown(&self) -> Result<()> {
994 info!("Initiating graceful shutdown of local node");
995
996 if self.consensus.is_leader().await {
998 self.transfer_leadership(None).await?;
999 }
1000
1001 self.remove_node(self.local_node_id, true).await?;
1003
1004 self.stop().await?;
1006
1007 info!("Graceful shutdown completed");
1008 Ok(())
1009 }
1010}
1011
1012impl Clone for NodeLifecycleManager {
1013 fn clone(&self) -> Self {
1014 Self {
1015 local_node_id: self.local_node_id,
1016 config: self.config.clone(),
1017 consensus: Arc::clone(&self.consensus),
1018 discovery: Arc::clone(&self.discovery),
1019 health_monitor: Arc::clone(&self.health_monitor),
1020 replication: Arc::clone(&self.replication),
1021 node_status: Arc::clone(&self.node_status),
1022 event_listeners: Arc::clone(&self.event_listeners),
1023 task_handle: Arc::clone(&self.task_handle),
1024 }
1025 }
1026}
1027
1028#[derive(Debug, Clone, Serialize, Deserialize)]
1030pub struct ClusterHealthStatus {
1031 pub status: ClusterHealth,
1032 pub total_nodes: usize,
1033 pub healthy_nodes: usize,
1034 pub operational_nodes: usize,
1035 pub failed_nodes: usize,
1036 pub health_ratio: f64,
1037 pub min_cluster_size: usize,
1038}
1039
1040#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
1042pub enum ClusterHealth {
1043 Healthy,
1044 Degraded,
1045 Unstable,
1046 Critical,
1047}
1048
1049impl ClusterHealth {
1050 pub fn is_operational(self) -> bool {
1051 !matches!(self, ClusterHealth::Critical)
1052 }
1053}
1054
1055#[cfg(test)]
1056mod tests {
1057 use super::*;
1058 use std::net::{IpAddr, Ipv4Addr};
1059
1060 #[test]
1061 fn test_node_state_properties() {
1062 assert!(NodeState::Active.is_operational());
1063 assert!(NodeState::Active.is_consensus_eligible());
1064 assert!(NodeState::Active.is_healthy());
1065
1066 assert!(NodeState::Degraded.is_operational());
1067 assert!(NodeState::Degraded.is_consensus_eligible());
1068 assert!(!NodeState::Degraded.is_healthy());
1069
1070 assert!(!NodeState::Failed.is_operational());
1071 assert!(!NodeState::Failed.is_consensus_eligible());
1072 assert!(!NodeState::Failed.is_healthy());
1073 }
1074
1075 #[test]
1076 fn test_node_status_performance_scoring() {
1077 let addr = SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), 8080);
1078 let metadata = NodeMetadata::default();
1079 let mut status = NodeStatus::new(1, addr, metadata);
1080
1081 assert!(status.performance_score > 0.8);
1083
1084 status.record_failure();
1086 status.record_failure();
1087 status.record_failure();
1088 assert!(status.performance_score < 0.9);
1089
1090 for _ in 0..10 {
1092 status.record_failure();
1093 }
1094 assert!(status.performance_score < 0.6);
1095 }
1096
1097 #[test]
1098 fn test_node_status_state_history() {
1099 let addr = SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), 8080);
1100 let metadata = NodeMetadata::default();
1101 let mut status = NodeStatus::new(1, addr, metadata);
1102
1103 assert_eq!(status.state, NodeState::Starting);
1105 assert_eq!(status.state_history.len(), 1);
1106
1107 status.update_state(NodeState::Active, "Joined cluster".to_string());
1109 status.update_state(NodeState::Degraded, "High CPU usage".to_string());
1110 status.update_state(NodeState::Active, "CPU usage normalized".to_string());
1111
1112 assert_eq!(status.state, NodeState::Active);
1114 assert_eq!(status.state_history.len(), 4);
1115 assert_eq!(status.state_history.last().unwrap().0, NodeState::Active);
1116 }
1117
1118 #[test]
1119 fn test_node_status_staleness() {
1120 let addr = SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), 8080);
1121 let metadata = NodeMetadata::default();
1122 let status = NodeStatus::new(1, addr, metadata);
1123
1124 assert!(!status.is_stale(Duration::from_secs(60)));
1126
1127 let mut old_status = status;
1129 old_status.last_seen = SystemTime::now()
1130 .duration_since(UNIX_EPOCH)
1131 .expect("system time should be after UNIX_EPOCH")
1132 .as_secs()
1133 - 120; assert!(old_status.is_stale(Duration::from_secs(60)));
1137 }
1138
1139 #[test]
1140 fn test_resource_capacity_defaults() {
1141 let capacity = ResourceCapacity::default();
1142
1143 assert!(capacity.cpu_cores > 0);
1144 assert!(capacity.memory_bytes > 0);
1145 assert!(capacity.disk_bytes > 0);
1146 assert!(capacity.network_bandwidth > 0);
1147 assert!(capacity.max_connections > 0);
1148 }
1149
1150 #[test]
1151 fn test_cluster_health_operational() {
1152 assert!(ClusterHealth::Healthy.is_operational());
1153 assert!(ClusterHealth::Degraded.is_operational());
1154 assert!(ClusterHealth::Unstable.is_operational());
1155 assert!(!ClusterHealth::Critical.is_operational());
1156 }
1157}