diff --git a/src/lib.rs b/src/lib.rs index ed8b35ff61..bb2fc24b1e 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) }, } @@ -816,6 +816,8 @@ 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_stop_sender = self.stop_sender.clone(); + let background_failure_peer_man = Arc::clone(&self.peer_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 +841,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 +863,19 @@ 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, halting node activity: {}", + e + ); + let _ = background_failure_stop_sender.send(()); + background_failure_peer_man.disconnect_all_peers(); + } + + res }); let mut stop_liquidity_handler = self.stop_sender.subscribe(); @@ -968,6 +978,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 +989,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 +1007,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 +1039,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]