-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathrunning_services.rs
More file actions
372 lines (323 loc) · 13.4 KB
/
Copy pathrunning_services.rs
File metadata and controls
372 lines (323 loc) · 13.4 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
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
//! Running services external validation
//!
//! This module provides the `RunningServicesValidator` which performs **end-to-end validation
//! from OUTSIDE the VM** to verify that Docker Compose services are running and accessible
//! after the `run` command has executed the deployment.
//!
//! ## Execution Context: External Validation
//!
//! **Why this validator is in `external_validators/` instead of `remote_actions/`**:
//!
//! This validator runs from the **test runner or deployment machine** and makes HTTP requests
//! to services **from outside the VM**, unlike validators in `remote_actions/` which execute
//! commands **inside the VM via SSH**.
//!
//! **Comparison**:
//! - `remote_actions/validators/docker.rs` - Executes `docker --version` inside VM via SSH
//! - `external_validators/running_services.rs` - Makes HTTP GET to `http://<vm-ip>:1212/health` from outside
//!
//! This distinction is crucial for understanding the validation scope:
//! - **Remote actions**: Validate internal VM state and configuration
//! - **External validators**: Validate end-to-end accessibility including network and firewall
//!
//! ## HTTPS Support
//!
//! When services have TLS enabled via Caddy reverse proxy:
//! - The validator uses HTTPS URLs with the configured domain
//! - Domains are resolved locally to the VM IP (no DNS dependency)
//! - Self-signed certificates are accepted for `.local` domains
//!
//! This approach allows testing to work without DNS configuration while still
//! being realistic (Caddy receives the correct SNI/Host header).
//!
//! ## Current Scope (Torrust Tracker)
//!
//! This validator performs external validation only (from test runner to VM):
//! - Tests tracker API health endpoint: HTTP or HTTPS depending on TLS config
//! - Tests HTTP tracker health endpoint: HTTP or HTTPS depending on TLS config
//!
//! **Validation Philosophy**: External checks are a superset of internal checks.
//! If external validation passes, it proves:
//! - Services are running inside the VM
//! - Firewall rules are configured correctly (port 80/443 for TLS, or service port for HTTP)
//! - Services are accessible from outside the VM
//! - TLS termination is working correctly (when enabled)
use std::net::IpAddr;
use std::path::PathBuf;
use std::time::Duration;
use reqwest::ClientBuilder;
use tracing::{info, instrument, warn};
use super::service_endpoint::ServiceEndpoint;
use crate::infrastructure::remote_actions::{RemoteAction, RemoteActionError};
/// Default deployment directory for Docker Compose files
const DEFAULT_DEPLOY_DIR: &str = "/opt/torrust";
/// HTTP client request timeout
const REQUEST_TIMEOUT_SECS: u64 = 10;
/// Action that validates Docker Compose services are running and healthy
///
/// Supports both HTTP and HTTPS endpoints. For HTTPS endpoints:
/// - Uses domain-based URLs with the configured domain
/// - Resolves domain to IP locally (no DNS dependency for testing)
/// - Accepts self-signed certificates for `.local` domains
pub struct RunningServicesValidator {
deploy_dir: PathBuf,
tracker_api_endpoint: ServiceEndpoint,
http_tracker_endpoints: Vec<ServiceEndpoint>,
}
impl RunningServicesValidator {
/// Create a new `RunningServicesValidator` with service endpoints
///
/// Uses the default deployment directory `/opt/torrust`.
///
/// # Arguments
/// * `tracker_api_endpoint` - Endpoint for the tracker API health check
/// * `http_tracker_endpoints` - Endpoints for HTTP tracker health checks
#[must_use]
pub fn new(
tracker_api_endpoint: ServiceEndpoint,
http_tracker_endpoints: Vec<ServiceEndpoint>,
) -> Self {
Self {
deploy_dir: PathBuf::from(DEFAULT_DEPLOY_DIR),
tracker_api_endpoint,
http_tracker_endpoints,
}
}
/// Create a new `RunningServicesValidator` with a custom deployment directory
///
/// # Arguments
/// * `deploy_dir` - Path to the directory containing docker-compose.yml on the remote host
/// * `tracker_api_endpoint` - Endpoint for the tracker API health check
/// * `http_tracker_endpoints` - Endpoints for HTTP tracker health checks
#[must_use]
pub fn with_deploy_dir(
deploy_dir: PathBuf,
tracker_api_endpoint: ServiceEndpoint,
http_tracker_endpoints: Vec<ServiceEndpoint>,
) -> Self {
Self {
deploy_dir,
tracker_api_endpoint,
http_tracker_endpoints,
}
}
/// Validate external accessibility of all configured endpoints
async fn validate_external_accessibility(&self) -> Result<(), RemoteActionError> {
// Check tracker API (required)
self.check_endpoint(&self.tracker_api_endpoint, "Tracker API")
.await?;
// Check all HTTP trackers
for (idx, endpoint) in self.http_tracker_endpoints.iter().enumerate() {
let name = format!("HTTP Tracker {}", idx + 1);
self.check_endpoint(endpoint, &name).await?;
}
Ok(())
}
/// Check a service endpoint for accessibility
///
/// Handles both HTTP and HTTPS endpoints. For HTTPS:
/// - Resolves domain to IP locally using reqwest's resolve feature
/// - Accepts self-signed certs for `.local` domains
async fn check_endpoint(
&self,
endpoint: &ServiceEndpoint,
service_name: &str,
) -> Result<(), RemoteActionError> {
let url = endpoint.url();
if endpoint.uses_tls() {
info!(
action = "running_services_validation",
check = "service_external",
service = service_name,
url = %url,
domain = ?endpoint.domain(),
resolve_to = %endpoint.server_ip(),
"Testing HTTPS endpoint (resolving domain to IP locally)"
);
} else {
info!(
action = "running_services_validation",
check = "service_external",
service = service_name,
url = %url,
"Testing HTTP endpoint"
);
}
let response = self.make_request(endpoint).await?;
if !response.status().is_success() {
return Err(RemoteActionError::ValidationFailed {
action_name: self.name().to_string(),
message: format!(
"{service_name} returned HTTP {}: {}. Service may not be healthy.",
response.status(),
response.status().canonical_reason().unwrap_or("Unknown")
),
});
}
info!(
action = "running_services_validation",
check = "service_external",
service = service_name,
url = %url,
status = "success",
"{service_name} health check passed"
);
Ok(())
}
/// Make an HTTP/HTTPS request to the endpoint
///
/// For HTTPS endpoints, this:
/// - Uses reqwest's `resolve()` to map domain to IP (like curl --resolve)
/// - Accepts self-signed certificates for `.local` domains
async fn make_request(
&self,
endpoint: &ServiceEndpoint,
) -> Result<reqwest::Response, RemoteActionError> {
let url = endpoint.url();
let mut client_builder =
ClientBuilder::new().timeout(Duration::from_secs(REQUEST_TIMEOUT_SECS));
// For HTTPS endpoints, configure domain resolution and certificate handling
if let Some(domain) = endpoint.domain() {
// Resolve domain to IP locally (like curl --resolve)
client_builder = client_builder.resolve(domain, endpoint.socket_addr());
// Accept self-signed certs for .local domains (Caddy's internal CA)
if endpoint.is_local_domain() {
warn!(
action = "running_services_validation",
domain = domain,
"Accepting self-signed certificates for .local domain"
);
client_builder = client_builder.danger_accept_invalid_certs(true);
}
}
let client = client_builder
.build()
.map_err(|e| RemoteActionError::ValidationFailed {
action_name: self.name().to_string(),
message: format!("Failed to build HTTP client: {e}"),
})?;
client.get(url.clone()).send().await.map_err(|e| {
let help_message = if endpoint.uses_tls() {
format!(
"HTTPS request to '{url}' failed: {e}. \
Check that Caddy is running and port 443 is open. \
Domain '{}' was resolved to {} for testing.",
endpoint.domain().unwrap_or("unknown"),
endpoint.server_ip()
)
} else {
format!(
"HTTP request to '{url}' failed: {e}. \
Check that service is running and firewall allows port {}.",
endpoint.port()
)
};
RemoteActionError::ValidationFailed {
action_name: self.name().to_string(),
message: help_message,
}
})
}
}
impl RemoteAction for RunningServicesValidator {
fn name(&self) -> &'static str {
"running-services-validation"
}
#[instrument(
name = "running_services_validation",
skip(self),
fields(
action_type = "validation",
component = "running_services",
server_ip = %server_ip,
deploy_dir = %self.deploy_dir.display()
)
)]
async fn execute(&self, server_ip: &IpAddr) -> Result<(), RemoteActionError> {
// Note: server_ip parameter is kept for trait compatibility and logging,
// but endpoints now contain their own server_ip for URL generation.
let _ = server_ip; // Suppress unused warning - used in instrument macro
info!(
action = "running_services_validation",
deploy_dir = %self.deploy_dir.display(),
"Validating Docker Compose services are running via external accessibility"
);
self.validate_external_accessibility().await?;
info!(
action = "running_services_validation",
status = "success",
"Running services validation completed successfully"
);
Ok(())
}
}
#[cfg(test)]
mod tests {
use std::net::{IpAddr, SocketAddr};
use std::path::PathBuf;
use crate::shared::DomainName;
use super::*;
fn test_ip() -> IpAddr {
"10.0.0.1".parse().unwrap()
}
fn test_socket_addr(port: u16) -> SocketAddr {
SocketAddr::new(test_ip(), port)
}
#[test]
fn it_should_use_default_deploy_dir_when_not_specified() {
assert_eq!(DEFAULT_DEPLOY_DIR, "/opt/torrust");
}
#[test]
fn it_should_return_correct_action_name_when_queried() {
assert_eq!("running-services-validation", "running-services-validation");
}
#[test]
fn it_should_create_validator_with_http_endpoints() {
let api_endpoint =
ServiceEndpoint::http(test_socket_addr(1212), "/api/health_check").unwrap();
let tracker_endpoints =
vec![ServiceEndpoint::http(test_socket_addr(7070), "/health_check").unwrap()];
let validator = RunningServicesValidator::new(api_endpoint.clone(), tracker_endpoints);
assert_eq!(validator.tracker_api_endpoint, api_endpoint);
assert_eq!(validator.http_tracker_endpoints.len(), 1);
}
#[test]
fn it_should_create_validator_with_https_endpoints() {
let domain = DomainName::new("api.tracker.local").unwrap();
let api_endpoint = ServiceEndpoint::https(&domain, "/api/health_check", test_ip()).unwrap();
let tracker_endpoints = vec![];
let validator = RunningServicesValidator::new(api_endpoint.clone(), tracker_endpoints);
assert!(validator.tracker_api_endpoint.uses_tls());
}
#[test]
fn it_should_create_validator_with_mixed_endpoints() {
let domain = DomainName::new("api.tracker.local").unwrap();
let api_endpoint = ServiceEndpoint::https(&domain, "/api/health_check", test_ip()).unwrap();
let tracker_endpoints = vec![
ServiceEndpoint::http(test_socket_addr(7070), "/health_check").unwrap(),
ServiceEndpoint::http(test_socket_addr(7071), "/health_check").unwrap(),
];
let validator = RunningServicesValidator::new(api_endpoint, tracker_endpoints);
assert!(validator.tracker_api_endpoint.uses_tls());
assert!(!validator.http_tracker_endpoints[0].uses_tls());
assert!(!validator.http_tracker_endpoints[1].uses_tls());
}
#[test]
fn it_should_accept_empty_tracker_endpoints() {
let api_endpoint =
ServiceEndpoint::http(test_socket_addr(1212), "/api/health_check").unwrap();
let validator = RunningServicesValidator::new(api_endpoint, vec![]);
assert_eq!(validator.http_tracker_endpoints.len(), 0);
}
#[test]
fn it_should_use_custom_deploy_dir() {
let api_endpoint =
ServiceEndpoint::http(test_socket_addr(1212), "/api/health_check").unwrap();
let validator = RunningServicesValidator::with_deploy_dir(
PathBuf::from("/custom/path"),
api_endpoint,
vec![],
);
assert_eq!(validator.deploy_dir, PathBuf::from("/custom/path"));
}
}