-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathservice_checker.rs
More file actions
235 lines (215 loc) · 8.32 KB
/
Copy pathservice_checker.rs
File metadata and controls
235 lines (215 loc) · 8.32 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
//! SSH Service Checker
//!
//! This module provides functionality to check if SSH service is available on a remote host
//! without requiring authentication. It's designed for connectivity testing only - like a "ping"
//! for SSH services to verify that the SSH daemon is running and accepting connections.
//!
//! ## Key Features
//!
//! - Pure connectivity testing without authentication
//! - Minimal SSH command execution to test service availability
//! - Distinguishes between "service not available" and "service available but auth failed"
//! - Lightweight and focused on service discovery
//!
//! ## Usage
//!
//! ```rust,no_run
//! use std::net::{SocketAddr, IpAddr, Ipv4Addr};
//! use torrust_tracker_deployer_lib::adapters::ssh::SshServiceChecker;
//!
//! # fn main() -> Result<(), Box<dyn std::error::Error>> {
//! let checker = SshServiceChecker::new();
//! let socket_addr = SocketAddr::new(IpAddr::V4(Ipv4Addr::new(192, 168, 1, 1)), 22);
//! let is_available = checker.is_service_available(socket_addr)?;
//! if is_available {
//! println!("SSH service is available");
//! } else {
//! println!("SSH service is not available");
//! }
//! # Ok(())
//! # }
//! ```
use std::net::SocketAddr;
use std::process::Command;
use tracing::debug;
/// SSH Service availability checker errors
#[derive(Debug, thiserror::Error)]
pub enum SshServiceError {
/// Command execution failed (e.g., ssh binary not found, process interrupted)
#[error("Failed to execute SSH service check command: {source}")]
CommandExecutionFailed {
#[source]
source: std::io::Error,
},
}
/// Result type for SSH service operations
pub type Result<T> = std::result::Result<T, SshServiceError>;
/// SSH Service Checker for testing service availability
///
/// This checker performs lightweight connectivity tests to determine if an SSH daemon
/// is running and accepting connections on a given host and port. It does not attempt
/// to authenticate or establish a working SSH session.
///
/// The checker uses minimal SSH commands with short timeouts and batch mode to quickly
/// determine service availability without user interaction.
#[derive(Debug)]
pub struct SshServiceChecker {
/// Connection timeout in seconds for SSH attempts
connect_timeout: u16,
}
impl Default for SshServiceChecker {
fn default() -> Self {
Self::new()
}
}
impl SshServiceChecker {
/// Create a new SSH service checker with default settings
///
/// Default connection timeout is 5 seconds.
#[must_use]
pub fn new() -> Self {
Self { connect_timeout: 5 }
}
/// Create a new SSH service checker with custom connection timeout
///
/// # Arguments
/// * `connect_timeout` - Timeout in seconds for connection attempts
#[must_use]
pub fn with_timeout(connect_timeout: u16) -> Self {
Self { connect_timeout }
}
/// Check if SSH service is available at the specified socket address
///
/// This method attempts a minimal SSH connection to test service availability.
/// It distinguishes between:
/// - Service not available (connection refused, no route to host)
/// - Service available (authentication failures are considered as service available)
///
/// # Arguments
/// * `socket_addr` - The socket address (IP and port) to test
///
/// # Returns
/// * `Ok(true)` - SSH service is available and accepting connections
/// * `Ok(false)` - SSH service is not available or not reachable
/// * `Err(SshServiceError)` - Command execution error (e.g., ssh binary not found)
///
/// # Errors
/// Returns an error if the SSH command cannot be executed (e.g., ssh binary not found
/// or process was terminated by signal).
pub fn is_service_available(&self, socket_addr: SocketAddr) -> Result<bool> {
debug!(
socket_addr = %socket_addr,
timeout = self.connect_timeout,
"Testing SSH service availability"
);
let host = socket_addr.ip().to_string();
let port = socket_addr.port();
let output = Command::new("ssh")
.args([
"-o",
"StrictHostKeyChecking=no",
"-o",
"UserKnownHostsFile=/dev/null",
"-o",
&format!("ConnectTimeout={}", self.connect_timeout),
"-o",
"BatchMode=yes", // Non-interactive mode
"-p",
&port.to_string(),
&format!("test@{host}"),
"echo",
"connectivity_test",
])
.output()
.map_err(|source| SshServiceError::CommandExecutionFailed { source })?;
// Analyze the command result to determine service availability
match output.status.code() {
Some(0) => {
// SSH command succeeded - service is definitely available
debug!(
socket_addr = %socket_addr,
"SSH service available (command succeeded)"
);
Ok(true)
}
Some(255) => {
// Exit code 255 can indicate different scenarios
let stderr = String::from_utf8_lossy(&output.stderr);
if stderr.contains("Connection refused") || stderr.contains("No route to host") {
// Service is not available or host is not reachable
debug!(
socket_addr = %socket_addr,
error = %stderr.trim(),
"SSH service not available"
);
Ok(false)
} else {
// Authentication failed, permission denied, etc. - service is available
debug!(
socket_addr = %socket_addr,
error = %stderr.trim(),
"SSH service available (authentication failed)"
);
Ok(true)
}
}
Some(exit_code) => {
// Other non-zero exit codes typically indicate service is available
// but there are other issues (auth, command execution, etc.)
debug!(
socket_addr = %socket_addr,
exit_code = exit_code,
"SSH service available (non-zero exit code)"
);
Ok(true)
}
None => {
// Process was terminated by signal - treat as command execution error
Err(SshServiceError::CommandExecutionFailed {
source: std::io::Error::new(
std::io::ErrorKind::Interrupted,
"SSH process terminated by signal",
),
})
}
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn it_should_create_ssh_service_checker_with_defaults() {
let checker = SshServiceChecker::new();
assert_eq!(checker.connect_timeout, 5);
}
#[test]
fn it_should_create_ssh_service_checker_with_custom_timeout() {
let checker = SshServiceChecker::with_timeout(10);
assert_eq!(checker.connect_timeout, 10);
}
#[test]
fn it_should_implement_default_trait() {
let checker = SshServiceChecker::default();
assert_eq!(checker.connect_timeout, 5);
}
#[test]
fn it_should_have_proper_error_display() {
let io_error = std::io::Error::new(std::io::ErrorKind::NotFound, "ssh command not found");
let error = SshServiceError::CommandExecutionFailed { source: io_error };
assert!(error
.to_string()
.contains("Failed to execute SSH service check command"));
assert!(std::error::Error::source(&error).is_some());
}
#[test]
fn it_should_support_debug_formatting() {
let checker = SshServiceChecker::new();
let debug_str = format!("{checker:?}");
assert!(debug_str.contains("SshServiceChecker"));
assert!(debug_str.contains("connect_timeout"));
}
// Note: We don't include integration tests that actually connect to SSH services
// as they would be flaky and depend on external services. The actual connectivity
// testing logic is documented through these unit tests and the implementation.
}