Skip to content

Commit b301596

Browse files
committed
chore:[#674] Tracker Checker: Ouput in JSON
1 parent 9a1ce0e commit b301596

File tree

8 files changed

+95
-59
lines changed

8 files changed

+95
-59
lines changed

Cargo.lock

Lines changed: 1 addition & 0 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

Cargo.toml

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -62,7 +62,7 @@ ringbuf = "0"
6262
serde = { version = "1", features = ["derive"] }
6363
serde_bencode = "0"
6464
serde_bytes = "0"
65-
serde_json = "1"
65+
serde_json = { version = "1", features = ["preserve_order"] }
6666
serde_repr = "0"
6767
thiserror = "1"
6868
tokio = { version = "1", features = ["macros", "net", "rt-multi-thread", "signal", "sync"] }
Lines changed: 26 additions & 27 deletions
Original file line numberDiff line numberDiff line change
@@ -1,51 +1,50 @@
11
use std::time::Duration;
22

3-
use colored::Colorize;
43
use reqwest::{Client as HttpClient, Url, Url as ServiceUrl};
54

6-
use crate::console::clients::checker::console::Console;
7-
use crate::console::clients::checker::printer::Printer;
85
use crate::console::clients::checker::service::{CheckError, CheckResult};
96

10-
pub async fn run(health_checks: &Vec<ServiceUrl>, console: &Console, check_results: &mut Vec<CheckResult>) {
11-
console.println("Health checks ...");
7+
use super::structs::{CheckerOutput, Status};
8+
9+
#[allow(clippy::missing_panics_doc)]
10+
pub async fn run(health_checks: &Vec<ServiceUrl>, check_results: &mut Vec<CheckResult>) -> Vec<CheckerOutput> {
11+
let mut health_checkers: Vec<CheckerOutput> = Vec::new();
1212

1313
for health_check_url in health_checks {
14-
match run_health_check(health_check_url.clone(), console).await {
15-
Ok(()) => check_results.push(Ok(())),
16-
Err(err) => check_results.push(Err(err)),
14+
let mut health_checker = CheckerOutput {
15+
url: health_check_url.to_string(),
16+
status: Status {
17+
code: String::new(),
18+
message: String::new(),
19+
},
20+
};
21+
match run_health_check(health_check_url.clone()).await {
22+
Ok(()) => {
23+
check_results.push(Ok(()));
24+
health_checker.status.code = "ok".to_string();
25+
}
26+
Err(err) => {
27+
check_results.push(Err(err));
28+
health_checker.status.code = "error".to_string();
29+
health_checker.status.message = "Health API is failing.".to_string();
30+
}
1731
}
32+
health_checkers.push(health_checker);
1833
}
34+
health_checkers
1935
}
2036

21-
async fn run_health_check(url: Url, console: &Console) -> Result<(), CheckError> {
37+
async fn run_health_check(url: Url) -> Result<(), CheckError> {
2238
let client = HttpClient::builder().timeout(Duration::from_secs(5)).build().unwrap();
2339

24-
let colored_url = url.to_string().yellow();
25-
2640
match client.get(url.clone()).send().await {
2741
Ok(response) => {
2842
if response.status().is_success() {
29-
console.println(&format!("{} - Health API at {} is OK", "✓".green(), colored_url));
3043
Ok(())
3144
} else {
32-
console.eprintln(&format!(
33-
"{} - Health API at {} is failing: {:?}",
34-
"✗".red(),
35-
colored_url,
36-
response
37-
));
3845
Err(CheckError::HealthCheckError { url })
3946
}
4047
}
41-
Err(err) => {
42-
console.eprintln(&format!(
43-
"{} - Health API at {} is failing: {:?}",
44-
"✗".red(),
45-
colored_url,
46-
err
47-
));
48-
Err(CheckError::HealthCheckError { url })
49-
}
48+
Err(_) => Err(CheckError::HealthCheckError { url }),
5049
}
5150
}

src/console/clients/checker/checks/http.rs

Lines changed: 20 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -1,47 +1,57 @@
11
use std::str::FromStr;
22

3-
use colored::Colorize;
43
use log::debug;
54
use reqwest::Url as ServiceUrl;
65
use torrust_tracker_primitives::info_hash::InfoHash;
76
use url::Url;
87

9-
use crate::console::clients::checker::console::Console;
10-
use crate::console::clients::checker::printer::Printer;
118
use crate::console::clients::checker::service::{CheckError, CheckResult};
129
use crate::shared::bit_torrent::tracker::http::client::requests::announce::QueryBuilder;
1310
use crate::shared::bit_torrent::tracker::http::client::responses::announce::Announce;
1411
use crate::shared::bit_torrent::tracker::http::client::responses::scrape;
1512
use crate::shared::bit_torrent::tracker::http::client::{requests, Client};
1613

17-
pub async fn run(http_trackers: &Vec<ServiceUrl>, console: &Console, check_results: &mut Vec<CheckResult>) {
18-
console.println("HTTP trackers ...");
14+
use super::structs::{CheckerOutput, Status};
15+
16+
#[allow(clippy::missing_panics_doc)]
17+
pub async fn run(http_trackers: &Vec<ServiceUrl>, check_results: &mut Vec<CheckResult>) -> Vec<CheckerOutput> {
18+
let mut http_checkers: Vec<CheckerOutput> = Vec::new();
1919

2020
for http_tracker in http_trackers {
21-
let colored_tracker_url = http_tracker.to_string().yellow();
21+
let mut http_checker = CheckerOutput {
22+
url: http_tracker.to_string(),
23+
status: Status {
24+
code: String::new(),
25+
message: String::new(),
26+
},
27+
};
2228

2329
match check_http_announce(http_tracker).await {
2430
Ok(()) => {
2531
check_results.push(Ok(()));
26-
console.println(&format!("{} - Announce at {} is OK", "✓".green(), colored_tracker_url));
32+
http_checker.status.code = "ok".to_string();
2733
}
2834
Err(err) => {
2935
check_results.push(Err(err));
30-
console.println(&format!("{} - Announce at {} is failing", "✗".red(), colored_tracker_url));
36+
http_checker.status.code = "error".to_string();
37+
http_checker.status.message = "Announce is failing.".to_string();
3138
}
3239
}
3340

3441
match check_http_scrape(http_tracker).await {
3542
Ok(()) => {
3643
check_results.push(Ok(()));
37-
console.println(&format!("{} - Scrape at {} is OK", "✓".green(), colored_tracker_url));
44+
http_checker.status.code = "ok".to_string();
3845
}
3946
Err(err) => {
4047
check_results.push(Err(err));
41-
console.println(&format!("{} - Scrape at {} is failing", "✗".red(), colored_tracker_url));
48+
http_checker.status.code = "error".to_string();
49+
http_checker.status.message = "Scrape is failing.".to_string();
4250
}
4351
}
52+
http_checkers.push(http_checker);
4453
}
54+
http_checkers
4555
}
4656

4757
async fn check_http_announce(tracker_url: &Url) -> Result<(), CheckError> {
Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
11
pub mod health;
22
pub mod http;
3+
pub mod structs;
34
pub mod udp;
Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,12 @@
1+
use serde::{Deserialize, Serialize};
2+
3+
#[derive(Serialize, Deserialize)]
4+
pub struct Status {
5+
pub code: String,
6+
pub message: String,
7+
}
8+
#[derive(Serialize, Deserialize)]
9+
pub struct CheckerOutput {
10+
pub url: String,
11+
pub status: Status,
12+
}
Lines changed: 25 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -1,26 +1,32 @@
11
use std::net::SocketAddr;
22

33
use aquatic_udp_protocol::{Port, TransactionId};
4-
use colored::Colorize;
54
use hex_literal::hex;
65
use log::debug;
76
use torrust_tracker_primitives::info_hash::InfoHash;
87

9-
use crate::console::clients::checker::console::Console;
10-
use crate::console::clients::checker::printer::Printer;
118
use crate::console::clients::checker::service::{CheckError, CheckResult};
129
use crate::console::clients::udp::checker;
1310

11+
use crate::console::clients::checker::checks::structs::{CheckerOutput, Status};
12+
1413
const ASSIGNED_BY_OS: u16 = 0;
1514
const RANDOM_TRANSACTION_ID: i32 = -888_840_697;
1615

17-
pub async fn run(udp_trackers: &Vec<SocketAddr>, console: &Console, check_results: &mut Vec<CheckResult>) {
18-
console.println("UDP trackers ...");
16+
#[allow(clippy::missing_panics_doc)]
17+
pub async fn run(udp_trackers: &Vec<SocketAddr>, check_results: &mut Vec<CheckResult>) -> Vec<CheckerOutput> {
18+
let mut udp_checkers: Vec<CheckerOutput> = Vec::new();
1919

2020
for udp_tracker in udp_trackers {
21-
debug!("UDP tracker: {:?}", udp_tracker);
21+
let mut checker_output = CheckerOutput {
22+
url: udp_tracker.to_string(),
23+
status: Status {
24+
code: String::new(),
25+
message: String::new(),
26+
},
27+
};
2228

23-
let colored_tracker_url = udp_tracker.to_string().yellow();
29+
debug!("UDP tracker: {:?}", udp_tracker);
2430

2531
let transaction_id = TransactionId(RANDOM_TRANSACTION_ID);
2632

@@ -32,7 +38,8 @@ pub async fn run(udp_trackers: &Vec<SocketAddr>, console: &Console, check_result
3238
check_results.push(Err(CheckError::UdpError {
3339
socket_addr: *udp_tracker,
3440
}));
35-
console.println(&format!("{} - Can't connect to socket {}", "✗".red(), colored_tracker_url));
41+
checker_output.status.code = "error".to_string();
42+
checker_output.status.message = "Can't connect to socket.".to_string();
3643
break;
3744
};
3845

@@ -42,11 +49,8 @@ pub async fn run(udp_trackers: &Vec<SocketAddr>, console: &Console, check_result
4249
check_results.push(Err(CheckError::UdpError {
4350
socket_addr: *udp_tracker,
4451
}));
45-
console.println(&format!(
46-
"{} - Can't make tracker connection request to {}",
47-
"✗".red(),
48-
colored_tracker_url
49-
));
52+
checker_output.status.code = "error".to_string();
53+
checker_output.status.message = "Can't make tracker connection request.".to_string();
5054
break;
5155
};
5256

@@ -60,13 +64,14 @@ pub async fn run(udp_trackers: &Vec<SocketAddr>, console: &Console, check_result
6064
.is_ok()
6165
{
6266
check_results.push(Ok(()));
63-
console.println(&format!("{} - Announce at {} is OK", "✓".green(), colored_tracker_url));
67+
checker_output.status.code = "ok".to_string();
6468
} else {
6569
let err = CheckError::UdpError {
6670
socket_addr: *udp_tracker,
6771
};
6872
check_results.push(Err(err));
69-
console.println(&format!("{} - Announce at {} is failing", "✗".red(), colored_tracker_url));
73+
checker_output.status.code = "error".to_string();
74+
checker_output.status.message = "Announce is failing.".to_string();
7075
}
7176

7277
debug!("Send scrape request");
@@ -75,13 +80,16 @@ pub async fn run(udp_trackers: &Vec<SocketAddr>, console: &Console, check_result
7580

7681
if (client.send_scrape_request(connection_id, transaction_id, info_hashes).await).is_ok() {
7782
check_results.push(Ok(()));
78-
console.println(&format!("{} - Announce at {} is OK", "✓".green(), colored_tracker_url));
83+
checker_output.status.code = "ok".to_string();
7984
} else {
8085
let err = CheckError::UdpError {
8186
socket_addr: *udp_tracker,
8287
};
8388
check_results.push(Err(err));
84-
console.println(&format!("{} - Announce at {} is failing", "✗".red(), colored_tracker_url));
89+
checker_output.status.code = "error".to_string();
90+
checker_output.status.message = "Scrape is failing.".to_string();
8591
}
92+
udp_checkers.push(checker_output);
8693
}
94+
udp_checkers
8795
}

src/console/clients/checker/service.rs

Lines changed: 9 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@ use std::sync::Arc;
33

44
use reqwest::Url;
55

6-
use super::checks;
6+
use super::checks::{self};
77
use super::config::Configuration;
88
use super::console::Console;
99
use crate::console::clients::checker::printer::Printer;
@@ -26,16 +26,21 @@ impl Service {
2626
/// # Errors
2727
///
2828
/// Will return OK is all checks pass or an array with the check errors.
29+
#[allow(clippy::missing_panics_doc)]
2930
pub async fn run_checks(&self) -> Vec<CheckResult> {
3031
self.console.println("Running checks for trackers ...");
3132

3233
let mut check_results = vec![];
3334

34-
checks::udp::run(&self.config.udp_trackers, &self.console, &mut check_results).await;
35+
let udp_checkers = checks::udp::run(&self.config.udp_trackers, &mut check_results).await;
3536

36-
checks::http::run(&self.config.http_trackers, &self.console, &mut check_results).await;
37+
let http_checkers = checks::http::run(&self.config.http_trackers, &mut check_results).await;
3738

38-
checks::health::run(&self.config.health_checks, &self.console, &mut check_results).await;
39+
let health_checkers = checks::health::run(&self.config.health_checks, &mut check_results).await;
40+
41+
let json_output =
42+
serde_json::json!({ "udp_trackers": udp_checkers, "http_trackers": http_checkers, "health_checks": health_checkers });
43+
self.console.println(&serde_json::to_string_pretty(&json_output).unwrap());
3944

4045
check_results
4146
}

0 commit comments

Comments
 (0)