diff --git a/src/connection.rs b/src/connection.rs index 70013cbb29..9eef8f7765 100644 --- a/src/connection.rs +++ b/src/connection.rs @@ -7,6 +7,7 @@ use std::collections::hash_map::{self, HashMap}; use std::ops::Deref; +use std::sync::atomic::{AtomicBool, Ordering}; use std::sync::{Arc, Mutex}; use std::time::Duration; @@ -57,7 +58,7 @@ where { pending_connections: PendingConnections, peer_manager: Arc, - disable_lightning_connections: bool, + connections_disabled: AtomicBool, tor_proxy_config: Option, keys_manager: Arc, logger: L, @@ -76,7 +77,7 @@ where Self { pending_connections, peer_manager, - disable_lightning_connections, + connections_disabled: AtomicBool::new(disable_lightning_connections), tor_proxy_config, keys_manager, logger, @@ -93,6 +94,16 @@ where self.do_connect_peer(node_id, addr).await } + /// Refuses any further peer connections and disconnects all connected peers. + pub(crate) fn disable_connections(&self) { + self.connections_disabled.store(true, Ordering::Release); + self.peer_manager.disconnect_all_peers(); + } + + pub(crate) fn connections_disabled(&self) -> bool { + self.connections_disabled.load(Ordering::Acquire) + } + pub(crate) fn disconnect_peer(&self, node_id: PublicKey) { self.peer_manager.disconnect_by_node_id(node_id); } @@ -123,7 +134,7 @@ where async fn do_connect_peer_internal( &self, node_id: PublicKey, addr: SocketAddress, ) -> Result<(), Error> { - if self.disable_lightning_connections { + if self.connections_disabled() { log_warn!(self.logger, "Lightning peer connections are disabled."); return Err(Error::ConnectionFailed); } diff --git a/src/lib.rs b/src/lib.rs index ed8b35ff61..fc40f1f60a 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -318,7 +318,7 @@ impl Node { // Startup spawns background tasks before it can fail, e.g., when binding our // listening addresses. Wind them all back down rather than leaving them running // behind a node that never came up. - self.shutdown(); + let _ = self.shutdown(); Err(e) }, } @@ -551,6 +551,7 @@ impl Node { for listener in listeners { let logger = Arc::clone(&listening_logger); let peer_mgr = Arc::clone(&peer_manager_connection_handler); + let listen_cm = Arc::clone(&self.connection_manager); let mut stop_listen = self.stop_sender.subscribe(); let runtime = Arc::clone(&self.runtime); self.runtime.spawn_cancellable_background_task(async move { @@ -571,6 +572,9 @@ impl Node { continue; }, }; + if listen_cm.connections_disabled() { + continue; + } let peer_mgr = Arc::clone(&peer_mgr); let logger = Arc::clone(&logger); runtime.spawn_cancellable_background_task(async move { @@ -816,6 +820,7 @@ impl Node { let background_onion_messenger = Arc::clone(&self.onion_messenger); let background_logger = Arc::clone(&self.logger); let background_error_logger = Arc::clone(&self.logger); + let background_failure_cm = Arc::clone(&self.connection_manager); let background_scorer = Arc::clone(&self.scorer); let stop_bp = self.background_processor_stop_sender.subscribe(); let sleeper_logger = Arc::clone(&self.logger); @@ -839,7 +844,7 @@ impl Node { }; self.runtime.spawn_background_processor_task(async move { - process_events_async( + let res = process_events_async( background_persister, |e| background_event_handler.handle_event(e), background_chain_mon, @@ -861,11 +866,18 @@ impl Node { ) }, ) - .await - .unwrap_or_else(|e| { - log_error!(background_error_logger, "Failed to process events: {}", e); - panic!("Failed to process events"); - }); + .await; + + if let Err(e) = &res { + log_error!( + background_error_logger, + "Background processing of events failed, disconnecting all peers: {}", + e + ); + background_failure_cm.disable_connections(); + } + + res }); let mut stop_liquidity_handler = self.stop_sender.subscribe(); @@ -968,6 +980,9 @@ impl Node { /// Disconnects all peers, stops all running background tasks, and shuts down [`Node`]. /// /// After this returns most API methods will return [`Error::NotRunning`]. + /// + /// Returns [`Error::PersistenceFailed`] if background event processing failed. The node is + /// shut down regardless. pub fn stop(&self) -> Result<(), Error> { let mut is_running_lock = self.is_running.write().expect("lock"); if !*is_running_lock { @@ -976,11 +991,16 @@ impl Node { log_info!(self.logger, "Shutting down LDK Node with node ID {}...", self.node_id()); - self.shutdown(); + let shutdown_res = self.shutdown(); - log_info!(self.logger, "Shutdown complete."); *is_running_lock = false; - Ok(()) + match shutdown_res { + Ok(()) => log_info!(self.logger, "Shutdown complete."), + Err(_) => { + log_error!(self.logger, "Shutdown complete, but background processing failed.") + }, + } + shutdown_res } /// Winds down everything [`Node::start_inner`] may have brought up. @@ -989,7 +1009,7 @@ impl Node { /// also used to clean up after a [`Node::start`] that failed part-way through, in which case /// some of the background tasks below were never spawned and the shutdown signals accordingly /// find no receivers. - fn shutdown(&self) { + fn shutdown(&self) -> Result<(), Error> { // Prevent blocking Electrum syncs from making any further callbacks before persistence // tasks stop accepting work. self.chain_source.begin_shutdown(); @@ -1021,10 +1041,12 @@ impl Node { } // Finally, wait until background processing stopped, at least until a timeout is reached. - self.runtime.wait_on_background_processor_task(); + let background_processor_res = self.runtime.wait_on_background_processor_task(); #[cfg(tokio_unstable)] self.runtime.log_metrics(); + + background_processor_res } /// Returns the status of the [`Node`]. diff --git a/src/runtime.rs b/src/runtime.rs index 8f9e94ccf3..289933618f 100644 --- a/src/runtime.rs +++ b/src/runtime.rs @@ -19,13 +19,14 @@ use tokio_util::task::TaskTracker; use crate::config::{ BACKGROUND_TASK_SHUTDOWN_TIMEOUT_SECS, LDK_EVENT_HANDLER_SHUTDOWN_TIMEOUT_SECS, }; +use crate::error::Error; use crate::logger::{log_debug, log_error, log_trace, LdkLogger, Logger}; pub(crate) struct Runtime { mode: RuntimeMode, background_tasks: Mutex>, cancellable_background_tasks: Mutex, - background_processor_task: Mutex>>, + background_processor_task: Mutex>>>, logger: Arc, } @@ -156,7 +157,7 @@ impl Runtime { pub fn spawn_background_processor_task(&self, future: F) where - F: Future + Send + 'static, + F: Future> + Send + 'static, { let mut background_processor_task = self.background_processor_task.lock().expect("lock"); debug_assert!(background_processor_task.is_none(), "Expected no background processor_task"); @@ -238,7 +239,9 @@ impl Runtime { /// /// Note this may find no task at all, as it's also reached when winding down a startup that /// failed before spawning it. - pub fn wait_on_background_processor_task(&self) { + /// + /// Returns [`Error::PersistenceFailed`] if the task failed or panicked. + pub fn wait_on_background_processor_task(&self) -> Result<(), Error> { if let Some(background_processor_task) = self.background_processor_task.lock().expect("lock").take() { @@ -256,17 +259,17 @@ impl Runtime { match timeout_res { Ok(stop_res) => match stop_res { - Ok(()) => { + Ok(Ok(())) => { log_debug!(self.logger, "Stopped background processing of events."); }, + Ok(Err(e)) => { + log_error!(self.logger, "Background processing of events failed: {}", e); + return Err(Error::PersistenceFailed); + }, Err(e) => { abort_handle.abort(); - log_error!( - self.logger, - "Stopping event handling failed. This should never happen: {}", - e - ); - panic!("Stopping event handling failed. This should never happen."); + log_error!(self.logger, "Background processing of events panicked: {}", e); + return Err(Error::PersistenceFailed); }, }, Err(e) => { @@ -275,6 +278,7 @@ impl Runtime { }, } } + Ok(()) } #[cfg(tokio_unstable)] @@ -474,7 +478,37 @@ mod tests { let runtime = test_runtime(); runtime.abort_cancellable_background_tasks(); runtime.wait_on_background_tasks(); - runtime.wait_on_background_processor_task(); + assert!(runtime.wait_on_background_processor_task().is_ok()); + } + + #[test] + fn background_processor_success_is_reported_as_ok() { + let runtime = test_runtime(); + runtime.spawn_background_processor_task(async { Ok(()) }); + assert!(runtime.wait_on_background_processor_task().is_ok()); + } + + #[test] + fn background_processor_error_is_returned_instead_of_panicking() { + let runtime = test_runtime(); + runtime.spawn_background_processor_task(async { + Err(lightning::io::Error::new(lightning::io::ErrorKind::Other, "persist failed")) + }); + assert!(matches!( + runtime.wait_on_background_processor_task(), + Err(Error::PersistenceFailed) + )); + assert!(runtime.wait_on_background_processor_task().is_ok()); + } + + #[test] + fn background_processor_panic_is_returned_instead_of_propagated() { + let runtime = test_runtime(); + runtime.spawn_background_processor_task(async { panic!("background processor panicked") }); + assert!(matches!( + runtime.wait_on_background_processor_task(), + Err(Error::PersistenceFailed) + )); } #[test]