Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
44 changes: 32 additions & 12 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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)
},
}
Expand Down Expand Up @@ -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);
Expand All @@ -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,
Expand All @@ -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();
Expand Down Expand Up @@ -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 {
Expand All @@ -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.
Expand All @@ -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();
Expand Down Expand Up @@ -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`].
Expand Down
56 changes: 45 additions & 11 deletions src/runtime.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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<JoinSet<()>>,
cancellable_background_tasks: Mutex<CancellableBackgroundTasks>,
background_processor_task: Mutex<Option<JoinHandle<()>>>,
background_processor_task: Mutex<Option<JoinHandle<Result<(), lightning::io::Error>>>>,
logger: Arc<Logger>,
}

Expand Down Expand Up @@ -156,7 +157,7 @@ impl Runtime {

pub fn spawn_background_processor_task<F>(&self, future: F)
where
F: Future<Output = ()> + Send + 'static,
F: Future<Output = Result<(), lightning::io::Error>> + 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");
Expand Down Expand Up @@ -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()
{
Expand All @@ -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) => {
Expand All @@ -275,6 +278,7 @@ impl Runtime {
},
}
}
Ok(())
}

#[cfg(tokio_unstable)]
Expand Down Expand Up @@ -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]
Expand Down
Loading