Skip to main content

oxirs_cluster/
node_lifecycle.rs

1//! # Node Lifecycle Management
2//!
3//! Advanced node lifecycle management with graceful addition/removal,
4//! health monitoring, and automated recovery for distributed clusters.
5
6use 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/// Node lifecycle state
22#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
23pub enum NodeState {
24    /// Node is starting up
25    Starting,
26    /// Node is healthy and operational
27    Active,
28    /// Node is experiencing issues but still operational
29    Degraded,
30    /// Node is temporarily unavailable
31    Suspended,
32    /// Node is being drained for maintenance
33    Draining,
34    /// Node is gracefully leaving the cluster
35    Leaving,
36    /// Node has left the cluster
37    Left,
38    /// Node is unresponsive
39    Failed,
40    /// Node is suspected to be Byzantine
41    Suspected,
42}
43
44impl NodeState {
45    /// Check if node is operational (can handle requests)
46    pub fn is_operational(self) -> bool {
47        matches!(self, NodeState::Active | NodeState::Degraded)
48    }
49
50    /// Check if node should be included in consensus
51    pub fn is_consensus_eligible(self) -> bool {
52        matches!(
53            self,
54            NodeState::Active | NodeState::Degraded | NodeState::Draining
55        )
56    }
57
58    /// Check if node is healthy
59    pub fn is_healthy(self) -> bool {
60        matches!(self, NodeState::Active)
61    }
62}
63
64/// Node lifecycle events
65#[derive(Debug, Clone, Serialize, Deserialize)]
66pub enum LifecycleEvent {
67    /// Node is joining the cluster
68    NodeJoining {
69        node_id: OxirsNodeId,
70        address: SocketAddr,
71        metadata: NodeMetadata,
72    },
73    /// Node has successfully joined
74    NodeJoined {
75        node_id: OxirsNodeId,
76        timestamp: u64,
77    },
78    /// Node state has changed
79    NodeStateChanged {
80        node_id: OxirsNodeId,
81        old_state: NodeState,
82        new_state: NodeState,
83        reason: String,
84        timestamp: u64,
85    },
86    /// Node is leaving the cluster
87    NodeLeaving {
88        node_id: OxirsNodeId,
89        reason: String,
90        graceful: bool,
91    },
92    /// Node has left the cluster
93    NodeLeft {
94        node_id: OxirsNodeId,
95        timestamp: u64,
96    },
97    /// Node was forcibly evicted
98    NodeEvicted {
99        node_id: OxirsNodeId,
100        reason: String,
101        timestamp: u64,
102    },
103    /// Cluster membership has changed
104    MembershipChanged {
105        added_nodes: Vec<OxirsNodeId>,
106        removed_nodes: Vec<OxirsNodeId>,
107        timestamp: u64,
108    },
109}
110
111/// Node metadata for join operations
112#[derive(Debug, Clone, Serialize, Deserialize)]
113pub struct NodeMetadata {
114    /// Node's advertised capabilities
115    pub capabilities: Vec<String>,
116    /// Node's data center or region
117    pub datacenter: Option<String>,
118    /// Node's rack identifier
119    pub rack: Option<String>,
120    /// Node's version information
121    pub version: String,
122    /// Custom tags for node identification
123    pub tags: HashMap<String, String>,
124    /// Node's resource capacity
125    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/// Resource capacity information
142#[derive(Debug, Clone, Serialize, Deserialize)]
143pub struct ResourceCapacity {
144    /// Maximum CPU cores available
145    pub cpu_cores: u32,
146    /// Maximum memory in bytes
147    pub memory_bytes: u64,
148    /// Maximum disk space in bytes
149    pub disk_bytes: u64,
150    /// Maximum network bandwidth in bytes/sec
151    pub network_bandwidth: u64,
152    /// Maximum concurrent connections
153    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, // 8GB default
163            disk_bytes: 100 * 1024 * 1024 * 1024, // 100GB default
164            network_bandwidth: 1_000_000_000,     // 1Gbps default
165            max_connections: 10000,
166        }
167    }
168}
169
170/// Node lifecycle configuration
171#[derive(Debug, Clone, Serialize, Deserialize)]
172pub struct LifecycleConfig {
173    /// Health check interval
174    pub health_check_interval: Duration,
175    /// Node failure detection timeout
176    pub failure_timeout: Duration,
177    /// Maximum time for graceful shutdown
178    pub graceful_shutdown_timeout: Duration,
179    /// Time to wait before removing failed nodes
180    pub removal_grace_period: Duration,
181    /// Enable automatic failure detection
182    pub enable_auto_failure_detection: bool,
183    /// Enable automatic recovery
184    pub enable_auto_recovery: bool,
185    /// Minimum cluster size before blocking operations
186    pub min_cluster_size: usize,
187    /// Maximum time for node join operations
188    pub join_timeout: Duration,
189    /// Enable Byzantine behavior detection
190    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/// Node status information
210#[derive(Debug, Clone, Serialize, Deserialize)]
211pub struct NodeStatus {
212    /// Node identifier
213    pub node_id: OxirsNodeId,
214    /// Current state
215    pub state: NodeState,
216    /// Node address
217    pub address: SocketAddr,
218    /// Node metadata
219    pub metadata: NodeMetadata,
220    /// Last seen timestamp
221    pub last_seen: u64,
222    /// Health information
223    pub health: NodeHealth,
224    /// Join timestamp
225    pub joined_at: u64,
226    /// State transition history (last 10 transitions)
227    pub state_history: Vec<(NodeState, u64, String)>,
228    /// Performance metrics
229    pub performance_score: f64,
230    /// Failure count since last successful operation
231    pub failure_count: u32,
232}
233
234impl NodeStatus {
235    /// Create new node status
236    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    /// Update node state
257    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        // Add to history
264        self.state_history.push((new_state, now, reason));
265
266        // Keep only last 10 transitions
267        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        // Reset failure count on successful state transitions
275        if matches!(new_state, NodeState::Active) {
276            self.failure_count = 0;
277        }
278    }
279
280    /// Update health information
281    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        // Calculate performance score based on health metrics
289        self.performance_score = self.calculate_performance_score();
290    }
291
292    /// Calculate performance score (0.0 to 1.0)
293    fn calculate_performance_score(&self) -> f64 {
294        let mut score: f64 = 1.0;
295
296        // Factor in CPU usage (high usage reduces score)
297        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        // Factor in memory usage
304        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        // Factor in response time
311        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        // Factor in failure count
318        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    /// Check if node has been inactive too long
328    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    /// Record a failure
337    pub fn record_failure(&mut self) {
338        self.failure_count += 1;
339        self.performance_score = self.calculate_performance_score();
340    }
341}
342
343/// Node lifecycle manager
344pub struct NodeLifecycleManager {
345    /// Local node ID
346    local_node_id: OxirsNodeId,
347    /// Configuration
348    config: LifecycleConfig,
349    /// Consensus manager
350    consensus: Arc<ConsensusManager>,
351    /// Discovery service
352    discovery: Arc<DiscoveryService>,
353    /// Health monitor
354    health_monitor: Arc<HealthMonitor>,
355    /// Replication manager
356    replication: Arc<ReplicationManager>,
357    /// Node status map
358    node_status: Arc<RwLock<HashMap<OxirsNodeId, NodeStatus>>>,
359    /// Event listeners
360    event_listeners: Arc<RwLock<Vec<tokio::sync::mpsc::UnboundedSender<LifecycleEvent>>>>,
361    /// Background task handle
362    task_handle: Arc<Mutex<Option<tokio::task::JoinHandle<()>>>>,
363}
364
365impl NodeLifecycleManager {
366    /// Create new node lifecycle manager
367    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    /// Start the lifecycle manager
389    pub async fn start(&self) -> Result<()> {
390        info!(
391            "Starting node lifecycle manager for node {}",
392            self.local_node_id
393        );
394
395        // Start background monitoring task
396        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    /// Stop the lifecycle manager
410    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    /// Add a node to the cluster
422    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        // Check if node already exists
431        {
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        // Create node status
441        let node_status = NodeStatus::new(node_id, address, metadata.clone());
442
443        // Emit joining event
444        self.emit_event(LifecycleEvent::NodeJoining {
445            node_id,
446            address,
447            metadata,
448        })
449        .await;
450
451        // Perform join process with timeout
452        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                // Emit joined event
463                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    /// Perform the actual node join process
488    async fn perform_node_join(
489        &self,
490        node_id: OxirsNodeId,
491        address: SocketAddr,
492        mut node_status: NodeStatus,
493    ) -> Result<()> {
494        // Note: The following operations are placeholders for future implementation.
495        // When the underlying components (ConsensusManager, DiscoveryService, ReplicationManager)
496        // expose APIs with interior mutability (e.g., async methods taking &self instead of &mut self),
497        // these calls can be uncommented. This is an architectural decision to maintain
498        // immutability at the lifecycle manager level while allowing the underlying
499        // components to manage their own state mutations internally.
500        //
501        // Proposed future APIs:
502        // - self.consensus.add_peer(node_id).await?;
503        // - self.discovery.add_node(node_info).await?;
504        // - self.replication.add_replica(node_id, address.to_string()).await?;
505
506        // Update node state to active
507        node_status.update_state(NodeState::Active, "Successfully joined cluster".to_string());
508
509        // Store node status
510        {
511            let mut nodes = self.node_status.write().await;
512            nodes.insert(node_id, node_status);
513        }
514
515        // Start health monitoring for the new node
516        self.health_monitor
517            .start_monitoring(node_id, address.to_string())
518            .await;
519
520        Ok(())
521    }
522
523    /// Clean up after a failed join
524    async fn cleanup_failed_join(&self, node_id: OxirsNodeId) {
525        warn!("Cleaning up failed join for node {}", node_id);
526
527        // Note: Placeholder for future component cleanup operations.
528        // See note in finalize_join() for details on interior mutability requirements.
529        //
530        // Proposed future cleanup APIs:
531        // - self.consensus.remove_peer(node_id).await?;
532        // - self.discovery.remove_node(node_id).await?;
533        // - self.replication.remove_replica(node_id).await?;
534
535        // Remove from status map
536        let mut nodes = self.node_status.write().await;
537        nodes.remove(&node_id);
538    }
539
540    /// Remove a node from the cluster
541    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        // Check if node exists
548        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        // Emit leaving event
558        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            // Perform graceful removal
572            self.perform_graceful_removal(node_id).await?;
573        } else {
574            // Perform immediate removal
575            self.perform_immediate_removal(node_id).await?;
576        }
577
578        // Emit left event
579        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    /// Perform graceful node removal
593    async fn perform_graceful_removal(&self, node_id: OxirsNodeId) -> Result<()> {
594        // Update node state to draining
595        {
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        // Wait for ongoing operations to complete
606        tokio::time::sleep(Duration::from_secs(5)).await;
607
608        // Perform actual removal
609        self.perform_immediate_removal(node_id).await
610    }
611
612    /// Perform immediate node removal
613    async fn perform_immediate_removal(&self, node_id: OxirsNodeId) -> Result<()> {
614        // Note: Placeholder for future component removal operations.
615        // See note in finalize_join() for details on interior mutability requirements.
616        //
617        // Proposed future removal APIs:
618        // - self.consensus.remove_peer(node_id).await?;
619        // - self.discovery.remove_node(node_id).await?;
620        // - self.replication.remove_replica(node_id).await?;
621
622        // Stop health monitoring
623        self.health_monitor.stop_monitoring(node_id).await;
624
625        // Update node state to left
626        {
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        // Remove from status map after a delay (for audit purposes)
634        let nodes = Arc::clone(&self.node_status);
635        tokio::spawn(async move {
636            tokio::time::sleep(Duration::from_secs(300)).await; // 5 minutes
637            let mut nodes = nodes.write().await;
638            nodes.remove(&node_id);
639        });
640
641        Ok(())
642    }
643
644    /// Force evict a non-responsive node
645    pub async fn force_evict_node(&self, node_id: OxirsNodeId, reason: String) -> Result<()> {
646        warn!("Force evicting node {}: {}", node_id, reason);
647
648        // Update node state to failed
649        {
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        // Emit eviction event
657        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        // Perform removal
668        self.perform_immediate_removal(node_id).await?;
669
670        info!("Successfully evicted node {}", node_id);
671        Ok(())
672    }
673
674    /// Get node status
675    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    /// Get all node statuses
681    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    /// Get healthy nodes
687    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    /// Get operational nodes
697    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    /// Check cluster health
707    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    /// Background monitoring loop
745    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    /// Perform health check on all nodes
770    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                    // Update state based on health
785                    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 // Keep current state
795                    };
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                        // Emit state change event
803                        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    /// Detect and handle node failures
823    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            // Update state to failed
842            {
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                    // Emit state change event
851                    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            // Auto-recovery if enabled
866            if self.config.enable_auto_recovery {
867                // Wait for grace period before removal
868                let manager = self.clone();
869                tokio::spawn(async move {
870                    tokio::time::sleep(manager.config.removal_grace_period).await;
871
872                    // Check if node is still failed
873                    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    /// Detect Byzantine behavior
891    async fn detect_byzantine_behavior(&self) -> Result<()> {
892        // This is a simplified Byzantine detection
893        // In a production system, this would analyze message patterns,
894        // voting behavior, and other consensus-related metrics
895
896        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 || // High failure count
904                    status.performance_score < 0.2 // Very low performance
905                })
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            // Update state to suspected
914            {
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                    // Emit state change event
924                    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            // Consider eviction based on severity
939            // This would need more sophisticated analysis in production
940        }
941
942        Ok(())
943    }
944
945    /// Emit a lifecycle event
946    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                // Listener disconnected, will be cleaned up later
951            }
952        }
953    }
954
955    /// Subscribe to lifecycle events
956    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    /// Transfer leadership before graceful shutdown
964    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            // Transfer to specific node
969            self.consensus
970                .transfer_leadership(target)
971                .await
972                .map_err(|e| ClusterError::Other(format!("Leadership transfer failed: {e}")))?;
973        } else {
974            // Let consensus layer choose the best candidate
975            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    /// Graceful shutdown of local node
993    pub async fn graceful_shutdown(&self) -> Result<()> {
994        info!("Initiating graceful shutdown of local node");
995
996        // Transfer leadership if we're the leader
997        if self.consensus.is_leader().await {
998            self.transfer_leadership(None).await?;
999        }
1000
1001        // Remove ourselves from the cluster
1002        self.remove_node(self.local_node_id, true).await?;
1003
1004        // Stop the lifecycle manager
1005        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/// Cluster health status
1029#[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/// Overall cluster health
1041#[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        // Initially should have good performance score
1082        assert!(status.performance_score > 0.8);
1083
1084        // Record failures should decrease score
1085        status.record_failure();
1086        status.record_failure();
1087        status.record_failure();
1088        assert!(status.performance_score < 0.9);
1089
1090        // High failure count should significantly decrease score
1091        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        // Should start with Starting state
1104        assert_eq!(status.state, NodeState::Starting);
1105        assert_eq!(status.state_history.len(), 1);
1106
1107        // Update state multiple times
1108        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        // Should track history
1113        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        // Should not be stale immediately
1125        assert!(!status.is_stale(Duration::from_secs(60)));
1126
1127        // Create an old status
1128        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; // 2 minutes ago
1134
1135        // Should be stale with 1 minute timeout
1136        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}