Skip to content

Commit 7fae0ec

Browse files
daywalker90cdecker
authored andcommitted
cln-plugin: fix missed-wakeup deadlock in Plugin::join and Plugin::shutdown
`Plugin::wait_handle` used a `tokio::sync::broadcast::Sender<()>` with its initial receiver immediately dropped. If `PluginDriver::run` exited or `Plugin::shutdown()` was called before the caller reached `Plugin::join()`, `broadcast::Sender::send(())` failed with zero receivers and dropped the signal; subsequent `Plugin::join()` calls then hung indefinitely because `Plugin` itself still held the `Sender`. In addition, `PluginDriver::run` never observed `wait_handle`, so `Plugin::shutdown()` did not stop the driver loop. Replace the broadcast channel with a `tokio::sync::watch::Sender<ShutdownState>` tracking `Running`, `ShuttingDown`, and `Stopped`: - `Plugin::shutdown()` transitions `Running` to `ShuttingDown`. - `PluginDriver::run` observes `ShuttingDown`, stops reading `input`, closes `receiver`, and drains any already-queued outgoing messages to `output` before exiting. - `ShutdownGuard` transitions the state to `Stopped` on driver exit (including unwinds), so `Plugin::join()` wakes only after queued outgoing messages have been delivered. Add unit tests covering `join()` after driver exit, `shutdown()` before `join()`, `shutdown()` waking a waiting `join()`, and draining queued outgoing messages before `join()` returns. Changelog-Fixed: cln-plugin: fix missed-wakeup deadlock in `Plugin::join()` and make `Plugin::shutdown()` cleanly stop the driver loop after draining queued outgoing messages.
1 parent ec7d197 commit 7fae0ec

1 file changed

Lines changed: 170 additions & 18 deletions

File tree

‎plugins/src/lib.rs‎

Lines changed: 170 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -125,6 +125,13 @@ where
125125
wildcard_subscription: Option<AsyncNotificationCallback<S>>,
126126
}
127127

128+
#[derive(Copy, Clone, Debug, PartialEq, Eq)]
129+
enum ShutdownState {
130+
Running,
131+
ShuttingDown,
132+
Stopped,
133+
}
134+
128135
#[derive(Clone)]
129136
pub struct Plugin<S>
130137
where
@@ -138,7 +145,7 @@ where
138145
/// "configuration" field of "init" message sent by cln
139146
configuration: Configuration,
140147
/// A signal that allows us to wait on the plugin's shutdown.
141-
wait_handle: tokio::sync::broadcast::Sender<()>,
148+
wait_handle: tokio::sync::watch::Sender<ShutdownState>,
142149

143150
sender: tokio::sync::mpsc::Sender<serde_json::Value>,
144151
}
@@ -799,7 +806,7 @@ where
799806
pub async fn start(mut self, state: S) -> Result<Plugin<S>, anyhow::Error> {
800807
let output = self.output;
801808
let input = self.input;
802-
let (wait_handle, _) = tokio::sync::broadcast::channel(1);
809+
let (wait_handle, _) = tokio::sync::watch::channel(ShutdownState::Running);
803810

804811
// An MPSC pair used by anything that needs to send messages
805812
// to the main daemon.
@@ -839,14 +846,18 @@ where
839846
let joiner = plugin.wait_handle.clone();
840847
// Start the PluginDriver to handle plugin IO
841848
tokio::spawn(async move {
849+
struct ShutdownGuard(tokio::sync::watch::Sender<ShutdownState>);
850+
impl Drop for ShutdownGuard {
851+
fn drop(&mut self) {
852+
self.0.send_replace(ShutdownState::Stopped);
853+
}
854+
}
855+
856+
let _keep_output = output.clone();
857+
let _guard = ShutdownGuard(joiner);
842858
if let Err(e) = driver.run(receiver, input, output).await {
843859
log::warn!("Plugin loop returned error {:?}", e);
844860
}
845-
846-
// Now that we have left the reader loop its time to
847-
// notify any waiting tasks. This most likely will cause
848-
// the main task to exit and the plugin to terminate.
849-
joiner.send(())
850861
});
851862
Ok(plugin)
852863
}
@@ -932,12 +943,21 @@ where
932943
I: Send + AsyncReadExt + Unpin,
933944
O: Send + AsyncWriteExt + Unpin,
934945
{
946+
let mut shutdown_rx = self.plugin.wait_handle.subscribe();
935947
loop {
948+
if *shutdown_rx.borrow_and_update() != ShutdownState::Running {
949+
break;
950+
}
936951
// If we encounter any error reading or writing from/to
937952
// the master we hand them up, so we can return control to
938953
// the user-code, which may require some cleanups or
939954
// similar.
940955
tokio::select! {
956+
res = shutdown_rx.changed() => {
957+
if res.is_err() || *shutdown_rx.borrow_and_update() != ShutdownState::Running {
958+
break;
959+
}
960+
}
941961
msg = input.next() => {
942962
if let Some(reply) = self.dispatch_message(msg, &self.plugin)? {
943963
output.lock().await.send(reply).await?;
@@ -950,6 +970,12 @@ where
950970
},
951971
}
952972
}
973+
974+
receiver.close();
975+
while let Some(v) = receiver.recv().await {
976+
output.lock().await.send(v).await?;
977+
}
978+
Ok(())
953979
}
954980

955981
/// Dispatch one decoded message. Returns an optional immediate reply
@@ -1280,16 +1306,22 @@ where
12801306
pub async fn join(&self) -> Result<(), Error> {
12811307
self.wait_handle
12821308
.subscribe()
1283-
.recv()
1309+
.wait_for(|&state| state == ShutdownState::Stopped)
12841310
.await
1285-
.context("error waiting for shutdown")
1311+
.context("error waiting for shutdown")?;
1312+
Ok(())
12861313
}
12871314

12881315
/// Request plugin shutdown
12891316
pub fn shutdown(&self) -> Result<(), Error> {
1290-
self.wait_handle
1291-
.send(())
1292-
.context("error waiting for shutdown")?;
1317+
self.wait_handle.send_if_modified(|state| {
1318+
if *state == ShutdownState::Running {
1319+
*state = ShutdownState::ShuttingDown;
1320+
true
1321+
} else {
1322+
false
1323+
}
1324+
});
12931325
Ok(())
12941326
}
12951327
}
@@ -1410,7 +1442,7 @@ mod test {
14101442
let (mut client_write, server_read) = tokio::io::duplex(1024);
14111443
let mut framed_in = FramedRead::new(server_read, JsonRpcCodec::default());
14121444
let (sender, mut receiver) = tokio::sync::mpsc::channel(4);
1413-
let (wait_handle, _) = tokio::sync::broadcast::channel(1);
1445+
let (wait_handle, _) = tokio::sync::watch::channel(ShutdownState::Running);
14141446

14151447
let plugin = Plugin {
14161448
state: (),
@@ -1455,7 +1487,7 @@ mod test {
14551487
let (mut client_write, server_read) = tokio::io::duplex(1024);
14561488
let mut framed_in = FramedRead::new(server_read, JsonRpcCodec::default());
14571489
let (sender, mut receiver) = tokio::sync::mpsc::channel(4);
1458-
let (wait_handle, _) = tokio::sync::broadcast::channel(1);
1490+
let (wait_handle, _) = tokio::sync::watch::channel(ShutdownState::Running);
14591491

14601492
let plugin = Plugin {
14611493
state: (),
@@ -1527,7 +1559,7 @@ mod test {
15271559
let (mut client_write, server_read) = tokio::io::duplex(1024);
15281560
let mut framed_in = FramedRead::new(server_read, JsonRpcCodec::default());
15291561
let (sender, mut receiver) = tokio::sync::mpsc::channel(4);
1530-
let (wait_handle, _) = tokio::sync::broadcast::channel(1);
1562+
let (wait_handle, _) = tokio::sync::watch::channel(ShutdownState::Running);
15311563

15321564
let plugin = Plugin {
15331565
state: (),
@@ -1570,7 +1602,7 @@ mod test {
15701602
let (mut client_write, server_read) = tokio::io::duplex(1024);
15711603
let mut framed_in = FramedRead::new(server_read, JsonRpcCodec::default());
15721604
let (sender, mut receiver) = tokio::sync::mpsc::channel(4);
1573-
let (wait_handle, _) = tokio::sync::broadcast::channel(1);
1605+
let (wait_handle, _) = tokio::sync::watch::channel(ShutdownState::Running);
15741606

15751607
let plugin = Plugin {
15761608
state: (),
@@ -1615,7 +1647,7 @@ mod test {
16151647
let (mut client_write, server_read) = tokio::io::duplex(1024);
16161648
let mut framed_in = FramedRead::new(server_read, JsonRpcCodec::default());
16171649
let (sender, mut receiver) = tokio::sync::mpsc::channel(4);
1618-
let (wait_handle, _) = tokio::sync::broadcast::channel(1);
1650+
let (wait_handle, _) = tokio::sync::watch::channel(ShutdownState::Running);
16191651

16201652
let plugin = Plugin {
16211653
state: (),
@@ -1790,7 +1822,7 @@ mod test {
17901822
let mut master_read = FramedRead::new(master_read, JsonCodec::default());
17911823

17921824
let (sender, receiver) = tokio::sync::mpsc::channel(4);
1793-
let (wait_handle, _) = tokio::sync::broadcast::channel(1);
1825+
let (wait_handle, _) = tokio::sync::watch::channel(ShutdownState::Running);
17941826

17951827
let plugin = Plugin {
17961828
state: (),
@@ -1875,4 +1907,124 @@ mod test {
18751907
drop(master_write);
18761908
let _ = driver_handle.await.unwrap();
18771909
}
1910+
1911+
async fn start_test_plugin() -> (
1912+
Plugin<()>,
1913+
tokio::io::DuplexStream,
1914+
FramedRead<tokio::io::DuplexStream, JsonCodec>,
1915+
) {
1916+
let (mut master_write, plugin_read) = tokio::io::duplex(4096);
1917+
let (plugin_write, master_read) = tokio::io::duplex(4096);
1918+
let mut master_read = FramedRead::new(master_read, JsonCodec::default());
1919+
1920+
let start_fut = Builder::new(plugin_read, plugin_write)
1921+
.with_logging(false)
1922+
.start(());
1923+
1924+
let handshake_fut = async {
1925+
master_write
1926+
.write_all(
1927+
b"{\"jsonrpc\":\"2.0\",\"id\":1,\"method\":\"getmanifest\",\"params\":{}}\n\n",
1928+
)
1929+
.await
1930+
.unwrap();
1931+
let manifest_resp = master_read.next().await.unwrap().unwrap().unwrap();
1932+
assert_eq!(manifest_resp["id"], 1);
1933+
1934+
master_write
1935+
.write_all(
1936+
concat!(
1937+
"{\"jsonrpc\":\"2.0\",\"id\":2,\"method\":\"init\",\"params\":{",
1938+
"\"options\":{},",
1939+
"\"configuration\":{",
1940+
"\"lightning-dir\":\"/tmp\",",
1941+
"\"rpc-file\":\"lightning-rpc\",",
1942+
"\"startup\":true,",
1943+
"\"network\":\"regtest\",",
1944+
"\"feature_set\":{}",
1945+
"}}}\n\n"
1946+
)
1947+
.as_bytes(),
1948+
)
1949+
.await
1950+
.unwrap();
1951+
let init_resp = master_read.next().await.unwrap().unwrap().unwrap();
1952+
assert_eq!(init_resp["id"], 2);
1953+
};
1954+
1955+
let (plugin, ()) = tokio::join!(start_fut, handshake_fut);
1956+
(plugin.unwrap().unwrap(), master_write, master_read)
1957+
}
1958+
1959+
#[tokio::test]
1960+
async fn test_join_after_driver_exits_does_not_hang() {
1961+
let (plugin, master_write, mut master_read) = start_test_plugin().await;
1962+
1963+
drop(master_write);
1964+
assert!(master_read.next().await.is_none());
1965+
1966+
assert!(plugin.join().now_or_never().is_some_and(|r| r.is_ok()));
1967+
}
1968+
1969+
#[tokio::test]
1970+
async fn test_shutdown_before_join_stops_driver_and_wakes_join() {
1971+
let (plugin, _master_write, mut master_read) = start_test_plugin().await;
1972+
1973+
plugin.shutdown().unwrap();
1974+
assert!(master_read.next().await.is_none());
1975+
1976+
assert!(plugin.join().now_or_never().is_some_and(|r| r.is_ok()));
1977+
// Repeated join/shutdown calls stay idempotent after shutdown.
1978+
assert!(plugin.join().now_or_never().is_some_and(|r| r.is_ok()));
1979+
plugin.shutdown().unwrap();
1980+
}
1981+
1982+
#[tokio::test]
1983+
async fn test_shutdown_wakes_waiting_join() {
1984+
let (plugin, _master_write, mut master_read) = start_test_plugin().await;
1985+
1986+
let join_plugin = plugin.clone();
1987+
let join_task = tokio::spawn(async move { join_plugin.join().await });
1988+
tokio::task::yield_now().await;
1989+
1990+
plugin.shutdown().unwrap();
1991+
join_task.await.unwrap().unwrap();
1992+
assert!(master_read.next().await.is_none());
1993+
}
1994+
1995+
#[tokio::test]
1996+
async fn test_shutdown_drains_queued_messages_before_join_returns() {
1997+
let (plugin, _master_write, mut master_read) = start_test_plugin().await;
1998+
1999+
// Fill output beyond the 4096-byte duplex buffer so draining blocks
2000+
// until master_read consumes the queued notifications.
2001+
let large_payload = "x".repeat(6000);
2002+
plugin
2003+
.send_custom_notification("bye".to_string(), json!({"seq": 1}))
2004+
.await
2005+
.unwrap();
2006+
plugin
2007+
.send_custom_notification("bye".to_string(), json!({"seq": 2, "pad": large_payload}))
2008+
.await
2009+
.unwrap();
2010+
plugin.shutdown().unwrap();
2011+
2012+
let join_plugin = plugin.clone();
2013+
let join_task = tokio::spawn(async move { join_plugin.join().await });
2014+
for _ in 0..5 {
2015+
tokio::task::yield_now().await;
2016+
}
2017+
assert!(!join_task.is_finished());
2018+
2019+
let first = master_read.next().await.unwrap().unwrap().unwrap();
2020+
assert_eq!(first["method"], "bye");
2021+
assert_eq!(first["params"]["bye"]["seq"], 1);
2022+
2023+
let second = master_read.next().await.unwrap().unwrap().unwrap();
2024+
assert_eq!(second["method"], "bye");
2025+
assert_eq!(second["params"]["bye"]["seq"], 2);
2026+
2027+
assert!(master_read.next().await.is_none());
2028+
join_task.await.unwrap().unwrap();
2029+
}
18782030
}

0 commit comments

Comments
 (0)