forked from torrust/torrust-tracker
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.rs
More file actions
347 lines (287 loc) · 12 KB
/
server.rs
File metadata and controls
347 lines (287 loc) · 12 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
//! Module to handle the HTTP server instances.
use std::net::SocketAddr;
use std::sync::Arc;
use axum_server::tls_rustls::RustlsConfig;
use axum_server::Handle;
use bittorrent_http_tracker_core::container::HttpTrackerCoreContainer;
use derive_more::Constructor;
use futures::future::BoxFuture;
use tokio::sync::oneshot::{Receiver, Sender};
use torrust_axum_server::custom_axum_server::{self, TimeoutAcceptor};
use torrust_axum_server::signals::graceful_shutdown;
use torrust_server_lib::logging::STARTED_ON;
use torrust_server_lib::registar::{ServiceHealthCheckJob, ServiceRegistration, ServiceRegistrationForm};
use torrust_server_lib::signals::{Halted, Started};
use torrust_tracker_primitives::service_binding::{Protocol, ServiceBinding};
use tracing::instrument;
use super::v1::routes::router;
use crate::HTTP_TRACKER_LOG_TARGET;
const TYPE_STRING: &str = "http_tracker";
/// Error that can occur when starting or stopping the HTTP server.
///
/// Some errors triggered while starting the server are:
///
/// - The spawned server cannot send its `SocketAddr` back to the main thread.
/// - The launcher cannot receive the `SocketAddr` from the spawned server.
///
/// Some errors triggered while stopping the server are:
///
/// - The channel to send the shutdown signal to the server is closed.
/// - The task to shutdown the server on the spawned server failed to execute to
/// completion.
#[derive(Debug)]
pub enum Error {
Error(String),
}
#[derive(Constructor, Debug)]
pub struct Launcher {
pub bind_to: SocketAddr,
pub tls: Option<RustlsConfig>,
}
impl Launcher {
#[instrument(skip(self, http_tracker_container, tx_start, rx_halt))]
fn start(
&self,
http_tracker_container: Arc<HttpTrackerCoreContainer>,
tx_start: Sender<Started>,
rx_halt: Receiver<Halted>,
) -> BoxFuture<'static, ()> {
let socket = std::net::TcpListener::bind(self.bind_to).expect("Could not bind tcp_listener to address.");
let address = socket.local_addr().expect("Could not get local_addr from tcp_listener.");
let handle = Handle::new();
tokio::task::spawn(graceful_shutdown(
handle.clone(),
rx_halt,
format!("Shutting down HTTP server on socket address: {address}"),
));
let tls = self.tls.clone();
let protocol = if tls.is_some() { Protocol::HTTPS } else { Protocol::HTTP };
let service_binding = ServiceBinding::new(protocol.clone(), address).expect("Service binding creation failed");
tracing::info!(target: HTTP_TRACKER_LOG_TARGET, "Starting on: {protocol}://{address}");
let app = router(http_tracker_container, service_binding.clone());
let running = Box::pin(async {
match tls {
Some(tls) => custom_axum_server::from_tcp_rustls_with_timeouts(socket, tls)
.handle(handle)
// The TimeoutAcceptor is commented because TSL does not work with it.
// See: https://github.com/torrust/torrust-index/issues/204#issuecomment-2115529214
//.acceptor(TimeoutAcceptor)
.serve(app.into_make_service_with_connect_info::<std::net::SocketAddr>())
.await
.expect("Axum server crashed."),
None => custom_axum_server::from_tcp_with_timeouts(socket)
.handle(handle)
.acceptor(TimeoutAcceptor)
.serve(app.into_make_service_with_connect_info::<std::net::SocketAddr>())
.await
.expect("Axum server crashed."),
}
});
tracing::info!(target: HTTP_TRACKER_LOG_TARGET, "{STARTED_ON}: {protocol}://{}", address);
tx_start
.send(Started {
service_binding,
address,
})
.expect("the HTTP(s) Tracker service should not be dropped");
running
}
}
/// A HTTP server instance controller with no HTTP instance running.
#[allow(clippy::module_name_repetitions)]
pub type StoppedHttpServer = HttpServer<Stopped>;
/// A HTTP server instance controller with a running HTTP instance.
#[allow(clippy::module_name_repetitions)]
pub type RunningHttpServer = HttpServer<Running>;
/// A HTTP server instance controller.
///
/// It's responsible for:
///
/// - Keeping the initial configuration of the server.
/// - Starting and stopping the server.
/// - Keeping the state of the server: `running` or `stopped`.
///
/// It's an state machine. Configurations cannot be changed. This struct
/// represents concrete configuration and state. It allows to start and stop the
/// server but always keeping the same configuration.
///
/// > **NOTICE**: if the configurations changes after running the server it will
/// > reset to the initial value after stopping the server. This struct is not
/// > intended to persist configurations between runs.
#[allow(clippy::module_name_repetitions)]
pub struct HttpServer<S> {
/// The state of the server: `running` or `stopped`.
pub state: S,
}
/// A stopped HTTP server state.
pub struct Stopped {
launcher: Launcher,
}
/// A running HTTP server state.
pub struct Running {
/// The address where the server is bound.
pub binding: SocketAddr,
pub halt_task: tokio::sync::oneshot::Sender<Halted>,
pub task: tokio::task::JoinHandle<Launcher>,
}
impl HttpServer<Stopped> {
/// It creates a new `HttpServer` controller in `stopped` state.
#[must_use]
pub fn new(launcher: Launcher) -> Self {
Self {
state: Stopped { launcher },
}
}
/// It starts the server and returns a `HttpServer` controller in `running`
/// state.
///
/// # Errors
///
/// It would return an error if no `SocketAddr` is returned after launching the server.
///
/// # Panics
///
/// It would panic spawned HTTP server launcher cannot send the bound `SocketAddr`
/// back to the main thread.
pub async fn start(
self,
http_tracker_container: Arc<HttpTrackerCoreContainer>,
form: ServiceRegistrationForm,
) -> Result<HttpServer<Running>, Error> {
let (tx_start, rx_start) = tokio::sync::oneshot::channel::<Started>();
let (tx_halt, rx_halt) = tokio::sync::oneshot::channel::<Halted>();
let launcher = self.state.launcher;
let task = tokio::spawn(async move {
let server = launcher.start(http_tracker_container, tx_start, rx_halt);
server.await;
launcher
});
let started = rx_start.await.expect("it should be able to start the service");
let listen_url = started.service_binding;
let binding = started.address;
form.send(ServiceRegistration::new(listen_url, check_fn))
.expect("it should be able to send service registration");
Ok(HttpServer {
state: Running {
binding,
halt_task: tx_halt,
task,
},
})
}
}
impl HttpServer<Running> {
/// It stops the server and returns a `HttpServer` controller in `stopped`
/// state.
///
/// # Errors
///
/// It would return an error if the channel for the task killer signal was closed.
pub async fn stop(self) -> Result<HttpServer<Stopped>, Error> {
self.state
.halt_task
.send(Halted::Normal)
.map_err(|_| Error::Error("Task killer channel was closed.".to_string()))?;
let launcher = self.state.task.await.map_err(|e| Error::Error(e.to_string()))?;
Ok(HttpServer {
state: Stopped { launcher },
})
}
}
/// Checks the Health by connecting to the HTTP tracker endpoint.
///
/// # Errors
///
/// This function will return an error if unable to connect.
/// Or if the request returns an error.
#[must_use]
pub fn check_fn(service_binding: &ServiceBinding) -> ServiceHealthCheckJob {
let url = format!("http://{}/health_check", service_binding.bind_address()); // DevSkim: ignore DS137138
let info = format!("checking http tracker health check at: {url}");
let job = tokio::spawn(async move {
match reqwest::get(url).await {
Ok(response) => Ok(response.status().to_string()),
Err(err) => Err(err.to_string()),
}
});
ServiceHealthCheckJob::new(service_binding.clone(), info, TYPE_STRING.to_string(), job)
}
#[cfg(test)]
mod tests {
use std::sync::Arc;
use bittorrent_http_tracker_core::container::HttpTrackerCoreContainer;
use bittorrent_http_tracker_core::services::announce::AnnounceService;
use bittorrent_http_tracker_core::services::scrape::ScrapeService;
use bittorrent_tracker_core::container::TrackerCoreContainer;
use torrust_axum_server::tsl::make_rust_tls;
use torrust_server_lib::registar::Registar;
use torrust_tracker_configuration::{logging, Configuration};
use torrust_tracker_test_helpers::configuration::ephemeral_public;
use crate::server::{HttpServer, Launcher};
pub fn initialize_container(configuration: &Configuration) -> HttpTrackerCoreContainer {
let core_config = Arc::new(configuration.core.clone());
let http_trackers = configuration
.http_trackers
.clone()
.expect("missing HTTP trackers configuration");
let http_tracker_config = &http_trackers[0];
let http_tracker_config = Arc::new(http_tracker_config.clone());
// HTTP stats
let (http_stats_event_sender, http_stats_repository) =
bittorrent_http_tracker_core::statistics::setup::factory(configuration.core.tracker_usage_statistics);
let http_stats_event_sender = Arc::new(http_stats_event_sender);
let http_stats_repository = Arc::new(http_stats_repository);
let tracker_core_container = Arc::new(TrackerCoreContainer::initialize(&core_config));
let announce_service = Arc::new(AnnounceService::new(
tracker_core_container.core_config.clone(),
tracker_core_container.announce_handler.clone(),
tracker_core_container.authentication_service.clone(),
tracker_core_container.whitelist_authorization.clone(),
http_stats_event_sender.clone(),
));
let scrape_service = Arc::new(ScrapeService::new(
tracker_core_container.core_config.clone(),
tracker_core_container.scrape_handler.clone(),
tracker_core_container.authentication_service.clone(),
http_stats_event_sender.clone(),
));
HttpTrackerCoreContainer {
tracker_core_container,
http_tracker_config,
http_stats_event_sender,
http_stats_repository,
announce_service,
scrape_service,
}
}
fn initialize_global_services(configuration: &Configuration) {
initialize_static();
logging::setup(&configuration.logging);
}
fn initialize_static() {
torrust_tracker_clock::initialize_static();
}
#[tokio::test]
async fn it_should_be_able_to_start_and_stop() {
let configuration = Arc::new(ephemeral_public());
let http_trackers = configuration
.http_trackers
.clone()
.expect("missing HTTP trackers configuration");
let http_tracker_config = &http_trackers[0];
initialize_global_services(&configuration);
let http_tracker_container = Arc::new(initialize_container(&configuration));
let bind_to = http_tracker_config.bind_address;
let tls = make_rust_tls(&http_tracker_config.tsl_config)
.await
.map(|tls| tls.expect("tls config failed"));
let register = &Registar::default();
let stopped = HttpServer::new(Launcher::new(bind_to, tls));
let started = stopped
.start(http_tracker_container, register.give_form())
.await
.expect("it should start the server");
let stopped = started.stop().await.expect("it should stop the server");
assert_eq!(stopped.state.launcher.bind_to, bind_to);
}
}