endstat/src/main.rs

166 lines
4.8 KiB
Rust
Raw Normal View History

2019-04-30 07:53:13 +00:00
extern crate actix;
extern crate actix_web;
extern crate reqwest;
extern crate ron;
extern crate serde;
use actix::System;
use actix_web::{
http::{Method, StatusCode},
server, App, HttpResponse, State,
};
2019-04-30 06:19:58 +00:00
use reqwest::{Client, Url, UrlError};
2019-04-30 05:44:26 +00:00
use ron::de::from_str;
use serde::Deserialize;
2019-04-30 07:53:13 +00:00
use std::{
error::Error,
fs::read_to_string,
sync::{Arc, Mutex},
time::{Duration, Instant},
};
2019-04-30 05:44:26 +00:00
2019-04-30 06:47:35 +00:00
#[derive(Deserialize, Debug, Clone)]
2019-04-30 05:44:26 +00:00
struct EndpointConf {
label: Option<String>,
endpoint: Option<String>,
port: Option<u16>,
code: Option<u16>,
body: Option<String>,
}
2019-04-30 06:47:35 +00:00
#[derive(Deserialize, Debug, Clone)]
2019-04-30 05:44:26 +00:00
struct WebsiteConf {
label: String,
base: String,
endpoints: Vec<EndpointConf>,
}
2019-04-30 06:47:35 +00:00
#[derive(Deserialize, Debug, Clone)]
2019-04-30 05:44:26 +00:00
struct Config {
2019-04-30 06:47:35 +00:00
refresh_time: u64,
2019-04-30 05:44:26 +00:00
websites: Vec<WebsiteConf>,
}
#[derive(Debug)]
struct Status {
status: u8,
location: String,
domain: String,
endpoint: String,
error: Option<String>,
}
2019-04-30 07:53:13 +00:00
struct FetchResults {
last_update: Instant,
refresh_time: u64,
config: Config,
statuses: Vec<Status>,
}
type StatusState = Arc<Mutex<FetchResults>>;
fn index(state: State<StatusState>) -> HttpResponse {
let mut state = state.lock().unwrap();
let mut result = String::new();
if Instant::now().duration_since(state.last_update) > Duration::from_secs(state.refresh_time) {
result = format!(
"it has been {:} seconds since last update, updating",
Instant::now().duration_since(state.last_update).as_secs()
);
state.last_update = Instant::now();
state.statuses = update_status(&state.config);
}
let result = format!("{}\n{:?}", result, state.statuses);
HttpResponse::with_body(StatusCode::OK, result)
}
2019-04-30 05:44:26 +00:00
fn main() -> Result<(), Box<Error>> {
let config = from_str::<Config>(&read_to_string("./endstat_conf.ron")?)?;
2019-04-30 06:47:35 +00:00
2019-04-30 07:53:13 +00:00
println!("running server");
let sys = System::new("status");
let a: Arc<Mutex<FetchResults>> = Arc::from(Mutex::from(FetchResults {
last_update: Instant::now(),
refresh_time: config.refresh_time,
config: config.clone(),
statuses: update_status(&config),
}));
2019-04-30 06:47:35 +00:00
2019-04-30 07:53:13 +00:00
server::new(move || {
App::with_state(a.clone()).resource("/", |r| r.method(Method::GET).with(index))
})
.bind("0.0.0.0:8080")?
.start();
2019-04-30 06:47:35 +00:00
2019-04-30 07:53:13 +00:00
sys.run();
2019-04-30 06:47:35 +00:00
Ok(())
}
2019-04-30 05:44:26 +00:00
2019-04-30 07:53:13 +00:00
fn update_status(config: &Config) -> Vec<Status> {
2019-04-30 06:47:35 +00:00
let client = Client::new();
2019-04-30 05:44:26 +00:00
let mut results: Vec<Status> = vec![];
2019-04-30 07:53:13 +00:00
for website_conf in &config.websites {
for endpoint in &website_conf.endpoints {
let (label, path, port, code, body) = get_endpoint_info(endpoint.clone());
2019-04-30 06:47:35 +00:00
let url = get_url(&website_conf.base, &path, port).expect("reading config");
if let Ok(mut res) = client.get(&url).send() {
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;
2019-04-30 05:44:26 +00:00
2019-04-30 06:47:35 +00:00
results.push(if !does_code_match {
Status {
status: 1,
location: url,
domain: website_conf.label.clone(),
endpoint: label,
error: Some(format!(
"Status code mismatch! {} != {}",
res.status().as_u16(),
code
)),
}
} else if !does_body_match {
Status {
status: 2,
location: url,
domain: website_conf.label.clone(),
endpoint: label,
error: Some(format!("Body mismatch! {} != {}", res_body, body)),
}
} else {
Status {
status: 0,
location: url,
domain: website_conf.label.clone(),
endpoint: label,
error: None,
}
});
}
2019-04-30 05:44:26 +00:00
}
}
2019-04-30 06:47:35 +00:00
results
2019-04-30 05:44:26 +00:00
}
2019-04-30 06:19:58 +00:00
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())
}
2019-04-30 05:44:26 +00:00
fn get_endpoint_info(endpoint: EndpointConf) -> (String, String, Option<u16>, u16, String) {
let path = endpoint.endpoint.unwrap_or_default();
let label = endpoint.label.unwrap_or_else(|| path.clone());
let code = endpoint.code.unwrap_or_else(|| 200);
let body = endpoint.body.unwrap_or_default();
(label, path, endpoint.port, code, body)
}