Skip to content

Commit 022147d

Browse files
authored
feat: add direct ICMP network ping (#324)
## Summary - Add `network-ping` / `nping` for bounded direct-origin IPv4/IPv6 ICMP checks with resolver-order address selection, per-host loss and latency statistics, and 0/1/255 aggregate exits. - Honor ssh_config `HostName` and `AddressFamily`, including cluster aliases and scoped IPv6 destinations, without SSH authentication, ProxyJump/ProxyCommand transport, or silent TCP/HTTP fallback. - Preserve OpenSSH root `-c` (cipher) and `-W` (stdio forwarding): packet count and reply timeout are long-only `--count` and `--timeout`. - Use datagram-first shared sockets, bounded duplicate-target scheduling, explicit permission diagnostics, and normal formatter output; document Linux/macOS requirements and direct-origin semantics in English/Korean README guidance, the man page, and architecture notes. - Synchronize existing HOME-sensitive, macOS Keychain, and key-interaction-counter tests after full-suite validation exposed process-global test races. ## Validation - Full parallel library suite passed: 1,744 passed, 0 failed, 7 ignored. Common SSH config/address-family/ping-exit contracts and all 14 OpenSSH harness selftests passed. - Twelve focused network-ping/CLI tests and two dispatcher credential-applicability tests passed; targeted Clippy and formatting passed. - Actual macOS unprivileged IPv4 and IPv6 loopback ICMP smoke tests passed. Linux live ICMP behavior was not manually exercised here; GitHub CI remains a separate merge gate. Closes #75
1 parent a0b3470 commit 022147d

15 files changed

Lines changed: 1122 additions & 14 deletions

File tree

‎ARCHITECTURE.md‎

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -99,6 +99,14 @@ Tokio-based async executor for concurrent command execution:
9999
- Real-time progress visualization
100100
- Stream mode for live output
101101

102+
### Direct ICMP Network Ping
103+
104+
`commands/network_ping.rs` implements the bssh-only `network-ping` / `nping` health check. Unlike `ping`, it does not enter the SSH client or authentication path. Initialized `Node.host` values already contain ssh_config `HostName` expansion, while `Node::config_host()` retains the alias used to resolve the effective `AddressFamily`; bounded DNS selects the first resolver-order address matching that family and reports it with the result.
105+
106+
Hosts are scheduled through a `buffer_unordered` stream capped by the global `--parallel` value. IPv4 and IPv6 each lazily share one surge-ping client/socket, request sequences are bounded to `u16`, and each host paces its probes with a minimum 200 ms interval. Tests inject a `NetworkProbe` implementation so DNS, loss, timing, family selection, and concurrency remain deterministic without ICMP privileges.
107+
108+
The socket preference is unprivileged `SOCK_DGRAM`, with surge-ping's raw-socket fallback where the platform requires it. Permission failures remain visible and never trigger a TCP/HTTP fallback. ProxyJump and ProxyCommand are deliberately outside the data path because the echo request originates locally; the dispatcher suppresses SSH and sudo password collection and the command warns when a proxy setting would otherwise apply. Output is the normal formatter only, with per-host received/sent and min/avg/max/population-standard-deviation plus aggregate reachability and the mean of reachable per-host averages.
109+
102110
### SSH Client
103111
**Documentation**: [docs/architecture/ssh-client.md](./docs/architecture/ssh-client.md)
104112

‎Cargo.lock‎

Lines changed: 65 additions & 0 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

‎Cargo.toml‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -95,6 +95,7 @@ opentelemetry-otlp = { version = "0.32", features = ["grpc-tonic", "logs"] }
9595
url = "2.5"
9696
tokio-rustls = "0.26"
9797
rustls-native-certs = "0.8"
98+
surge-ping = "0.9.1"
9899

99100
[target.'cfg(target_os = "macos")'.dependencies]
100101
security-framework = "3.7.0"

‎README.md‎

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -540,6 +540,10 @@ pdsh -w node1,node2,backup1,backup2 -x "*backup*" -q
540540
bssh --cluster production ping
541541
bssh -H "host1,host2" ping
542542

543+
# Test direct ICMP reachability (alias: nping)
544+
bssh --cluster production network-ping
545+
bssh -6 -H "host1,host2" network-ping --count 10 --timeout 1 --interval 0.5
546+
543547
# List configured clusters
544548
bssh list
545549

@@ -552,6 +556,20 @@ bssh --cluster production upload local.txt /tmp/
552556
bssh -H "host1,host2" download /etc/hosts ./backups/
553557
```
554558

559+
#### Direct ICMP network ping
560+
561+
`network-ping` (alias `nping`) measures direct ICMP reachability without logging in over SSH. It sends four requests per host by default, waits up to two seconds per reply, spaces requests by at least 0.2 seconds, uses the global `--parallel` limit, and reports the selected IP plus received/sent, loss, and min/avg/max/population-stddev statistics. `--count` and `--timeout` are intentionally long-only because OpenSSH-compatible root `-c` and `-W` remain the cipher and stdio-forward options; `--interval` is long-only.
562+
563+
Host aliases are expanded through ssh_config `HostName`, and the first resolver-order address allowed by `-4`, `-6`, or `AddressFamily` is probed and shown. ICMP originates on the local machine: `ProxyJump`, `ProxyCommand`, SSH authentication, TUI/stream output, and output directories are not used. The command never silently falls back to TCP or HTTP, so success proves only that the selected address replied to ICMP; failure can also mean that ICMP is filtered.
564+
565+
The command prefers unprivileged ICMP datagram sockets. Linux installations may need an appropriate `net.ipv4.ping_group_range` for the process group or `CAP_NET_RAW` if datagram sockets are restricted; macOS normally permits ping sockets without elevation. Socket permission failures are reported explicitly. Exit status is 0 when every host answers at least once, 1 for mixed reachability, and 255 when none answers or setup fails; command-line parse errors retain clap's exit status 2.
566+
567+
#### 직접 ICMP 네트워크 핑
568+
569+
`network-ping`(`nping`)은 SSH 로그인 없이 로컬 머신에서 대상 주소로 ICMP echo를 직접 전송합니다. 기본값은 호스트당 4회, 응답별 제한 시간 2초, 전송 간격 0.2초이며 전역 `--parallel` 제한을 사용합니다. 선택된 IP, 수신/송신 수, 손실률, min/avg/max/모집단 표준편차를 출력합니다. OpenSSH 호환 루트 `-c`와 `-W`는 각각 cipher와 stdio-forward 의미를 유지하므로 요청 횟수와 제한 시간은 긴 옵션 `--count`, `--timeout`만 제공합니다.
570+
571+
ssh_config의 `HostName` 별칭을 적용하고 `-4`, `-6`, `AddressFamily`에 맞는 DNS 결과 중 resolver 순서상 첫 주소를 사용합니다. `ProxyJump`와 `ProxyCommand`는 ICMP를 중계하지 않으며 TCP/HTTP로 자동 대체하지 않습니다. 따라서 성공은 선택한 주소의 제한적인 ICMP 응답만 의미하고, 실패는 방화벽의 ICMP 차단 때문일 수도 있습니다. 권한 없이 사용할 수 있는 ICMP 데이터그램 소켓을 우선 사용하며, Linux에서 제한된 경우 프로세스 그룹에 맞는 `net.ipv4.ping_group_range` 또는 `CAP_NET_RAW`가 필요할 수 있습니다. macOS에서는 일반적으로 별도의 권한 없이 ping 소켓을 사용할 수 있고, 소켓 권한 오류는 명시적으로 보고합니다. 종료 코드는 전체 응답 0, 일부 응답 1, 전부 미응답 또는 준비 실패 255이며 인자 파싱 오류는 2입니다.
572+
555573
## Exit Code Strategies
556574

557575
By default, bssh returns the main rank's exit code, matching MPI-oriented

‎docs/man/bssh.1‎

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -439,6 +439,21 @@ List available clusters from configuration
439439
.B ping
440440
Test connectivity to hosts
441441

442+
.TP
443+
.B network-ping, nping
444+
Test direct ICMP reachability without opening an SSH connection.
445+
.RS
446+
Usage: bssh [global options] network-ping [\fB--count\fR \fICOUNT\fR] [\fB--timeout\fR \fISECONDS\fR] [\fB--interval\fR \fISECONDS\fR]
447+
.br
448+
The defaults are 4 requests, a 2 second per-request reply timeout, and a 0.2 second interval. The interval cannot be less than 0.2 seconds. The global \fB--parallel\fR limit controls host concurrency.
449+
.br
450+
The count and timeout options are deliberately long-only because the OpenSSH-compatible root \fB-c\fR and \fB-W\fR options keep their cipher and stdio-forward meanings. The command uses normal output only; TUI, stream, and output-directory modes do not apply.
451+
.br
452+
ssh_config HostName aliases are expanded, then the first resolver-order address allowed by \fB-4\fR, \fB-6\fR, or AddressFamily is selected and reported. ICMP originates directly from the local machine, so ProxyJump and ProxyCommand are ignored with a warning. There is no TCP or HTTP fallback.
453+
.br
454+
Unprivileged ICMP datagram sockets are preferred. Restricted Linux systems may require a suitable ping_group_range or CAP_NET_RAW; macOS normally permits ping sockets without elevation. Permission failures are reported explicitly.
455+
.RE
456+
442457
.TP
443458
.B upload
444459
Upload files to remote hosts using SFTP (supports glob patterns)
@@ -1977,6 +1992,26 @@ Command-line usage errors are rejected by the argument parser before this
19771992
contract applies and keep the parser's own exit code 2, as they do for every
19781993
subcommand.
19791994

1995+
.SS network-ping Subcommand
1996+
The
1997+
.BR network-ping
1998+
subcommand reports direct ICMP reachability rather than SSH service or authentication health. A host counts as reachable after at least one echo reply. Packet loss is calculated as lost requests divided by sent requests (for example, 3 replies from 4 requests is 25% loss), and latency uses min/avg/max/population-standard-deviation. Its exit codes are:
1999+
2000+
.TP
2001+
.B 0
2002+
Every targeted host answered at least once
2003+
2004+
.TP
2005+
.B 1
2006+
At least one host answered and at least one did not
2007+
2008+
.TP
2009+
.B 255
2010+
No host answered, or bssh failed during DNS or ICMP socket setup
2011+
2012+
.PP
2013+
Argument parser failures, including zero count/timeout/parallel, parallelism above 4096, a non-finite duration, an interval below 0.2 seconds, or a duration above 3600 seconds, retain exit status 2.
2014+
19802015
.SH OUTPUT FILES
19812016
When using the
19822017
.B --output-dir

‎src/app/dispatcher.rs‎

Lines changed: 41 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,7 @@ use bssh::{
2222
exec::{ExecuteCommandParams, execute_command},
2323
interactive::InteractiveCommand,
2424
list::list_clusters,
25+
network_ping::network_ping_nodes,
2526
ping::ping_nodes,
2627
upload::{FileTransferParams, upload_file},
2728
},
@@ -574,6 +575,7 @@ async fn wait_for_no_session_transport(client: &bssh::ssh::tokio_client::Client)
574575
fn sudo_password_is_applicable(command: &Option<Commands>, command_text: &str) -> bool {
575576
match command {
576577
Some(Commands::Ping)
578+
| Some(Commands::NetworkPing { .. })
577579
| Some(Commands::Upload { .. })
578580
| Some(Commands::Download { .. })
579581
| Some(Commands::List)
@@ -595,7 +597,9 @@ fn sudo_password_is_applicable(command: &Option<Commands>, command_text: &str) -
595597
fn ssh_password_is_applicable(command: &Option<Commands>) -> bool {
596598
!matches!(
597599
command,
598-
Some(Commands::List) | Some(Commands::CacheStats { .. })
600+
Some(Commands::List)
601+
| Some(Commands::NetworkPing { .. })
602+
| Some(Commands::CacheStats { .. })
599603
)
600604
}
601605

@@ -643,6 +647,7 @@ fn subcommand_name(command: &Option<Commands>) -> &'static str {
643647
match command {
644648
Some(Commands::List) => "list",
645649
Some(Commands::Ping) => "ping",
650+
Some(Commands::NetworkPing { .. }) => "network-ping",
646651
Some(Commands::Upload { .. }) => "upload",
647652
Some(Commands::Download { .. }) => "download",
648653
Some(Commands::Interactive { .. }) => "interactive",
@@ -830,9 +835,8 @@ pub async fn dispatch_command_with_background(
830835
ctx.cluster_name.as_deref().or(cli.cluster.as_deref()),
831836
);
832837

833-
// `ping` is the one subcommand whose exit code depends on how many
834-
// hosts answered, so the outcome is translated here rather than
835-
// discarded. See `PingOutcome` for the 0/1/255 contract.
838+
// Connectivity subcommands return an outcome so the dispatcher can
839+
// preserve their 0/1/255 aggregate contract.
836840
let outcome = ping_nodes(
837841
ctx.nodes.clone(),
838842
ctx.max_parallel,
@@ -852,6 +856,26 @@ pub async fn dispatch_command_with_background(
852856

853857
Ok(outcome.exit_code())
854858
}
859+
Some(Commands::NetworkPing {
860+
count,
861+
timeout,
862+
interval,
863+
}) => {
864+
let outcome = network_ping_nodes(
865+
ctx.nodes.clone(),
866+
*count,
867+
Duration::from_secs_f64(*timeout),
868+
Duration::from_secs_f64(*interval),
869+
ctx.max_parallel,
870+
build_ssh_connection_config_resolver(
871+
cli,
872+
ctx,
873+
ctx.cluster_name.as_deref().or(cli.cluster.as_deref()),
874+
),
875+
)
876+
.await?;
877+
Ok(outcome.exit_code())
878+
}
855879
Some(Commands::Upload {
856880
source,
857881
destination,
@@ -1466,6 +1490,14 @@ mod tests {
14661490

14671491
assert!(!sudo_password_is_applicable(&None, ""));
14681492
assert!(!sudo_password_is_applicable(&Some(Commands::Ping), "true"));
1493+
assert!(!sudo_password_is_applicable(
1494+
&Some(Commands::NetworkPing {
1495+
count: 1,
1496+
timeout: 1.0,
1497+
interval: 0.2,
1498+
}),
1499+
"",
1500+
));
14691501
assert!(!sudo_password_is_applicable(&interactive_command(), ""));
14701502
assert!(!sudo_password_is_applicable(
14711503
&Some(Commands::CacheStats {
@@ -1484,6 +1516,11 @@ mod tests {
14841516
assert!(ssh_password_is_applicable(&interactive_command()));
14851517

14861518
assert!(!ssh_password_is_applicable(&Some(Commands::List)));
1519+
assert!(!ssh_password_is_applicable(&Some(Commands::NetworkPing {
1520+
count: 1,
1521+
timeout: 1.0,
1522+
interval: 0.2,
1523+
})));
14871524
assert!(!ssh_password_is_applicable(&Some(Commands::CacheStats {
14881525
detailed: false,
14891526
clear: false,

0 commit comments

Comments
 (0)