wallet: wait for listeners before treating connect refusal as an error #155
4 changed files with 455 additions and 61 deletions
|
|
@ -48,6 +48,10 @@ env var:
|
||||||
- **`monerod`** is spawned when the chain source is *local*:
|
- **`monerod`** is spawned when the chain source is *local*:
|
||||||
`--non-interactive --data-dir <datadir> --rpc-bind-ip 127.0.0.1 --rpc-bind-port
|
`--non-interactive --data-dir <datadir> --rpc-bind-ip 127.0.0.1 --rpc-bind-port
|
||||||
18081`. The wallet child dials `127.0.0.1:18081`.
|
18081`. The wallet child dials `127.0.0.1:18081`.
|
||||||
|
- **Start waits up to 5s for `127.0.0.1:18081` to accept before spawning
|
||||||
|
`monero-wallet-rpc`, and up to 5s for that child's own port before
|
||||||
|
`open_wallet`.** A closed port fails the start. A connect refusal while state is
|
||||||
|
still `connecting` is not shown as an error.
|
||||||
- **`arti`** is spawned as a SOCKS child only when the chain source is a
|
- **`arti`** is spawned as a SOCKS child only when the chain source is a
|
||||||
`.onion` daemon: `arti proxy -p <port>`.
|
`.onion` daemon: `arti proxy -p <port>`.
|
||||||
- `--trusted-daemon` is never passed.
|
- `--trusted-daemon` is never passed.
|
||||||
|
|
|
||||||
250
src/node.rs
250
src/node.rs
|
|
@ -1014,7 +1014,8 @@ impl Node {
|
||||||
self.child_height.store(height, Ordering::Relaxed);
|
self.child_height.store(height, Ordering::Relaxed);
|
||||||
self.child_target.store(target_height, Ordering::Relaxed);
|
self.child_target.store(target_height, Ordering::Relaxed);
|
||||||
if let Ok(mut slot) = self.child_error.lock() {
|
if let Ok(mut slot) = self.child_error.lock() {
|
||||||
*slot = if connected { None } else { error };
|
let previous = slot.clone();
|
||||||
|
*slot = probe_error(connected, error, previous);
|
||||||
}
|
}
|
||||||
self.wallet_child_status()
|
self.wallet_child_status()
|
||||||
}
|
}
|
||||||
|
|
@ -2316,6 +2317,32 @@ pub fn ingest_chat_frame(
|
||||||
Ok(line.to_vec())
|
Ok(line.to_vec())
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// The error a wallet-child probe leaves on the status row.
|
||||||
|
///
|
||||||
|
/// `probed` is what the probe said (`None` when the RPC answered); `previous` is
|
||||||
|
/// what the row already held. A wallet RPC that refuses the connection because
|
||||||
|
/// it is still coming up is not an error to show — the row would flash
|
||||||
|
/// `wallet connect: Connection refused` and then clear itself on the next tick.
|
||||||
|
/// It is not silent either: whatever real error the row already held survives.
|
||||||
|
/// A timeout, `-13`, `No wallet file`, or a bad passphrase is the RPC's own
|
||||||
|
/// answer and is kept, as is the same connect text once the child is up and
|
||||||
|
/// answering (`connected`) and then stops.
|
||||||
|
pub(crate) fn probe_error(
|
||||||
|
connected: bool,
|
||||||
|
probed: Option<String>,
|
||||||
|
previous: Option<String>,
|
||||||
|
) -> Option<String> {
|
||||||
|
if connected {
|
||||||
|
return None;
|
||||||
|
}
|
||||||
|
match probed {
|
||||||
|
Some(err) if wallet::error_is_unreachable(&err) => {
|
||||||
|
previous.filter(|prev| !wallet::error_is_unreachable(prev))
|
||||||
|
}
|
||||||
|
other => other,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
fn spawn_rend(
|
fn spawn_rend(
|
||||||
node: Arc<Node>,
|
node: Arc<Node>,
|
||||||
rend: impl futures::Stream<Item = tor_hsservice::RendRequest> + Send + 'static,
|
rend: impl futures::Stream<Item = tor_hsservice::RendRequest> + Send + 'static,
|
||||||
|
|
@ -2446,6 +2473,7 @@ pub(crate) fn test_node_with_wallets(home: &Path, wallets: &[(&str, &str)]) -> A
|
||||||
pub(crate) mod tests {
|
pub(crate) mod tests {
|
||||||
use super::*;
|
use super::*;
|
||||||
use crate::wallet_child::DEFAULT_MONEROD_RPC_PORT;
|
use crate::wallet_child::DEFAULT_MONEROD_RPC_PORT;
|
||||||
|
use crate::wallet_child::test_support::PublishedPortHold;
|
||||||
use std::pin::Pin;
|
use std::pin::Pin;
|
||||||
|
|
||||||
use crate::wallet::ChainSource;
|
use crate::wallet::ChainSource;
|
||||||
|
|
@ -3114,6 +3142,32 @@ pub(crate) mod tests {
|
||||||
path
|
path
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// [`fake_child_bin`] with the shared log written *last*: this child's own
|
||||||
|
/// `<log>.<pid>` lands immediately and the path a harness that reads it
|
||||||
|
/// would take lags behind — a killed child's write landing after a clear
|
||||||
|
/// (CI run 905, job 1373).
|
||||||
|
fn fake_child_bin_shared_late(
|
||||||
|
dir: &Path,
|
||||||
|
name: &str,
|
||||||
|
log: &Path,
|
||||||
|
delay: &str,
|
||||||
|
body: &str,
|
||||||
|
) -> PathBuf {
|
||||||
|
std::fs::create_dir_all(dir).expect("fake bin dir");
|
||||||
|
let path = dir.join(name);
|
||||||
|
let script = format!(
|
||||||
|
"#!/bin/sh\ntmp='{log}'.$$.writing\n: > \"$tmp\"\nprintf '%s\\n' \"$0\" >> \"$tmp\"\nfor a in \"$@\"; do printf '%s\\n' \"$a\" >> \"$tmp\"; done\nmv -f \"$tmp\" '{log}'.$$\n{delay}\ncp -f '{log}'.$$ '{log}'.$$.shared\nmv -f '{log}'.$$.shared '{log}'\n{body}\n",
|
||||||
|
log = log.display(),
|
||||||
|
delay = delay,
|
||||||
|
body = body
|
||||||
|
);
|
||||||
|
std::fs::write(&path, script).expect("write fake bin");
|
||||||
|
let mut perms = std::fs::metadata(&path).expect("stat").permissions();
|
||||||
|
std::os::unix::fs::PermissionsExt::set_mode(&mut perms, 0o700);
|
||||||
|
std::fs::set_permissions(&path, perms).expect("chmod");
|
||||||
|
path
|
||||||
|
}
|
||||||
|
|
||||||
/// A loopback daemon is the one source that spawns no SOCKS child, so the
|
/// A loopback daemon is the one source that spawns no SOCKS child, so the
|
||||||
/// test drives exactly one process.
|
/// test drives exactly one process.
|
||||||
fn loopback_child_config(bin: PathBuf, filename: &str) -> ChildConfig {
|
fn loopback_child_config(bin: PathBuf, filename: &str) -> ChildConfig {
|
||||||
|
|
@ -3211,6 +3265,9 @@ pub(crate) mod tests {
|
||||||
);
|
);
|
||||||
node.set_wallet_child_config(&loopback_child_config(bin, "onionwire"))
|
node.set_wallet_child_config(&loopback_child_config(bin, "onionwire"))
|
||||||
.expect("set config");
|
.expect("set config");
|
||||||
|
// The gate dials the port the fake was told to bind; a shell fake cannot
|
||||||
|
// bind one, so hold it here.
|
||||||
|
let _hold = PublishedPortHold::watching(std::slice::from_ref(&log));
|
||||||
node.start_wallet_child().expect("start");
|
node.start_wallet_child().expect("start");
|
||||||
// The child is a fake process; the wallet the node actually talks to is
|
// The child is a fake process; the wallet the node actually talks to is
|
||||||
// the mock RPC, which is where the numbers come from.
|
// the mock RPC, which is where the numbers come from.
|
||||||
|
|
@ -3264,6 +3321,9 @@ pub(crate) mod tests {
|
||||||
wallet_filename: "onionwire".to_string(),
|
wallet_filename: "onionwire".to_string(),
|
||||||
})
|
})
|
||||||
.expect("set config");
|
.expect("set config");
|
||||||
|
// The gate dials the port the fake was told to bind; a shell fake cannot
|
||||||
|
// bind one, so hold the port it publishes.
|
||||||
|
let _hold = PublishedPortHold::watching(&[dir.path().join("rpc.argv")]);
|
||||||
node.start_wallet_child().expect("start");
|
node.start_wallet_child().expect("start");
|
||||||
|
|
||||||
let status = node.wallet_child_refresh().await;
|
let status = node.wallet_child_refresh().await;
|
||||||
|
|
@ -3335,6 +3395,7 @@ pub(crate) mod tests {
|
||||||
node.set_wallet_child_config(&loopback_child_config(bin.clone(), "onionwire"))
|
node.set_wallet_child_config(&loopback_child_config(bin.clone(), "onionwire"))
|
||||||
.expect("set config");
|
.expect("set config");
|
||||||
|
|
||||||
|
let _hold = PublishedPortHold::watching(std::slice::from_ref(&log));
|
||||||
node.start_wallet_child().expect("start");
|
node.start_wallet_child().expect("start");
|
||||||
let status = node.wallet_child_status();
|
let status = node.wallet_child_status();
|
||||||
assert!(status.running, "{status:?}");
|
assert!(status.running, "{status:?}");
|
||||||
|
|
@ -3401,6 +3462,9 @@ pub(crate) mod tests {
|
||||||
node.set_wallet_child_config(&loopback_child_config(bin, "onionwire"))
|
node.set_wallet_child_config(&loopback_child_config(bin, "onionwire"))
|
||||||
.expect("set config");
|
.expect("set config");
|
||||||
|
|
||||||
|
// The fake exits instead of binding its port; the gate must still see
|
||||||
|
// the accept the real child would have offered before it died.
|
||||||
|
let _hold = PublishedPortHold::watching(std::slice::from_ref(&log));
|
||||||
node.start_wallet_child().expect("start");
|
node.start_wallet_child().expect("start");
|
||||||
let mut status = node.wallet_child_status();
|
let mut status = node.wallet_child_status();
|
||||||
for _ in 0..300 {
|
for _ in 0..300 {
|
||||||
|
|
@ -3435,6 +3499,7 @@ pub(crate) mod tests {
|
||||||
{
|
{
|
||||||
let node = offline_node(&home, Arc::new(NoDial));
|
let node = offline_node(&home, Arc::new(NoDial));
|
||||||
node.set_wallet_child_config(&saved).expect("set config");
|
node.set_wallet_child_config(&saved).expect("set config");
|
||||||
|
let _hold = PublishedPortHold::watching(std::slice::from_ref(&log));
|
||||||
node.start_wallet_child().expect("start");
|
node.start_wallet_child().expect("start");
|
||||||
let before = sealed_creds(&node);
|
let before = sealed_creds(&node);
|
||||||
|
|
||||||
|
|
@ -3524,6 +3589,7 @@ pub(crate) mod tests {
|
||||||
);
|
);
|
||||||
node.set_wallet_child_config(&loopback_child_config(bin, "onionwire"))
|
node.set_wallet_child_config(&loopback_child_config(bin, "onionwire"))
|
||||||
.expect("set config");
|
.expect("set config");
|
||||||
|
let _hold = PublishedPortHold::watching(std::slice::from_ref(&log));
|
||||||
node.start_wallet_child().expect("start");
|
node.start_wallet_child().expect("start");
|
||||||
|
|
||||||
let mut pid = 0u32;
|
let mut pid = 0u32;
|
||||||
|
|
@ -3987,25 +4053,6 @@ pub(crate) mod tests {
|
||||||
.expect("a running wallet child")
|
.expect("a running wallet child")
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Wait for the pid of a child that is not `previous` — the restart's.
|
|
||||||
async fn wait_for_new_child_pid(node: &Node, previous: u32) -> u32 {
|
|
||||||
for _ in 0..600 {
|
|
||||||
let pid = node
|
|
||||||
.wallet_child
|
|
||||||
.lock()
|
|
||||||
.ok()
|
|
||||||
.and_then(|guard| guard.clone())
|
|
||||||
.and_then(|child| child.wallet_rpc_pid());
|
|
||||||
if let Some(pid) = pid
|
|
||||||
&& pid != previous
|
|
||||||
{
|
|
||||||
return pid;
|
|
||||||
}
|
|
||||||
tokio::time::sleep(Duration::from_millis(10)).await;
|
|
||||||
}
|
|
||||||
panic!("the restart never reported a new wallet-child pid");
|
|
||||||
}
|
|
||||||
|
|
||||||
/// `--rpc-bind-port <port>` out of a fake child's argv log.
|
/// `--rpc-bind-port <port>` out of a fake child's argv log.
|
||||||
fn rpc_port_in(raw: &str) -> Option<u16> {
|
fn rpc_port_in(raw: &str) -> Option<u16> {
|
||||||
let lines: Vec<&str> = raw.lines().collect();
|
let lines: Vec<&str> = raw.lines().collect();
|
||||||
|
|
@ -4044,6 +4091,68 @@ pub(crate) mod tests {
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// The port the *next* child was spawned with, read from the argv log that
|
||||||
|
/// child alone owns — `<log>.<pid>`.
|
||||||
|
///
|
||||||
|
/// The pid comes from the directory, not from the node: the node publishes
|
||||||
|
/// the child only after the readiness gate saw its RPC accept, so a test
|
||||||
|
/// that must *be* that listener has to find the port from the outside. The
|
||||||
|
/// shared path is still the wrong one for the same reason
|
||||||
|
/// [`wait_for_child_rpc_port`] documents.
|
||||||
|
async fn wait_for_restarted_rpc_port(argv_log: &Path, previous_pid: u32) -> u16 {
|
||||||
|
let name = argv_log
|
||||||
|
.file_name()
|
||||||
|
.and_then(|name| name.to_str())
|
||||||
|
.expect("the argv log has a file name");
|
||||||
|
let dir = argv_log.parent().expect("the argv log has a directory");
|
||||||
|
let prefix = format!("{name}.");
|
||||||
|
for _ in 0..600 {
|
||||||
|
if let Ok(entries) = std::fs::read_dir(dir) {
|
||||||
|
for entry in entries.flatten() {
|
||||||
|
let path = entry.path();
|
||||||
|
let Some(name) = path.file_name().and_then(|name| name.to_str()) else {
|
||||||
|
continue;
|
||||||
|
};
|
||||||
|
let Some(suffix) = name.strip_prefix(prefix.as_str()) else {
|
||||||
|
continue;
|
||||||
|
};
|
||||||
|
// `<log>.<pid>` only. A child killed between its shared write
|
||||||
|
// and its own leaves `<log>.<pid>.writing` behind, and that
|
||||||
|
// temp file still names the *previous* child's port.
|
||||||
|
let Ok(pid) = suffix.parse::<u32>() else {
|
||||||
|
continue;
|
||||||
|
};
|
||||||
|
if pid == previous_pid {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
if let Ok(raw) = std::fs::read_to_string(&path)
|
||||||
|
&& let Some(port) = rpc_port_in(&raw)
|
||||||
|
{
|
||||||
|
return port;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
tokio::time::sleep(Duration::from_millis(10)).await;
|
||||||
|
}
|
||||||
|
panic!(
|
||||||
|
"no child other than pid {previous_pid} published an --rpc-bind-port under {}",
|
||||||
|
dir.display()
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Bind the restarted child's mock on `port`, retrying while the readiness
|
||||||
|
/// stand-in still holds it: the stand-in releases the port on the gate's own
|
||||||
|
/// probe, and the mock must own it from then on.
|
||||||
|
async fn bind_when_free(port: u16) -> tokio::net::TcpListener {
|
||||||
|
for _ in 0..500 {
|
||||||
|
if let Ok(listener) = tokio::net::TcpListener::bind(("127.0.0.1", port)).await {
|
||||||
|
return listener;
|
||||||
|
}
|
||||||
|
tokio::time::sleep(Duration::from_millis(10)).await;
|
||||||
|
}
|
||||||
|
panic!("the readiness stand-in never released port {port}");
|
||||||
|
}
|
||||||
|
|
||||||
/// The wallet-file passphrase this install remembers, `""` when none.
|
/// The wallet-file passphrase this install remembers, `""` when none.
|
||||||
fn sealed_passphrase(node: &Node) -> String {
|
fn sealed_passphrase(node: &Node) -> String {
|
||||||
node.store
|
node.store
|
||||||
|
|
@ -4055,6 +4164,48 @@ pub(crate) mod tests {
|
||||||
.unwrap_or_default()
|
.unwrap_or_default()
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// A wallet RPC that is not answering *yet* is not a row error: it is the
|
||||||
|
/// child coming up, and the row would otherwise flash the string the user
|
||||||
|
/// saw. Everything else — a timeout, `-13`, a refused passphrase — is the
|
||||||
|
/// RPC's own answer and stays on the row.
|
||||||
|
#[test]
|
||||||
|
fn an_unreachable_probe_is_not_a_status_error() {
|
||||||
|
use crate::wallet::error_is_unreachable;
|
||||||
|
assert!(error_is_unreachable(
|
||||||
|
"wallet connect: Connection refused (os error 111)"
|
||||||
|
));
|
||||||
|
assert!(error_is_unreachable("wallet write: Connection reset"));
|
||||||
|
assert!(!error_is_unreachable("wallet RPC timed out"));
|
||||||
|
assert!(!error_is_unreachable("No wallet file"));
|
||||||
|
assert_eq!(
|
||||||
|
probe_error(
|
||||||
|
false,
|
||||||
|
Some("wallet connect: Connection refused (os error 111)".into()),
|
||||||
|
None
|
||||||
|
),
|
||||||
|
None,
|
||||||
|
"a connect refusal while coming up is not a row error"
|
||||||
|
);
|
||||||
|
assert_eq!(
|
||||||
|
probe_error(
|
||||||
|
false,
|
||||||
|
Some("wallet connect: Connection refused (os error 111)".into()),
|
||||||
|
Some("bad passphrase".into())
|
||||||
|
),
|
||||||
|
Some("bad passphrase".into()),
|
||||||
|
"a connect refusal must not replace a real error"
|
||||||
|
);
|
||||||
|
assert_eq!(
|
||||||
|
probe_error(false, Some("No wallet file".into()), None),
|
||||||
|
Some("No wallet file".into()),
|
||||||
|
"an RPC answer is still stored"
|
||||||
|
);
|
||||||
|
assert_eq!(
|
||||||
|
probe_error(true, Some("ignored".into()), Some("old".into())),
|
||||||
|
None
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
/// The bug this card exists for: `monero-wallet-rpc` keeps a wallet open
|
/// The bug this card exists for: `monero-wallet-rpc` keeps a wallet open
|
||||||
/// only for the life of its process, so a restarted child answered every
|
/// only for the life of its process, so a restarted child answered every
|
||||||
/// read with `-13 No wallet file` while the file sat on disk. The second
|
/// read with `-13 No wallet file` while the file sat on disk. The second
|
||||||
|
|
@ -4081,19 +4232,29 @@ pub(crate) mod tests {
|
||||||
test_record_wallet(&node.store.lock().unwrap(), "onionwire-1", "savings");
|
test_record_wallet(&node.store.lock().unwrap(), "onionwire-1", "savings");
|
||||||
|
|
||||||
// First start: the catalogue holds the file, but this install holds no
|
// First start: the catalogue holds the file, but this install holds no
|
||||||
// passphrase for it. That is a state, not a failure.
|
// passphrase for it. That is a state, not a failure. The gate needs the
|
||||||
|
// port the fake was told to bind; the restart below is answered by this
|
||||||
|
// test's own mock, so the hold is dropped before it.
|
||||||
|
let hold = PublishedPortHold::watching(std::slice::from_ref(&argv_log));
|
||||||
node.start_wallet_child().expect("first start");
|
node.start_wallet_child().expect("first start");
|
||||||
let status = node.wallet_child_status();
|
let status = node.wallet_child_status();
|
||||||
assert!(status.running, "{status:?}");
|
assert!(status.running, "{status:?}");
|
||||||
assert!(!status.wallet_open, "{status:?}");
|
assert!(!status.wallet_open, "{status:?}");
|
||||||
assert!(status.needs_passphrase, "{status:?}");
|
assert!(status.needs_passphrase, "{status:?}");
|
||||||
assert!(status.last_error.is_none(), "{status:?}");
|
assert!(status.last_error.is_none(), "{status:?}");
|
||||||
|
drop(hold);
|
||||||
|
|
||||||
// Restart it with the passphrase the user supplied. The child picks a
|
// Restart it with the passphrase the user supplied. The child picks a
|
||||||
// fresh port, so the mock is bound to the port *this* spawn named while
|
// fresh port, so the mock is bound to the port *this* spawn named while
|
||||||
// the open waits for its RPC to answer — read from the argv log the new
|
// the open waits for its RPC to answer — read from the argv log the new
|
||||||
// pid owns, never from the shared path the previous child wrote: a loaded
|
// pid owns, never from the shared path the previous child wrote: a loaded
|
||||||
// runner lands that write after a clear (CI run 905, job 1373).
|
// runner lands that write after a clear (CI run 905, job 1373).
|
||||||
|
//
|
||||||
|
// The node cannot name that pid any more (it publishes the child only
|
||||||
|
// once the gate has seen the RPC accept), so the port comes from the
|
||||||
|
// directory — and the mock must own it *before* the gate's probe, not
|
||||||
|
// after: a listener that accepts the probe and then closes resets the
|
||||||
|
// client's own dial, which is an RPC answer, not an unreachable child.
|
||||||
let first_pid = child_pid(&node);
|
let first_pid = child_pid(&node);
|
||||||
std::fs::write(&argv_log, b"").expect("clear the argv log");
|
std::fs::write(&argv_log, b"").expect("clear the argv log");
|
||||||
let requests = Arc::new(Mutex::new(Vec::new()));
|
let requests = Arc::new(Mutex::new(Vec::new()));
|
||||||
|
|
@ -4101,11 +4262,8 @@ pub(crate) mod tests {
|
||||||
let started = tokio::task::spawn_blocking(move || {
|
let started = tokio::task::spawn_blocking(move || {
|
||||||
starter.open_wallet_with_passphrase("onionwire-1", "walletfile-pass")
|
starter.open_wallet_with_passphrase("onionwire-1", "walletfile-pass")
|
||||||
});
|
});
|
||||||
let pid = wait_for_new_child_pid(&node, first_pid).await;
|
let port = wait_for_restarted_rpc_port(&argv_log, first_pid).await;
|
||||||
let port = wait_for_child_rpc_port(&argv_log, pid).await;
|
let listener = bind_when_free(port).await;
|
||||||
let listener = tokio::net::TcpListener::bind(("127.0.0.1", port))
|
|
||||||
.await
|
|
||||||
.unwrap_or_else(|e| panic!("bind the restarted child's mock on {port}: {e}"));
|
|
||||||
tokio::spawn(serve_mock_rpc(
|
tokio::spawn(serve_mock_rpc(
|
||||||
listener,
|
listener,
|
||||||
recording_wallet_reply(Arc::clone(&requests)),
|
recording_wallet_reply(Arc::clone(&requests)),
|
||||||
|
|
@ -4177,16 +4335,19 @@ pub(crate) mod tests {
|
||||||
.expect("set config");
|
.expect("set config");
|
||||||
test_record_wallet(&node.store.lock().unwrap(), "onionwire-1", "savings");
|
test_record_wallet(&node.store.lock().unwrap(), "onionwire-1", "savings");
|
||||||
|
|
||||||
|
let hold = PublishedPortHold::watching(std::slice::from_ref(&argv_log));
|
||||||
node.start_wallet_child().expect("first start");
|
node.start_wallet_child().expect("first start");
|
||||||
let first_pid = child_pid(&node);
|
let first_pid = child_pid(&node);
|
||||||
// The killed child's argv is in the shared path (its own log lands first,
|
// The killed child's argv is in the shared path (its own log lands first,
|
||||||
// so this waits for both) — the content the old harness would read.
|
// so this waits for both) — the content the old harness would read.
|
||||||
let stale_port = wait_for_child_rpc_port(&argv_log, first_pid).await;
|
let stale_port = wait_for_child_rpc_port(&argv_log, first_pid).await;
|
||||||
|
|
||||||
// The restart's exec is late here, the way a loaded runner delays it, so
|
// The restart's own log lands at once, while the shared path lags 2s
|
||||||
// the shared path still holds the killed child's argv while the restarted
|
// behind — the way a loaded runner lands the killed child's write after
|
||||||
// child is already being dialled.
|
// a clear. The lag is what makes the shared read below wrong; it is not
|
||||||
let restart = fake_child_bin_after(
|
// the child's exec that is late, because the readiness gate now runs
|
||||||
|
// before the child is published and cannot wait 2s for an argv file.
|
||||||
|
let restart = fake_child_bin_shared_late(
|
||||||
&dir.path().join("fake-bins-restart"),
|
&dir.path().join("fake-bins-restart"),
|
||||||
"monero-wallet-rpc",
|
"monero-wallet-rpc",
|
||||||
&argv_log,
|
&argv_log,
|
||||||
|
|
@ -4197,24 +4358,20 @@ pub(crate) mod tests {
|
||||||
.expect("re-point the child at the late-write stand-in");
|
.expect("re-point the child at the late-write stand-in");
|
||||||
let requests = Arc::new(Mutex::new(Vec::new()));
|
let requests = Arc::new(Mutex::new(Vec::new()));
|
||||||
let starter = Arc::clone(&node);
|
let starter = Arc::clone(&node);
|
||||||
|
drop(hold);
|
||||||
let started = tokio::task::spawn_blocking(move || {
|
let started = tokio::task::spawn_blocking(move || {
|
||||||
starter.open_wallet_with_passphrase("onionwire-1", "walletfile-pass")
|
starter.open_wallet_with_passphrase("onionwire-1", "walletfile-pass")
|
||||||
});
|
});
|
||||||
let pid = wait_for_new_child_pid(&node, first_pid).await;
|
// The premise of the test, asserted while it is true: the shared path
|
||||||
// The premise of the test: the shared path still holds the killed
|
// still holds the killed child's argv, so a harness that reads it binds
|
||||||
// child's argv, so a harness that reads it binds the mock on the wrong
|
// the mock on the wrong port and the restart never reaches a mock at all.
|
||||||
// port. Reading the restarted child's own log instead is what the fix
|
|
||||||
// is — with the shared read, this test fails on the port above after the
|
|
||||||
// whole `WALLET_OPEN_WAIT`.
|
|
||||||
assert_eq!(
|
assert_eq!(
|
||||||
rpc_port_in(&std::fs::read_to_string(&argv_log).unwrap_or_default()),
|
rpc_port_in(&std::fs::read_to_string(&argv_log).unwrap_or_default()),
|
||||||
Some(stale_port),
|
Some(stale_port),
|
||||||
"the restarted child must not have written the shared path yet"
|
"the restarted child must not have written the shared path yet"
|
||||||
);
|
);
|
||||||
let port = wait_for_child_rpc_port(&argv_log, pid).await;
|
let port = wait_for_restarted_rpc_port(&argv_log, first_pid).await;
|
||||||
let listener = tokio::net::TcpListener::bind(("127.0.0.1", port))
|
let listener = bind_when_free(port).await;
|
||||||
.await
|
|
||||||
.unwrap_or_else(|e| panic!("bind the restarted child's mock on {port}: {e}"));
|
|
||||||
tokio::spawn(serve_mock_rpc(
|
tokio::spawn(serve_mock_rpc(
|
||||||
listener,
|
listener,
|
||||||
recording_wallet_reply(Arc::clone(&requests)),
|
recording_wallet_reply(Arc::clone(&requests)),
|
||||||
|
|
@ -4259,6 +4416,7 @@ pub(crate) mod tests {
|
||||||
.expect("set config");
|
.expect("set config");
|
||||||
test_record_wallet(&node.store.lock().unwrap(), "onionwire-1", "savings");
|
test_record_wallet(&node.store.lock().unwrap(), "onionwire-1", "savings");
|
||||||
|
|
||||||
|
let hold = PublishedPortHold::watching(std::slice::from_ref(&argv_log));
|
||||||
node.start_wallet_child()
|
node.start_wallet_child()
|
||||||
.expect("a wallet-less child still starts");
|
.expect("a wallet-less child still starts");
|
||||||
let status = node.wallet_child_status();
|
let status = node.wallet_child_status();
|
||||||
|
|
@ -4274,12 +4432,14 @@ pub(crate) mod tests {
|
||||||
std::fs::write(&argv_log, b"").expect("clear the argv log");
|
std::fs::write(&argv_log, b"").expect("clear the argv log");
|
||||||
let requests = Arc::new(Mutex::new(Vec::new()));
|
let requests = Arc::new(Mutex::new(Vec::new()));
|
||||||
let starter = Arc::clone(&node);
|
let starter = Arc::clone(&node);
|
||||||
|
// The second start is answered by the mock this test binds, and the node
|
||||||
|
// cannot name its pid: it publishes the child only once the gate has seen
|
||||||
|
// the RPC accept. The mock is bound from the child's own log, in time for
|
||||||
|
// the gate's next probe.
|
||||||
|
drop(hold);
|
||||||
let started = tokio::task::spawn_blocking(move || starter.start_wallet_child());
|
let started = tokio::task::spawn_blocking(move || starter.start_wallet_child());
|
||||||
let pid = wait_for_new_child_pid(&node, first_pid).await;
|
let port = wait_for_restarted_rpc_port(&argv_log, first_pid).await;
|
||||||
let port = wait_for_child_rpc_port(&argv_log, pid).await;
|
let listener = bind_when_free(port).await;
|
||||||
let listener = tokio::net::TcpListener::bind(("127.0.0.1", port))
|
|
||||||
.await
|
|
||||||
.unwrap_or_else(|e| panic!("bind the fake child's mock on {port}: {e}"));
|
|
||||||
tokio::spawn(serve_mock_rpc(
|
tokio::spawn(serve_mock_rpc(
|
||||||
listener,
|
listener,
|
||||||
recording_wallet_reply(Arc::clone(&requests)),
|
recording_wallet_reply(Arc::clone(&requests)),
|
||||||
|
|
|
||||||
|
|
@ -19,17 +19,23 @@ impl std::fmt::Display for Error {
|
||||||
|
|
||||||
impl std::error::Error for Error {}
|
impl std::error::Error for Error {}
|
||||||
|
|
||||||
|
/// Is this failure "the wallet RPC is not answering yet"? That is the one class
|
||||||
|
/// a retry can fix — a freshly spawned `monero-wallet-rpc` binds its port a
|
||||||
|
/// moment after `spawn` returns. Everything else (a refused passphrase, a
|
||||||
|
/// protocol error) is the RPC's own answer and retrying it would only repeat it.
|
||||||
|
///
|
||||||
|
/// Deliberately *not* the timeout: a hung child is not a start in progress.
|
||||||
|
///
|
||||||
|
/// The free function is the rule itself: a status row keeps an already
|
||||||
|
/// formatted `String`, and it must apply exactly the same test to it.
|
||||||
|
pub fn error_is_unreachable(msg: &str) -> bool {
|
||||||
|
msg.starts_with("wallet connect:") || msg.starts_with("wallet write:")
|
||||||
|
}
|
||||||
|
|
||||||
impl Error {
|
impl Error {
|
||||||
/// Is this failure "the wallet RPC is not answering yet"? That is the one
|
/// [`error_is_unreachable`], on this error's own message.
|
||||||
/// class a retry can fix — a freshly spawned `monero-wallet-rpc` binds its
|
|
||||||
/// port a moment after `spawn` returns. Everything else (a refused
|
|
||||||
/// passphrase, a protocol error) is the RPC's own answer and retrying it
|
|
||||||
/// would only repeat it.
|
|
||||||
///
|
|
||||||
/// Deliberately *not* the timeout: a hung child is not a start in progress.
|
|
||||||
pub fn is_unreachable(&self) -> bool {
|
pub fn is_unreachable(&self) -> bool {
|
||||||
let msg = self.0.as_str();
|
error_is_unreachable(self.0.as_str())
|
||||||
msg.starts_with("wallet connect:") || msg.starts_with("wallet write:")
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -67,6 +67,20 @@ pub const SOCKS_PROBE_TIMEOUT: Duration = Duration::from_millis(500);
|
||||||
/// Gap between readiness-probe attempts.
|
/// Gap between readiness-probe attempts.
|
||||||
pub const SOCKS_PROBE_INTERVAL: Duration = Duration::from_millis(100);
|
pub const SOCKS_PROBE_INTERVAL: Duration = Duration::from_millis(100);
|
||||||
|
|
||||||
|
/// How long `start_children` waits for the app-owned chain daemon to accept a
|
||||||
|
/// TCP connection after `Node::launch` (or the `monerod` spawn) returned.
|
||||||
|
///
|
||||||
|
/// This is a `connect()`-accepted budget, not a Tor-bootstrap or chain-sync
|
||||||
|
/// budget: the spike saw Cuprate's unrestricted listener accept within ~0.2s of
|
||||||
|
/// `launch` returning. A longer wait only makes Start look dead again.
|
||||||
|
pub const DAEMON_LISTENER_TIMEOUT: Duration = Duration::from_secs(5);
|
||||||
|
|
||||||
|
/// How long `start_children` waits for its own `monero-wallet-rpc` to accept a
|
||||||
|
/// TCP connection before handing the client back. Same reasoning as
|
||||||
|
/// [`DAEMON_LISTENER_TIMEOUT`]: the child binds its port a moment after
|
||||||
|
/// `spawn` returns.
|
||||||
|
pub const WALLET_RPC_LISTENER_TIMEOUT: Duration = Duration::from_secs(5);
|
||||||
|
|
||||||
/// The scheme Monero's `--proxy` needs for SOCKS5. A bare `host:port` means
|
/// The scheme Monero's `--proxy` needs for SOCKS5. A bare `host:port` means
|
||||||
/// SOCKS4a (docs/proxies.md), which is *not* what this app asks for.
|
/// SOCKS4a (docs/proxies.md), which is *not* what this app asks for.
|
||||||
pub const SOCKS5_SCHEME: &str = "socks5://";
|
pub const SOCKS5_SCHEME: &str = "socks5://";
|
||||||
|
|
@ -299,6 +313,22 @@ impl WalletChild {
|
||||||
format!("{SOCKS5_SCHEME}127.0.0.1:{port}")
|
format!("{SOCKS5_SCHEME}127.0.0.1:{port}")
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Poll `127.0.0.1:port` until it accepts, or `budget` elapses.
|
||||||
|
///
|
||||||
|
/// Proves the listener accepted a TCP connection. Does not prove HTTP, a
|
||||||
|
/// wallet file, or a synced chain. `what` is the noun in the error
|
||||||
|
/// (`chain daemon RPC`, `monero-wallet-rpc`).
|
||||||
|
pub fn loopback_listener_ready(port: u16, budget: Duration, what: &str) -> Result<()> {
|
||||||
|
match Self::poll_loopback(port, budget) {
|
||||||
|
Ok(()) => Ok(()),
|
||||||
|
Err(last) => Err(ChildError(format!(
|
||||||
|
"{what} on 127.0.0.1:{port} did not accept a connection within {}s ({}) — not continuing startup against a closed port",
|
||||||
|
budget.as_secs_f32(),
|
||||||
|
last
|
||||||
|
))),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
/// Wait for the SOCKS listener to accept a connection, with an explicit
|
/// Wait for the SOCKS listener to accept a connection, with an explicit
|
||||||
/// budget so a dead proxy fails visibly instead of hanging the wallet
|
/// budget so a dead proxy fails visibly instead of hanging the wallet
|
||||||
/// screen.
|
/// screen.
|
||||||
|
|
@ -307,22 +337,32 @@ impl WalletChild {
|
||||||
/// it does not prove the Tor circuit works. It also does not resolve the
|
/// it does not prove the Tor circuit works. It also does not resolve the
|
||||||
/// `.onion` name locally — the name travels inside the SOCKS request.
|
/// `.onion` name locally — the name travels inside the SOCKS request.
|
||||||
pub fn socks_listener_ready(port: u16, budget: Duration) -> Result<()> {
|
pub fn socks_listener_ready(port: u16, budget: Duration) -> Result<()> {
|
||||||
|
match Self::poll_loopback(port, budget) {
|
||||||
|
Ok(()) => Ok(()),
|
||||||
|
Err(last) => Err(ChildError(format!(
|
||||||
|
"SOCKS proxy on 127.0.0.1:{port} did not accept a connection within {}s \
|
||||||
|
({last}) — not spawning a wallet child against a dead proxy",
|
||||||
|
budget.as_secs_f32()
|
||||||
|
))),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// One accept loop, shared by every loopback readiness gate. `Err` carries
|
||||||
|
/// the last connect error as text, not a formatted message: the caller owns
|
||||||
|
/// the wording (the SOCKS gate and the daemon/wallet-RPC gates say
|
||||||
|
/// different things).
|
||||||
|
fn poll_loopback(port: u16, budget: Duration) -> std::result::Result<(), String> {
|
||||||
let addr = SocketAddr::from((Ipv4Addr::LOCALHOST, port));
|
let addr = SocketAddr::from((Ipv4Addr::LOCALHOST, port));
|
||||||
let deadline = Instant::now() + budget;
|
let deadline = Instant::now() + budget;
|
||||||
let mut last = None;
|
let mut last = None;
|
||||||
while Instant::now() <= deadline {
|
while Instant::now() <= deadline {
|
||||||
match TcpStream::connect_timeout(&addr, SOCKS_PROBE_TIMEOUT) {
|
match TcpStream::connect_timeout(&addr, SOCKS_PROBE_TIMEOUT) {
|
||||||
Ok(_) => return Ok(()),
|
Ok(_) => return Ok(()),
|
||||||
Err(e) => last = Some(e),
|
Err(e) => last = Some(e.to_string()),
|
||||||
}
|
}
|
||||||
std::thread::sleep(SOCKS_PROBE_INTERVAL);
|
std::thread::sleep(SOCKS_PROBE_INTERVAL);
|
||||||
}
|
}
|
||||||
Err(ChildError(format!(
|
Err(last.unwrap_or_else(|| "no attempt".into()))
|
||||||
"SOCKS proxy on 127.0.0.1:{port} did not accept a connection within {}s \
|
|
||||||
({}) — not spawning a wallet child against a dead proxy",
|
|
||||||
budget.as_secs_f32(),
|
|
||||||
last.map(|e| e.to_string()).unwrap_or_default()
|
|
||||||
)))
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/// The honest one-liner a UI can show for the configured chain source. A
|
/// The honest one-liner a UI can show for the configured chain source. A
|
||||||
|
|
@ -525,6 +565,20 @@ impl WalletChild {
|
||||||
ChainSource::None | ChainSource::Remote { .. } => {}
|
ChainSource::None | ChainSource::Remote { .. } => {}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if matches!(
|
||||||
|
self.source,
|
||||||
|
ChainSource::Local { .. } | ChainSource::InProcessCuprate { .. }
|
||||||
|
) {
|
||||||
|
// Node::launch returning is not "18081 accepts". The spike saw the
|
||||||
|
// unrestricted listener up within 0.2s of return; wait for that
|
||||||
|
// accept so the wallet child is not spawned against a closed port.
|
||||||
|
Self::loopback_listener_ready(
|
||||||
|
DEFAULT_MONEROD_RPC_PORT,
|
||||||
|
DAEMON_LISTENER_TIMEOUT,
|
||||||
|
"chain daemon RPC",
|
||||||
|
)?;
|
||||||
|
}
|
||||||
|
|
||||||
// A `.onion` daemon is only reachable through SOCKS. The app bundles the
|
// A `.onion` daemon is only reachable through SOCKS. The app bundles the
|
||||||
// `arti` binary as that proxy; it must be up before the wallet child
|
// `arti` binary as that proxy; it must be up before the wallet child
|
||||||
// starts, or the wallet child sits there failing to dial its daemon.
|
// starts, or the wallet child sits there failing to dial its daemon.
|
||||||
|
|
@ -564,6 +618,9 @@ impl WalletChild {
|
||||||
// monero-wallet-rpc creates the wallet file 0600; make that true even if
|
// monero-wallet-rpc creates the wallet file 0600; make that true even if
|
||||||
// it already existed with looser bits.
|
// it already existed with looser bits.
|
||||||
harden_wallet_file(&self.wallet_dir.join(&self.wallet_filename));
|
harden_wallet_file(&self.wallet_dir.join(&self.wallet_filename));
|
||||||
|
// Do not hand back a client whose port is still closed: `pick_port` only
|
||||||
|
// proved the port was free, not that the child bound it.
|
||||||
|
Self::loopback_listener_ready(port, WALLET_RPC_LISTENER_TIMEOUT, "monero-wallet-rpc")?;
|
||||||
Ok(Some(WalletClient {
|
Ok(Some(WalletClient {
|
||||||
url: format!("http://{user}:{}@127.0.0.1:{port}/json_rpc", pass.as_str()),
|
url: format!("http://{user}:{}@127.0.0.1:{port}/json_rpc", pass.as_str()),
|
||||||
no_spend: false,
|
no_spend: false,
|
||||||
|
|
@ -1223,6 +1280,7 @@ fn harden_wallet_file(path: &Path) {
|
||||||
|
|
||||||
#[cfg(test)]
|
#[cfg(test)]
|
||||||
mod tests {
|
mod tests {
|
||||||
|
use super::test_support::PublishedPortHold;
|
||||||
use super::*;
|
use super::*;
|
||||||
use std::io::Write;
|
use std::io::Write;
|
||||||
|
|
||||||
|
|
@ -1522,6 +1580,33 @@ mod tests {
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// The shared accept wait: it passes for a live listener and fails, inside
|
||||||
|
/// its budget, for a closed port — with a message that names the thing that
|
||||||
|
/// did not accept, so the wallet screen can say which port is closed.
|
||||||
|
#[test]
|
||||||
|
fn loopback_listener_ready_accepts_a_live_listener_and_times_out_without_one() {
|
||||||
|
let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
|
||||||
|
let port = listener.local_addr().unwrap().port();
|
||||||
|
assert!(
|
||||||
|
WalletChild::loopback_listener_ready(
|
||||||
|
port,
|
||||||
|
Duration::from_millis(200),
|
||||||
|
"chain daemon RPC"
|
||||||
|
)
|
||||||
|
.is_ok(),
|
||||||
|
"a live listener is ready"
|
||||||
|
);
|
||||||
|
drop(listener);
|
||||||
|
let err =
|
||||||
|
WalletChild::loopback_listener_ready(9, Duration::from_millis(200), "chain daemon RPC")
|
||||||
|
.expect_err("a closed port must fail the start, not hang");
|
||||||
|
let msg = err.to_string();
|
||||||
|
assert!(msg.contains("chain daemon RPC"), "{msg}");
|
||||||
|
assert!(msg.contains("127.0.0.1:9"), "{msg}");
|
||||||
|
assert!(msg.contains("not continuing startup"), "{msg}");
|
||||||
|
assert!(!msg.contains("dead proxy"), "{msg}");
|
||||||
|
}
|
||||||
|
|
||||||
/// The spawn path: a `.onion` remote starts `arti proxy -p <port>` first,
|
/// The spawn path: a `.onion` remote starts `arti proxy -p <port>` first,
|
||||||
/// the wallet child is pointed at it, and stopping the wallet child takes
|
/// the wallet child is pointed at it, and stopping the wallet child takes
|
||||||
/// the SOCKS listener with it.
|
/// the SOCKS listener with it.
|
||||||
|
|
@ -1562,6 +1647,9 @@ mod tests {
|
||||||
))
|
))
|
||||||
.with_socks_port(socks_port);
|
.with_socks_port(socks_port);
|
||||||
|
|
||||||
|
// The daemon gate does not apply to a remote source, but the wallet
|
||||||
|
// RPC's own port gate does: hold what the fake publishes.
|
||||||
|
let _hold = PublishedPortHold::watching(std::slice::from_ref(&rpc_log));
|
||||||
let client = child.start(&store).unwrap().expect("enabled child");
|
let client = child.start(&store).unwrap().expect("enabled child");
|
||||||
assert!(child.running(), "both children must be tracked");
|
assert!(child.running(), "both children must be tracked");
|
||||||
assert!(client.url().contains("127.0.0.1"), "{}", client.url());
|
assert!(client.url().contains("127.0.0.1"), "{}", client.url());
|
||||||
|
|
@ -1664,6 +1752,7 @@ mod tests {
|
||||||
&rpc_log,
|
&rpc_log,
|
||||||
));
|
));
|
||||||
|
|
||||||
|
let _hold = PublishedPortHold::watching(std::slice::from_ref(&rpc_log));
|
||||||
child.start(&store).unwrap().expect("enabled child");
|
child.start(&store).unwrap().expect("enabled child");
|
||||||
let rpc_argv = wait_for_argv(&rpc_log);
|
let rpc_argv = wait_for_argv(&rpc_log);
|
||||||
assert!(
|
assert!(
|
||||||
|
|
@ -1776,6 +1865,9 @@ mod tests {
|
||||||
.unwrap()
|
.unwrap()
|
||||||
.with_wallet_rpc_bin(fake_bin(&dir, "monero-wallet-rpc", &rpc_log));
|
.with_wallet_rpc_bin(fake_bin(&dir, "monero-wallet-rpc", &rpc_log));
|
||||||
|
|
||||||
|
// The gate dials the ports the fakes were told to bind; a shell fake
|
||||||
|
// cannot bind one, so hold them here.
|
||||||
|
let _hold = PublishedPortHold::watching(&[monerod_log.clone(), rpc_log.clone()]);
|
||||||
let client = child.start(&store).unwrap().expect("enabled child");
|
let client = child.start(&store).unwrap().expect("enabled child");
|
||||||
assert!(child.running(), "children must be tracked");
|
assert!(child.running(), "children must be tracked");
|
||||||
|
|
||||||
|
|
@ -1858,6 +1950,7 @@ mod tests {
|
||||||
.unwrap()
|
.unwrap()
|
||||||
.with_wallet_rpc_bin(fake_bin(&dir, "monero-wallet-rpc", &rpc_log));
|
.with_wallet_rpc_bin(fake_bin(&dir, "monero-wallet-rpc", &rpc_log));
|
||||||
|
|
||||||
|
let _hold = PublishedPortHold::watching(std::slice::from_ref(&rpc_log));
|
||||||
let first = child.start(&store).unwrap().unwrap().url().to_string();
|
let first = child.start(&store).unwrap().unwrap().url().to_string();
|
||||||
child.stop().unwrap();
|
child.stop().unwrap();
|
||||||
let second = child.start(&store).unwrap().unwrap().url().to_string();
|
let second = child.start(&store).unwrap().unwrap().url().to_string();
|
||||||
|
|
@ -2192,3 +2285,134 @@ mod tests {
|
||||||
false
|
false
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Test-only stand-in for the ports the fake children cannot bind.
|
||||||
|
///
|
||||||
|
/// The readiness gates dial a port the child was told to bind (`18081` for the
|
||||||
|
/// daemon, the argv's `--rpc-bind-port` for `monero-wallet-rpc`) and refuse to
|
||||||
|
/// continue while nothing accepts. A `sh` fake child cannot bind one, and the
|
||||||
|
/// wallet RPC's port is picked at random *inside* the start, so a test cannot
|
||||||
|
/// bind it up front either: without this, every start path in the suite would
|
||||||
|
/// fail the gate instead of exercising the code behind it.
|
||||||
|
///
|
||||||
|
/// Only for a start nothing dials afterwards. A test that answers the wallet RPC
|
||||||
|
/// itself must own the port *before* the gate's probe: a listener that accepts
|
||||||
|
/// the probe and then closes resets the client's own dial, and a reset is an RPC
|
||||||
|
/// answer, not an unreachable child.
|
||||||
|
#[cfg(test)]
|
||||||
|
pub(crate) mod test_support {
|
||||||
|
use std::collections::HashMap;
|
||||||
|
use std::path::{Path, PathBuf};
|
||||||
|
use std::sync::Arc;
|
||||||
|
use std::sync::atomic::{AtomicBool, Ordering};
|
||||||
|
use std::time::{Duration, SystemTime};
|
||||||
|
|
||||||
|
/// Holds every `--rpc-bind-port` a watched argv log publishes, for as long
|
||||||
|
/// as this value lives.
|
||||||
|
///
|
||||||
|
/// A held port is released the moment something connects to it: that connect
|
||||||
|
/// is the gate's own probe, and every dial after it must see the child's real
|
||||||
|
/// state (refused, or the test's own mock) rather than this stand-in. A
|
||||||
|
/// rewrite of the log is a new publication — the restart of a child whose
|
||||||
|
/// argv is identical (a local daemon's `18081`) is held again, while the
|
||||||
|
/// released publication is not.
|
||||||
|
pub(crate) struct PublishedPortHold {
|
||||||
|
stop: Arc<AtomicBool>,
|
||||||
|
handle: Option<std::thread::JoinHandle<()>>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl PublishedPortHold {
|
||||||
|
/// Watch these argv logs (`<something>.argv`, `argv.log`) and hold what
|
||||||
|
/// they publish.
|
||||||
|
pub(crate) fn watching(logs: &[PathBuf]) -> Self {
|
||||||
|
let logs: Vec<PathBuf> = logs.to_vec();
|
||||||
|
let stop = Arc::new(AtomicBool::new(false));
|
||||||
|
let flag = Arc::clone(&stop);
|
||||||
|
let handle = std::thread::spawn(move || {
|
||||||
|
// Held listeners and their ports, the write each log was last
|
||||||
|
// read at, and the ports released for its current write.
|
||||||
|
let mut held: Vec<std::net::TcpListener> = Vec::new();
|
||||||
|
let mut held_ports: Vec<u16> = Vec::new();
|
||||||
|
let mut seen_at: HashMap<PathBuf, SystemTime> = HashMap::new();
|
||||||
|
let mut released: HashMap<PathBuf, Vec<u16>> = HashMap::new();
|
||||||
|
while !flag.load(Ordering::Relaxed) {
|
||||||
|
for path in &logs {
|
||||||
|
let Some(mtime) = modified(path) else {
|
||||||
|
continue;
|
||||||
|
};
|
||||||
|
if seen_at.insert(path.clone(), mtime) != Some(mtime) {
|
||||||
|
// A new write of this log: a fresh publication, so a
|
||||||
|
// port released for the previous one is bindable.
|
||||||
|
released.remove(path);
|
||||||
|
}
|
||||||
|
for port in published_ports(path) {
|
||||||
|
let released_here = released
|
||||||
|
.get(path)
|
||||||
|
.is_some_and(|ports| ports.contains(&port));
|
||||||
|
if held_ports.contains(&port) || released_here {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
// A failed bind is not an error: something else is
|
||||||
|
// already answering on that port, which is all the
|
||||||
|
// gate asks for.
|
||||||
|
if let Ok(listener) =
|
||||||
|
std::net::TcpListener::bind((std::net::Ipv4Addr::LOCALHOST, port))
|
||||||
|
{
|
||||||
|
let _ = listener.set_nonblocking(true);
|
||||||
|
held.push(listener);
|
||||||
|
held_ports.push(port);
|
||||||
|
}
|
||||||
|
released.entry(path.clone()).or_default().push(port);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
let mut keeping = Vec::new();
|
||||||
|
let mut keeping_ports = Vec::new();
|
||||||
|
for (listener, port) in held.drain(..).zip(held_ports.drain(..)) {
|
||||||
|
match listener.accept() {
|
||||||
|
// The gate's probe: release the port.
|
||||||
|
Ok(_) => {}
|
||||||
|
Err(e) if e.kind() == std::io::ErrorKind::WouldBlock => {
|
||||||
|
keeping.push(listener);
|
||||||
|
keeping_ports.push(port);
|
||||||
|
}
|
||||||
|
Err(_) => {}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
held = keeping;
|
||||||
|
held_ports = keeping_ports;
|
||||||
|
std::thread::sleep(Duration::from_millis(10));
|
||||||
|
}
|
||||||
|
});
|
||||||
|
Self {
|
||||||
|
stop,
|
||||||
|
handle: Some(handle),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Drop for PublishedPortHold {
|
||||||
|
fn drop(&mut self) {
|
||||||
|
self.stop.store(true, Ordering::Relaxed);
|
||||||
|
if let Some(handle) = self.handle.take() {
|
||||||
|
let _ = handle.join();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn modified(log: &Path) -> Option<SystemTime> {
|
||||||
|
std::fs::metadata(log).ok()?.modified().ok()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The ports named after `--rpc-bind-port` in a fake child's argv log.
|
||||||
|
fn published_ports(log: &Path) -> Vec<u16> {
|
||||||
|
let Ok(raw) = std::fs::read_to_string(log) else {
|
||||||
|
return Vec::new();
|
||||||
|
};
|
||||||
|
raw.lines()
|
||||||
|
.collect::<Vec<&str>>()
|
||||||
|
.windows(2)
|
||||||
|
.filter(|pair| pair[0] == "--rpc-bind-port")
|
||||||
|
.filter_map(|pair| pair[1].trim().parse().ok())
|
||||||
|
.collect()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
|
||||||
Loading…
Reference in a new issue