forked from torrust/torrust-tracker
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathstatistics.rs
More file actions
490 lines (385 loc) · 15.9 KB
/
statistics.rs
File metadata and controls
490 lines (385 loc) · 15.9 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
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
//! Structs to collect and keep tracker metrics.
//!
//! The tracker collects metrics such as:
//!
//! - Number of connections handled
//! - Number of `announce` requests handled
//! - Number of `scrape` request handled
//!
//! These metrics are collected for each connection type: UDP and HTTP and
//! also for each IP version used by the peers: IPv4 and IPv6.
//!
//! > Notice: that UDP tracker have an specific `connection` request. For the HTTP metrics the counter counts one connection for each `announce` or `scrape` request.
//!
//! The data is collected by using an `event-sender -> event listener` model.
//!
//! The tracker uses an [`statistics::EventSender`](crate::tracker::statistics::EventSender) instance to send an event.
//! The [`statistics::Keeper`](crate::tracker::statistics::Keeper) listens to new events and uses the [`statistics::Repo`](crate::tracker::statistics::Repo) to upgrade and store metrics.
//!
//! See the [`statistics::Event`](crate::tracker::statistics::Event) enum to check which events are available.
use std::sync::Arc;
use async_trait::async_trait;
use log::debug;
#[cfg(test)]
use mockall::{automock, predicate::str};
use tokio::sync::mpsc::error::SendError;
use tokio::sync::{mpsc, RwLock, RwLockReadGuard};
const CHANNEL_BUFFER_SIZE: usize = 65_535;
/// An statistics event. It is used to collect tracker metrics.
///
/// - `Tcp` prefix means the event was triggered by the HTTP tracker
/// - `Udp` prefix means the event was triggered by the UDP tracker
/// - `4` or `6` prefixes means the IP version used by the peer
/// - Finally the event suffix is the type of request: `announce`, `scrape` or `connection`
///
/// > NOTE: HTTP trackers do not use `connection` requests.
#[derive(Debug, PartialEq, Eq)]
pub enum Event {
// code-review: consider one single event for request type with data: Event::Announce { scheme: HTTPorUDP, ip_version: V4orV6 }
// Attributes are enums too.
Tcp4Announce,
Tcp4Scrape,
Tcp6Announce,
Tcp6Scrape,
Udp4Connect,
Udp4Announce,
Udp4Scrape,
Udp6Connect,
Udp6Announce,
Udp6Scrape,
}
/// Metrics collected by the tracker.
///
/// - Number of connections handled
/// - Number of `announce` requests handled
/// - Number of `scrape` request handled
///
/// These metrics are collected for each connection type: UDP and HTTP
/// and also for each IP version used by the peers: IPv4 and IPv6.
#[derive(Debug, PartialEq, Default)]
pub struct Metrics {
/// Total number of TCP (HTTP tracker) connections from IPv4 peers.
/// Since the HTTP tracker spec does not require a handshake, this metric
/// increases for every HTTP request.
pub tcp4_connections_handled: u64,
/// Total number of TCP (HTTP tracker) `announce` requests from IPv4 peers.
pub tcp4_announces_handled: u64,
/// Total number of TCP (HTTP tracker) `scrape` requests from IPv4 peers.
pub tcp4_scrapes_handled: u64,
/// Total number of TCP (HTTP tracker) connections from IPv6 peers.
pub tcp6_connections_handled: u64,
/// Total number of TCP (HTTP tracker) `announce` requests from IPv6 peers.
pub tcp6_announces_handled: u64,
/// Total number of TCP (HTTP tracker) `scrape` requests from IPv6 peers.
pub tcp6_scrapes_handled: u64,
/// Total number of UDP (UDP tracker) connections from IPv4 peers.
pub udp4_connections_handled: u64,
/// Total number of UDP (UDP tracker) `announce` requests from IPv4 peers.
pub udp4_announces_handled: u64,
/// Total number of UDP (UDP tracker) `scrape` requests from IPv4 peers.
pub udp4_scrapes_handled: u64,
/// Total number of UDP (UDP tracker) `connection` requests from IPv6 peers.
pub udp6_connections_handled: u64,
/// Total number of UDP (UDP tracker) `announce` requests from IPv6 peers.
pub udp6_announces_handled: u64,
/// Total number of UDP (UDP tracker) `scrape` requests from IPv6 peers.
pub udp6_scrapes_handled: u64,
}
/// The service responsible for keeping tracker metrics (listening to statistics events and handle them).
///
/// It actively listen to new statistics events. When it receives a new event
/// it accordingly increases the counters.
pub struct Keeper {
pub repository: Repo,
}
impl Default for Keeper {
fn default() -> Self {
Self::new()
}
}
impl Keeper {
#[must_use]
pub fn new() -> Self {
Self { repository: Repo::new() }
}
#[must_use]
pub fn new_active_instance() -> (Box<dyn EventSender>, Repo) {
let mut stats_tracker = Self::new();
let stats_event_sender = stats_tracker.run_event_listener();
(stats_event_sender, stats_tracker.repository)
}
pub fn run_event_listener(&mut self) -> Box<dyn EventSender> {
let (sender, receiver) = mpsc::channel::<Event>(CHANNEL_BUFFER_SIZE);
let stats_repository = self.repository.clone();
tokio::spawn(async move { event_listener(receiver, stats_repository).await });
Box::new(Sender { sender })
}
}
async fn event_listener(mut receiver: mpsc::Receiver<Event>, stats_repository: Repo) {
while let Some(event) = receiver.recv().await {
event_handler(event, &stats_repository).await;
}
}
async fn event_handler(event: Event, stats_repository: &Repo) {
match event {
// TCP4
Event::Tcp4Announce => {
stats_repository.increase_tcp4_announces().await;
stats_repository.increase_tcp4_connections().await;
}
Event::Tcp4Scrape => {
stats_repository.increase_tcp4_scrapes().await;
stats_repository.increase_tcp4_connections().await;
}
// TCP6
Event::Tcp6Announce => {
stats_repository.increase_tcp6_announces().await;
stats_repository.increase_tcp6_connections().await;
}
Event::Tcp6Scrape => {
stats_repository.increase_tcp6_scrapes().await;
stats_repository.increase_tcp6_connections().await;
}
// UDP4
Event::Udp4Connect => {
stats_repository.increase_udp4_connections().await;
}
Event::Udp4Announce => {
stats_repository.increase_udp4_announces().await;
}
Event::Udp4Scrape => {
stats_repository.increase_udp4_scrapes().await;
}
// UDP6
Event::Udp6Connect => {
stats_repository.increase_udp6_connections().await;
}
Event::Udp6Announce => {
stats_repository.increase_udp6_announces().await;
}
Event::Udp6Scrape => {
stats_repository.increase_udp6_scrapes().await;
}
}
debug!("stats: {:?}", stats_repository.get_stats().await);
}
/// A trait to allow sending statistics events
#[async_trait]
#[cfg_attr(test, automock)]
pub trait EventSender: Sync + Send {
async fn send_event(&self, event: Event) -> Option<Result<(), SendError<Event>>>;
}
/// An [`statistics::EventSender`](crate::tracker::statistics::EventSender) implementation.
///
/// It uses a channel sender to send the statistic events. The channel is created by a
/// [`statistics::Keeper`](crate::tracker::statistics::Keeper)
pub struct Sender {
sender: mpsc::Sender<Event>,
}
#[async_trait]
impl EventSender for Sender {
async fn send_event(&self, event: Event) -> Option<Result<(), SendError<Event>>> {
Some(self.sender.send(event).await)
}
}
/// A repository for the tracker metrics.
#[derive(Clone)]
pub struct Repo {
pub stats: Arc<RwLock<Metrics>>,
}
impl Default for Repo {
fn default() -> Self {
Self::new()
}
}
impl Repo {
#[must_use]
pub fn new() -> Self {
Self {
stats: Arc::new(RwLock::new(Metrics::default())),
}
}
pub async fn get_stats(&self) -> RwLockReadGuard<'_, Metrics> {
self.stats.read().await
}
pub async fn increase_tcp4_announces(&self) {
let mut stats_lock = self.stats.write().await;
stats_lock.tcp4_announces_handled += 1;
drop(stats_lock);
}
pub async fn increase_tcp4_connections(&self) {
let mut stats_lock = self.stats.write().await;
stats_lock.tcp4_connections_handled += 1;
drop(stats_lock);
}
pub async fn increase_tcp4_scrapes(&self) {
let mut stats_lock = self.stats.write().await;
stats_lock.tcp4_scrapes_handled += 1;
drop(stats_lock);
}
pub async fn increase_tcp6_announces(&self) {
let mut stats_lock = self.stats.write().await;
stats_lock.tcp6_announces_handled += 1;
drop(stats_lock);
}
pub async fn increase_tcp6_connections(&self) {
let mut stats_lock = self.stats.write().await;
stats_lock.tcp6_connections_handled += 1;
drop(stats_lock);
}
pub async fn increase_tcp6_scrapes(&self) {
let mut stats_lock = self.stats.write().await;
stats_lock.tcp6_scrapes_handled += 1;
drop(stats_lock);
}
pub async fn increase_udp4_connections(&self) {
let mut stats_lock = self.stats.write().await;
stats_lock.udp4_connections_handled += 1;
drop(stats_lock);
}
pub async fn increase_udp4_announces(&self) {
let mut stats_lock = self.stats.write().await;
stats_lock.udp4_announces_handled += 1;
drop(stats_lock);
}
pub async fn increase_udp4_scrapes(&self) {
let mut stats_lock = self.stats.write().await;
stats_lock.udp4_scrapes_handled += 1;
drop(stats_lock);
}
pub async fn increase_udp6_connections(&self) {
let mut stats_lock = self.stats.write().await;
stats_lock.udp6_connections_handled += 1;
drop(stats_lock);
}
pub async fn increase_udp6_announces(&self) {
let mut stats_lock = self.stats.write().await;
stats_lock.udp6_announces_handled += 1;
drop(stats_lock);
}
pub async fn increase_udp6_scrapes(&self) {
let mut stats_lock = self.stats.write().await;
stats_lock.udp6_scrapes_handled += 1;
drop(stats_lock);
}
}
#[cfg(test)]
mod tests {
mod stats_tracker {
use crate::tracker::statistics::{Event, Keeper, Metrics};
#[tokio::test]
async fn should_contain_the_tracker_statistics() {
let stats_tracker = Keeper::new();
let stats = stats_tracker.repository.get_stats().await;
assert_eq!(stats.tcp4_announces_handled, Metrics::default().tcp4_announces_handled);
}
#[tokio::test]
async fn should_create_an_event_sender_to_send_statistical_events() {
let mut stats_tracker = Keeper::new();
let event_sender = stats_tracker.run_event_listener();
let result = event_sender.send_event(Event::Udp4Connect).await;
assert!(result.is_some());
}
}
mod event_handler {
use crate::tracker::statistics::{event_handler, Event, Repo};
#[tokio::test]
async fn should_increase_the_tcp4_announces_counter_when_it_receives_a_tcp4_announce_event() {
let stats_repository = Repo::new();
event_handler(Event::Tcp4Announce, &stats_repository).await;
let stats = stats_repository.get_stats().await;
assert_eq!(stats.tcp4_announces_handled, 1);
}
#[tokio::test]
async fn should_increase_the_tcp4_connections_counter_when_it_receives_a_tcp4_announce_event() {
let stats_repository = Repo::new();
event_handler(Event::Tcp4Announce, &stats_repository).await;
let stats = stats_repository.get_stats().await;
assert_eq!(stats.tcp4_connections_handled, 1);
}
#[tokio::test]
async fn should_increase_the_tcp4_scrapes_counter_when_it_receives_a_tcp4_scrape_event() {
let stats_repository = Repo::new();
event_handler(Event::Tcp4Scrape, &stats_repository).await;
let stats = stats_repository.get_stats().await;
assert_eq!(stats.tcp4_scrapes_handled, 1);
}
#[tokio::test]
async fn should_increase_the_tcp4_connections_counter_when_it_receives_a_tcp4_scrape_event() {
let stats_repository = Repo::new();
event_handler(Event::Tcp4Scrape, &stats_repository).await;
let stats = stats_repository.get_stats().await;
assert_eq!(stats.tcp4_connections_handled, 1);
}
#[tokio::test]
async fn should_increase_the_tcp6_announces_counter_when_it_receives_a_tcp6_announce_event() {
let stats_repository = Repo::new();
event_handler(Event::Tcp6Announce, &stats_repository).await;
let stats = stats_repository.get_stats().await;
assert_eq!(stats.tcp6_announces_handled, 1);
}
#[tokio::test]
async fn should_increase_the_tcp6_connections_counter_when_it_receives_a_tcp6_announce_event() {
let stats_repository = Repo::new();
event_handler(Event::Tcp6Announce, &stats_repository).await;
let stats = stats_repository.get_stats().await;
assert_eq!(stats.tcp6_connections_handled, 1);
}
#[tokio::test]
async fn should_increase_the_tcp6_scrapes_counter_when_it_receives_a_tcp6_scrape_event() {
let stats_repository = Repo::new();
event_handler(Event::Tcp6Scrape, &stats_repository).await;
let stats = stats_repository.get_stats().await;
assert_eq!(stats.tcp6_scrapes_handled, 1);
}
#[tokio::test]
async fn should_increase_the_tcp6_connections_counter_when_it_receives_a_tcp6_scrape_event() {
let stats_repository = Repo::new();
event_handler(Event::Tcp6Scrape, &stats_repository).await;
let stats = stats_repository.get_stats().await;
assert_eq!(stats.tcp6_connections_handled, 1);
}
#[tokio::test]
async fn should_increase_the_udp4_connections_counter_when_it_receives_a_udp4_connect_event() {
let stats_repository = Repo::new();
event_handler(Event::Udp4Connect, &stats_repository).await;
let stats = stats_repository.get_stats().await;
assert_eq!(stats.udp4_connections_handled, 1);
}
#[tokio::test]
async fn should_increase_the_udp4_announces_counter_when_it_receives_a_udp4_announce_event() {
let stats_repository = Repo::new();
event_handler(Event::Udp4Announce, &stats_repository).await;
let stats = stats_repository.get_stats().await;
assert_eq!(stats.udp4_announces_handled, 1);
}
#[tokio::test]
async fn should_increase_the_udp4_scrapes_counter_when_it_receives_a_udp4_scrape_event() {
let stats_repository = Repo::new();
event_handler(Event::Udp4Scrape, &stats_repository).await;
let stats = stats_repository.get_stats().await;
assert_eq!(stats.udp4_scrapes_handled, 1);
}
#[tokio::test]
async fn should_increase_the_udp6_connections_counter_when_it_receives_a_udp6_connect_event() {
let stats_repository = Repo::new();
event_handler(Event::Udp6Connect, &stats_repository).await;
let stats = stats_repository.get_stats().await;
assert_eq!(stats.udp6_connections_handled, 1);
}
#[tokio::test]
async fn should_increase_the_udp6_announces_counter_when_it_receives_a_udp6_announce_event() {
let stats_repository = Repo::new();
event_handler(Event::Udp6Announce, &stats_repository).await;
let stats = stats_repository.get_stats().await;
assert_eq!(stats.udp6_announces_handled, 1);
}
#[tokio::test]
async fn should_increase_the_udp6_scrapes_counter_when_it_receives_a_udp6_scrape_event() {
let stats_repository = Repo::new();
event_handler(Event::Udp6Scrape, &stats_repository).await;
let stats = stats_repository.get_stats().await;
assert_eq!(stats.udp6_scrapes_handled, 1);
}
}
}