forked from torrust/torrust-tracker
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlauncher.rs
More file actions
253 lines (205 loc) · 10.7 KB
/
launcher.rs
File metadata and controls
253 lines (205 loc) · 10.7 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
use std::net::SocketAddr;
use std::sync::Arc;
use std::time::Duration;
use bittorrent_tracker_client::udp::client::check;
use bittorrent_udp_tracker_core::container::UdpTrackerCoreContainer;
use bittorrent_udp_tracker_core::{self, UDP_TRACKER_LOG_TARGET};
use derive_more::Constructor;
use futures_util::StreamExt;
use tokio::select;
use tokio::sync::oneshot;
use tokio::time::interval;
use torrust_server_lib::logging::STARTED_ON;
use torrust_server_lib::registar::ServiceHealthCheckJob;
use torrust_server_lib::signals::{shutdown_signal_with_message, Halted, Started};
use torrust_tracker_primitives::service_binding::{Protocol, ServiceBinding};
use tracing::instrument;
use super::request_buffer::ActiveRequests;
use crate::container::UdpTrackerServerContainer;
use crate::event::{ConnectionContext, Event};
use crate::server::bound_socket::BoundSocket;
use crate::server::processor::Processor;
use crate::server::receiver::Receiver;
const IP_BANS_RESET_INTERVAL_IN_SECS: u64 = 3600 * 24;
const TYPE_STRING: &str = "udp_tracker";
/// A UDP server instance launcher.
#[derive(Constructor)]
pub struct Launcher;
impl Launcher {
/// It starts the UDP server instance with graceful shutdown.
///
/// # Panics
///
/// It panics if unable to bind to udp socket, and get the address from the udp socket.
/// It panics if unable to send address of socket.
/// It panics if the udp server is loaded when the tracker is private.
#[instrument(skip(udp_tracker_core_container, udp_tracker_server_container, bind_to, tx_start, rx_halt))]
pub async fn run_with_graceful_shutdown(
udp_tracker_core_container: Arc<UdpTrackerCoreContainer>,
udp_tracker_server_container: Arc<UdpTrackerServerContainer>,
bind_to: SocketAddr,
cookie_lifetime: Duration,
tx_start: oneshot::Sender<Started>,
rx_halt: oneshot::Receiver<Halted>,
) {
tracing::info!(target: UDP_TRACKER_LOG_TARGET, "Starting on: {bind_to}");
if udp_tracker_core_container.tracker_core_container.core_config.private {
tracing::error!("udp services cannot be used for private trackers");
panic!("it should not use udp if using authentication");
}
let socket = tokio::time::timeout(Duration::from_millis(5000), BoundSocket::new(bind_to))
.await
.expect("it should bind to the socket within five seconds");
let bound_socket = match socket {
Ok(socket) => socket,
Err(e) => {
tracing::error!(target: UDP_TRACKER_LOG_TARGET, addr = %bind_to, err = %e, "Udp::run_with_graceful_shutdown panic! (error when building socket)" );
panic!("could not bind to socket!");
}
};
let service_binding = bound_socket.service_binding().clone();
let address = bound_socket.address();
let local_udp_url = bound_socket.url().to_string();
tracing::info!(target: UDP_TRACKER_LOG_TARGET, "{STARTED_ON}: {local_udp_url}");
let receiver = Receiver::new(bound_socket.into());
tracing::trace!(target: UDP_TRACKER_LOG_TARGET, local_udp_url, "Udp::run_with_graceful_shutdown (spawning main loop)");
let running = {
let local_addr = local_udp_url.clone();
tokio::task::spawn(async move {
tracing::debug!(target: UDP_TRACKER_LOG_TARGET, local_addr, "Udp::run_with_graceful_shutdown::task (listening...)");
let () = Self::run_udp_server_main(
receiver,
udp_tracker_core_container,
udp_tracker_server_container,
cookie_lifetime,
)
.await;
})
};
tx_start
.send(Started {
service_binding,
address,
})
.expect("the UDP Tracker service should not be dropped");
tracing::debug!(target: UDP_TRACKER_LOG_TARGET, local_udp_url, "Udp::run_with_graceful_shutdown (started)");
let stop = running.abort_handle();
let halt_task = tokio::task::spawn(shutdown_signal_with_message(
rx_halt,
format!("Halting UDP Service Bound to Socket: {address}"),
));
select! {
_ = running => { tracing::debug!(target: UDP_TRACKER_LOG_TARGET, local_udp_url, "Udp::run_with_graceful_shutdown (stopped)"); },
_ = halt_task => { tracing::debug!(target: UDP_TRACKER_LOG_TARGET, local_udp_url, "Udp::run_with_graceful_shutdown (halting)"); }
}
stop.abort();
tokio::task::yield_now().await; // lets allow the other threads to complete.
}
#[must_use]
#[instrument(skip(service_binding))]
pub fn check(service_binding: &ServiceBinding) -> ServiceHealthCheckJob {
let info = format!("checking the udp tracker health check at: {}", service_binding.bind_address());
let service_binding_clone = service_binding.clone();
let job = tokio::spawn(async move { check(&service_binding_clone).await });
ServiceHealthCheckJob::new(service_binding.clone(), info, TYPE_STRING.to_string(), job)
}
#[instrument(skip(receiver, udp_tracker_core_container, udp_tracker_server_container))]
async fn run_udp_server_main(
mut receiver: Receiver,
udp_tracker_core_container: Arc<UdpTrackerCoreContainer>,
udp_tracker_server_container: Arc<UdpTrackerServerContainer>,
cookie_lifetime: Duration,
) {
let active_requests = &mut ActiveRequests::default();
let server_socket_addr = receiver.bound_socket_address();
let server_service_binding =
ServiceBinding::new(Protocol::UDP, server_socket_addr).expect("Bound socket to service binding should not fail");
let local_addr = server_service_binding.clone().to_string();
let cookie_lifetime = cookie_lifetime.as_secs_f64();
let ban_cleaner = udp_tracker_core_container.ban_service.clone();
tokio::spawn(async move {
let mut cleaner_interval = interval(Duration::from_secs(IP_BANS_RESET_INTERVAL_IN_SECS));
cleaner_interval.tick().await;
loop {
cleaner_interval.tick().await;
ban_cleaner.write().await.reset_bans();
}
});
loop {
let server_service_binding =
ServiceBinding::new(Protocol::UDP, server_socket_addr).expect("Bound socket to service binding should not fail");
if let Some(req) = {
tracing::trace!(target: UDP_TRACKER_LOG_TARGET, local_addr, "Udp::run_udp_server (wait for request)");
receiver.next().await
} {
tracing::trace!(target: UDP_TRACKER_LOG_TARGET, local_addr, "Udp::run_udp_server::loop (in)");
let req = match req {
Ok(req) => req,
Err(e) => {
if e.kind() == std::io::ErrorKind::Interrupted {
tracing::warn!(target: UDP_TRACKER_LOG_TARGET, local_addr, err = %e, "Udp::run_udp_server::loop (interrupted)");
return;
}
tracing::error!(target: UDP_TRACKER_LOG_TARGET, local_addr, err = %e, "Udp::run_udp_server::loop break: (got error)");
break;
}
};
let client_socket_addr = req.from;
if let Some(udp_server_stats_event_sender) = udp_tracker_server_container.stats_event_sender.as_deref() {
udp_server_stats_event_sender
.send(Event::UdpRequestReceived {
context: ConnectionContext::new(client_socket_addr, server_service_binding.clone()),
})
.await;
}
if udp_tracker_core_container.ban_service.read().await.is_banned(&req.from.ip()) {
tracing::debug!(target: UDP_TRACKER_LOG_TARGET, local_addr, "Udp::run_udp_server::loop continue: (banned ip)");
if let Some(udp_server_stats_event_sender) = udp_tracker_server_container.stats_event_sender.as_deref() {
udp_server_stats_event_sender
.send(Event::UdpRequestBanned {
context: ConnectionContext::new(client_socket_addr, server_service_binding.clone()),
})
.await;
}
continue;
}
let processor = Processor::new(
receiver.socket.clone(),
udp_tracker_core_container.clone(),
udp_tracker_server_container.clone(),
cookie_lifetime,
);
/* We spawn the new task even if the active requests buffer is
full. This could seem counterintuitive because we are accepting
more request and consuming more memory even if the server is
already busy. However, we "force_push" the new tasks in the
buffer. That means, in the worst scenario we will abort a
running task to make place for the new task.
Once concern could be to reach an starvation point were we are
only adding and removing tasks without given them the chance to
finish. However, the buffer is yielding before aborting one
tasks, giving it the chance to finish. */
let abort_handle: tokio::task::AbortHandle = tokio::task::spawn(processor.process_request(req)).abort_handle();
if abort_handle.is_finished() {
continue;
}
let old_request_aborted = active_requests.force_push(abort_handle, &local_addr).await;
if old_request_aborted {
// Evicted task from active requests buffer was aborted.
if let Some(udp_server_stats_event_sender) = udp_tracker_server_container.stats_event_sender.as_deref() {
udp_server_stats_event_sender
.send(Event::UdpRequestAborted {
context: ConnectionContext::new(client_socket_addr, server_service_binding),
})
.await;
}
}
} else {
tokio::task::yield_now().await;
// the request iterator returned `None`.
tracing::error!(target: UDP_TRACKER_LOG_TARGET, local_addr, "Udp::run_udp_server breaking: (ran dry, should not happen in production!)");
break;
}
}
}
}