2019-05-01 20:01:27 +00:00
|
|
|
use crate::{config::*, handlers::Status, State};
|
|
|
|
use chrono::prelude::*;
|
2019-05-01 18:13:46 +00:00
|
|
|
use reqwest::{Client, Url, UrlError};
|
|
|
|
|
|
|
|
pub fn update_state(state: State) {
|
|
|
|
let new_statuses = { Some(update_status(&state.read().unwrap().config)) };
|
|
|
|
let mut write_state = state.try_write().expect("Could not unlock");
|
2019-05-01 20:15:18 +00:00
|
|
|
write_state.timestamp = Utc::now();
|
|
|
|
write_state.timestamp_str = Utc::now().format("%Y-%m-%d %H:%M:%S").to_string();
|
2019-05-01 18:13:46 +00:00
|
|
|
write_state.statuses = new_statuses.unwrap();
|
|
|
|
}
|
|
|
|
|
2019-05-01 20:01:27 +00:00
|
|
|
pub fn update_status(config: &Config) -> Vec<Status> {
|
2019-05-01 18:13:46 +00:00
|
|
|
let client = Client::new();
|
|
|
|
let mut results: Vec<Status> = vec![];
|
|
|
|
|
|
|
|
for website_conf in &config.websites {
|
|
|
|
for endpoint in &website_conf.endpoints {
|
|
|
|
results.push(get_result(website_conf, &client, endpoint));
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
results
|
|
|
|
}
|
|
|
|
|
|
|
|
fn get_result(website_conf: &WebsiteConfig, client: &Client, endpoint: &EndpointConfig) -> Status {
|
|
|
|
let (label, path, port, code, body) = get_endpoint_info(endpoint.clone());
|
|
|
|
let url = get_url(&website_conf.base, &path, port).expect("reading config");
|
|
|
|
let ping_result = client.get(&url).send();
|
|
|
|
|
|
|
|
match ping_result {
|
|
|
|
Ok(mut res) => {
|
|
|
|
let res_body = res.text().expect("could not get body of request");
|
|
|
|
let does_code_match = res.status() == code;
|
|
|
|
let does_body_match = body.is_empty() || res_body == body;
|
|
|
|
let mut error = None;
|
|
|
|
|
|
|
|
if !does_code_match {
|
|
|
|
error = Some(format!(
|
|
|
|
"Status code mismatch: {} != {}.",
|
|
|
|
res.status().as_u16(),
|
|
|
|
code
|
|
|
|
));
|
|
|
|
}
|
|
|
|
|
|
|
|
if !does_body_match {
|
|
|
|
error = Some(if let Some(msg) = error {
|
|
|
|
format!(
|
|
|
|
"{} Body mismatch: {} != {}.",
|
|
|
|
msg,
|
|
|
|
res_body.len(),
|
|
|
|
body.len()
|
|
|
|
)
|
|
|
|
} else {
|
|
|
|
format!("Body mismatch: {} != {}.", res_body.len(), body.len())
|
|
|
|
});
|
|
|
|
}
|
|
|
|
|
|
|
|
Status {
|
|
|
|
status: if error.is_some() { 1 } else { 0 },
|
|
|
|
location: url,
|
|
|
|
domain: website_conf.label.clone(),
|
|
|
|
endpoint: label,
|
|
|
|
error,
|
|
|
|
}
|
|
|
|
}
|
|
|
|
Err(e) => Status {
|
|
|
|
status: 2,
|
|
|
|
location: url,
|
|
|
|
domain: website_conf.label.clone(),
|
|
|
|
endpoint: label,
|
|
|
|
error: Some(format!("{}", e)),
|
|
|
|
},
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
fn get_url(base: &String, path: &String, port: Option<u16>) -> Result<String, UrlError> {
|
|
|
|
let mut url = Url::parse(base)?.join(path)?;
|
|
|
|
if let Err(e) = url.set_port(port) {
|
|
|
|
println!("{:?}", e);
|
|
|
|
}
|
|
|
|
Ok(url.into_string())
|
|
|
|
}
|