Compare commits
39 Commits
Author | SHA1 | Date |
---|---|---|
Edward Shen | 54c53629db | |
Edward Shen | 3224c02d6f | |
Edward Shen | 2a56b0f4ad | |
Edward Shen | fa49084778 | |
Edward Shen | 2793469627 | |
Edward Shen | be38c16c8d | |
Edward Shen | 2cbbbdd101 | |
Edward Shen | 85f765b30d | |
Edward Shen | ecb0b8ca6a | |
Edward Shen | 443dca2841 | |
Edward Shen | f42c70b27e | |
Edward Shen | 17a0730275 | |
Edward Shen | 82b944a748 | |
Edward Shen | 816a6daed1 | |
Edward Shen | ddab660945 | |
Edward Shen | 39d932c949 | |
Edward Shen | 01757eb4da | |
Edward Shen | f7e6dd3246 | |
Edward Shen | 90ce6167cf | |
Edward Shen | 567d5b36ed | |
Edward Shen | 8304f4c645 | |
Edward Shen | c4e8bc61b6 | |
William Tan | 77f5f62f56 | |
Edward Shen | 978321b0ce | |
Edward Shen | 5aa57864d7 | |
Edward Shen | 25ed4f0acb | |
Edward Shen | 57574993b6 | |
Edward Shen | 18a95cb3cd | |
Edward Shen | b950efb703 | |
Edward Shen | 6e3ab3f522 | |
Edward Shen | 993019f352 | |
Edward Shen | f0c38b4d79 | |
Edward Shen | e88efdae56 | |
Edward Shen | 0f4ca23655 | |
Edward Shen | c83190ada6 | |
Edward Shen | 211a3f9477 | |
Edward Shen | 0e8abe2701 | |
Edward Shen | fef8fd66c7 | |
Edward Shen | af79f6d2a3 |
|
@ -0,0 +1,2 @@
|
|||
target/
|
||||
config/endstat_conf.ron
|
|
@ -1,4 +1,5 @@
|
|||
target
|
||||
**/*.rs.bk
|
||||
*.ron
|
||||
**/*.ron
|
||||
.vscode/
|
||||
!**/endstat_conf.example.ron
|
||||
|
|
File diff suppressed because it is too large
Load Diff
16
Cargo.toml
16
Cargo.toml
|
@ -1,6 +1,6 @@
|
|||
[package]
|
||||
name = "endstat"
|
||||
version = "0.1.0"
|
||||
version = "0.2.0"
|
||||
authors = ["Edward Shen <code@eddie.sh>"]
|
||||
edition = "2018"
|
||||
|
||||
|
@ -8,9 +8,19 @@ edition = "2018"
|
|||
reqwest = "0.9"
|
||||
serde = { version = "1.0", features = ["derive"] }
|
||||
ron = "0.5"
|
||||
actix-web = "1.0.0-beta.2"
|
||||
actix-web = { version = "1.0", default-features = false, features = ["brotli", "flate2-zlib"] }
|
||||
actix = "0.8"
|
||||
tokio = "0.1"
|
||||
tera = "0.11"
|
||||
env_logger = "0.6"
|
||||
lazy_static = "1.3.0"
|
||||
chrono = { version = "0.4", features = ["serde"] }
|
||||
ring = "^0"
|
||||
log="0.4"
|
||||
rss = { version = "1.7.0", optional = true }
|
||||
|
||||
[features]
|
||||
default = ["json", "webhooks"]
|
||||
|
||||
json = []
|
||||
rss_feed = ["rss"]
|
||||
webhooks = []
|
||||
|
|
|
@ -0,0 +1,27 @@
|
|||
FROM rust:1.34.1-slim-stretch as builder
|
||||
|
||||
RUN apt update && apt install -y pkg-config libssl-dev
|
||||
|
||||
WORKDIR /app
|
||||
RUN mkdir src && touch src/lib.rs
|
||||
COPY Cargo.lock /app
|
||||
COPY Cargo.toml /app
|
||||
|
||||
RUN cargo build --release
|
||||
|
||||
COPY src/ src/
|
||||
RUN cargo build --release
|
||||
|
||||
FROM debian:stable-slim
|
||||
|
||||
RUN apt update && apt upgrade -y && apt install -y libssl1.1 ca-certificates
|
||||
|
||||
WORKDIR /app
|
||||
|
||||
COPY --from=builder /app/target/release/endstat /app
|
||||
COPY ./config /app/config
|
||||
COPY ./templates /app/templates
|
||||
RUN mv /app/config/endstat_conf.example.ron /app/config/endstat_conf.ron
|
||||
EXPOSE 8080
|
||||
|
||||
CMD ["/app/endstat"]
|
31
README.md
31
README.md
|
@ -1,6 +1,31 @@
|
|||
# endstat
|
||||
|
||||
EndStat is an easy-to-use lazy **End**point **Stat**us checking tool, meant for
|
||||
`endstat` is an easy-to-use **End**point **Stat**us checking tool, meant for
|
||||
checking the health of various web locations. It supports arbitrary domains and
|
||||
ports, status matching, and body matching using a quick-to-understand config
|
||||
file.
|
||||
ports, status matching, and body matching using [ron][ron], a quick-to-understand config
|
||||
file notation, built in [Rust][rust] using [actix][actix].
|
||||
|
||||
My motivation was that I wanted to make a dashboard that was easy-to-use to make
|
||||
sure my homelab services were running when I screwed around with config files.
|
||||
|
||||
[ron]: https://github.com/ron-rs/ron
|
||||
[rust]: https://rust-lang.org
|
||||
[actix]: https://github.com/ron-rs/ron
|
||||
|
||||
## Features
|
||||
- HTTP/HTTPS
|
||||
- Arbitrary ports
|
||||
- Expected body and/or status code responses
|
||||
- Optional no redirect following
|
||||
- API endpoints (`/api`, `/rss`)
|
||||
- Webhooks
|
||||
|
||||
## Getting started
|
||||
|
||||
There's an example config file that you can simply rename to `endstat_conf.ron`.
|
||||
It should be a relatively comprehensive example of what sort of flexibility
|
||||
`endstat` offers.
|
||||
|
||||
If you're building from source, execute `cargo run`.
|
||||
|
||||
If you've gotten this binary from somewhere else, simply execute it.
|
||||
|
|
|
@ -0,0 +1,44 @@
|
|||
#![enable(implicit_some)]
|
||||
(
|
||||
refresh_time: 60,
|
||||
bind_address: "0.0.0.0:8080",
|
||||
|
||||
websites: [
|
||||
(
|
||||
label: "Basic usage",
|
||||
endpoints: [
|
||||
(label: "Supports HTTPS", endpoint: "https://example.com"),
|
||||
(label: "Supports HTTP", endpoint: "http://example.com"),
|
||||
(label: "Supports no redirection", endpoint: "http://google.com", code: 301, follow_redirects: false),
|
||||
]
|
||||
),
|
||||
(
|
||||
label: "More features!",
|
||||
base: "http://portquiz.net/",
|
||||
endpoints: [
|
||||
(label: "You can even set a base url"),
|
||||
(label: "Or use different ports", port: 8080),
|
||||
],
|
||||
),
|
||||
(
|
||||
label: "Even more stuff!",
|
||||
endpoints: [
|
||||
(label: "Or expect different reponse codes (like 418)", endpoint: "http://error418.net/", code: 418),
|
||||
(label: "Or response checking!", endpoint: "http://urlecho.appspot.com/echo", body: "None"),
|
||||
(label: "Or response hash comparison!", endpoint: "http://urlecho.appspot.com/echo", body_hash: "dc937b59892604f5a86ac96936cd7ff09e25f18ae6b758e8014a24c7fa039e91"),
|
||||
(label: "Or a combination!", endpoint: "http://urlecho.appspot.com/echo?status=503&Content-Type=text%2Fhtml&body=None", body: "None", code: 503),
|
||||
(label: "Or expect the endpoint to fail entirely!", endpoint: "http://lol.arpa", should_err: true),
|
||||
],
|
||||
),
|
||||
(
|
||||
label: "Some error messages",
|
||||
endpoints:[
|
||||
(label: "The code doesn't match!", endpoint: "http://example.com/", code: 204),
|
||||
(label: "The body doesn't match!", endpoint: "http://example.com/", body: "asdf"),
|
||||
(label: "Slow reponse time", endpoint: "http://slowwly.robertomurray.co.uk/delay/2000/url/", max_rtt: 1337),
|
||||
(label: "Plethora of issues!", endpoint: "http://slowwly.robertomurray.co.uk/delay/1000/url/", body: "asdf", code: 418, max_rtt: 50),
|
||||
(label: "Here's an error:", endpoint: "https://some-invalid-website.arpa")
|
||||
]
|
||||
),
|
||||
]
|
||||
)
|
|
@ -1,5 +1,19 @@
|
|||
use serde::{Deserialize, Serialize};
|
||||
|
||||
#[derive(Deserialize, Serialize, Debug, Clone, Default)]
|
||||
pub struct Config {
|
||||
pub refresh_time: u64,
|
||||
pub bind_address: String,
|
||||
pub websites: Vec<WebsiteConfig>,
|
||||
}
|
||||
|
||||
#[derive(Deserialize, Serialize, Debug, Clone)]
|
||||
pub struct WebsiteConfig {
|
||||
pub label: String,
|
||||
pub base: Option<String>,
|
||||
pub endpoints: Vec<EndpointConfig>,
|
||||
}
|
||||
|
||||
#[derive(Deserialize, Serialize, Debug, Clone)]
|
||||
pub struct EndpointConfig {
|
||||
pub label: Option<String>,
|
||||
|
@ -7,20 +21,20 @@ pub struct EndpointConfig {
|
|||
pub port: Option<u16>,
|
||||
pub code: Option<u16>,
|
||||
pub body: Option<String>,
|
||||
pub body_hash: Option<String>,
|
||||
pub follow_redirects: Option<bool>,
|
||||
pub max_rtt: Option<i64>,
|
||||
pub should_err: Option<bool>,
|
||||
pub webhooks: Option<Webhooks>,
|
||||
}
|
||||
|
||||
#[derive(Deserialize, Serialize, Debug, Clone)]
|
||||
pub struct WebsiteConfig {
|
||||
pub label: String,
|
||||
pub base: String,
|
||||
pub endpoints: Vec<EndpointConfig>,
|
||||
}
|
||||
|
||||
#[derive(Deserialize, Serialize, Debug, Clone, Default)]
|
||||
pub struct Config {
|
||||
pub refresh_time: u64,
|
||||
pub bind_address: String,
|
||||
pub websites: Vec<WebsiteConfig>,
|
||||
pub struct Webhooks {
|
||||
pub on_change: Option<String>,
|
||||
pub on_ok: Option<String>,
|
||||
pub on_warn: Option<String>,
|
||||
pub on_error: Option<String>,
|
||||
pub on_not_ok: Option<String>,
|
||||
}
|
||||
|
||||
pub fn get_endpoint_info(endpoint: EndpointConfig) -> (String, String, Option<u16>, u16, String) {
|
||||
|
|
128
src/handlers.rs
128
src/handlers.rs
|
@ -1,33 +1,11 @@
|
|||
use crate::config::*;
|
||||
use crate::utils::EpochTimestamp;
|
||||
use crate::State;
|
||||
use actix_web::{
|
||||
error::ErrorInternalServerError, web::Data, Error as WebError, HttpResponse,
|
||||
Result as WebResult,
|
||||
};
|
||||
use reqwest::{Client, Url, UrlError};
|
||||
|
||||
use serde::Serialize;
|
||||
use std::sync::{Arc, MutexGuard, RwLock, RwLockWriteGuard};
|
||||
use tera::{Context, Tera};
|
||||
|
||||
#[derive(Clone, Serialize, Default, Debug)]
|
||||
pub struct Status {
|
||||
status: u8,
|
||||
location: String,
|
||||
domain: String,
|
||||
endpoint: String,
|
||||
error: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Serialize, Debug)]
|
||||
pub struct QueryResults {
|
||||
pub last_update: EpochTimestamp,
|
||||
pub refresh_time: u64,
|
||||
pub config: Config,
|
||||
pub statuses: Vec<Status>,
|
||||
}
|
||||
|
||||
type State = Arc<RwLock<QueryResults>>;
|
||||
#[cfg(feature = "rss_feed")]
|
||||
use rss::{ChannelBuilder, ItemBuilder};
|
||||
|
||||
pub fn index(tmpl: Data<Tera>, state: Data<State>) -> WebResult<HttpResponse, WebError> {
|
||||
let state = state.read().unwrap();
|
||||
|
@ -40,88 +18,38 @@ pub fn index(tmpl: Data<Tera>, state: Data<State>) -> WebResult<HttpResponse, We
|
|||
Ok(HttpResponse::Ok().content_type("text/html").body(s))
|
||||
}
|
||||
|
||||
#[cfg(feature = "json")]
|
||||
pub fn json_endpoint(state: Data<State>) -> HttpResponse {
|
||||
let state = state.read().unwrap();
|
||||
HttpResponse::Ok().json(&state.statuses)
|
||||
HttpResponse::Ok().json(&*state.groups)
|
||||
}
|
||||
|
||||
pub fn update_state(mut state: RwLockWriteGuard<QueryResults>) -> RwLockWriteGuard<QueryResults> {
|
||||
if EpochTimestamp::now() - state.last_update >= state.refresh_time {
|
||||
state.last_update = EpochTimestamp::now();
|
||||
state.statuses = update_status(&state.config);
|
||||
}
|
||||
#[cfg(feature = "rss_feed")]
|
||||
pub fn rss_endpoint(state: Data<State>) -> HttpResponse {
|
||||
let state = state.read().unwrap();
|
||||
let mut chan = ChannelBuilder::default()
|
||||
.title("endstat")
|
||||
.description("Endpoint statuses")
|
||||
.link("https://git.eddie.sh/edward/endstat")
|
||||
.build()
|
||||
.unwrap();
|
||||
|
||||
state
|
||||
}
|
||||
let mut endpoints = vec![];
|
||||
|
||||
fn update_status(config: &Config) -> Vec<Status> {
|
||||
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));
|
||||
for group in &state.groups {
|
||||
for endpoint in &group.endpoints {
|
||||
endpoints.push(
|
||||
ItemBuilder::default()
|
||||
.title(format!("{}: {}", group.label, endpoint.label))
|
||||
.link(endpoint.location.clone())
|
||||
.description(Some(endpoint.status.clone().into()))
|
||||
.build()
|
||||
.unwrap()
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
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())
|
||||
chan.set_items(endpoints);
|
||||
|
||||
HttpResponse::Ok().content_type("application/rss+xml").body(chan.to_string())
|
||||
}
|
||||
|
|
69
src/main.rs
69
src/main.rs
|
@ -1,68 +1,81 @@
|
|||
extern crate actix;
|
||||
extern crate actix_web;
|
||||
extern crate env_logger;
|
||||
extern crate reqwest;
|
||||
extern crate ron;
|
||||
extern crate serde;
|
||||
extern crate tokio;
|
||||
#![forbid(unsafe_code)]
|
||||
|
||||
#[macro_use]
|
||||
extern crate log;
|
||||
#[macro_use]
|
||||
extern crate tera;
|
||||
|
||||
#[cfg(feature = "rss_feed")]
|
||||
extern crate rss;
|
||||
|
||||
mod config;
|
||||
mod handlers;
|
||||
mod utils;
|
||||
mod results;
|
||||
mod updater;
|
||||
|
||||
use self::config::*;
|
||||
use self::handlers::*;
|
||||
use self::utils::EpochTimestamp;
|
||||
use self::{config::*, handlers::*, results::QueryResults, updater::*};
|
||||
use actix::System;
|
||||
use actix_web::{middleware::Logger, web::resource, App, HttpServer};
|
||||
use ron::de::from_str;
|
||||
use std::{
|
||||
env::var,
|
||||
fs::read_to_string,
|
||||
sync::{Arc, RwLock},
|
||||
time::Duration,
|
||||
};
|
||||
use tokio::prelude::{Future, Stream};
|
||||
use tokio::timer::Interval;
|
||||
use tokio::{
|
||||
prelude::{Future, Stream},
|
||||
timer::Interval,
|
||||
};
|
||||
|
||||
pub type State = Arc<RwLock<QueryResults>>;
|
||||
|
||||
fn main() {
|
||||
System::run(move || {
|
||||
System::run(|| {
|
||||
let conf_file_loc =
|
||||
var("ENDSTAT_CONF").unwrap_or_else(|_| String::from("./config/endstat_conf.ron"));
|
||||
let config = from_str::<Config>(
|
||||
&read_to_string("./endstat_conf.ron").expect("Could not find config file"),
|
||||
&read_to_string(&conf_file_loc).unwrap_or_else(|_| panic!("finding {}", conf_file_loc)),
|
||||
)
|
||||
.unwrap();
|
||||
let bind_addr = config.bind_address.clone();
|
||||
let bind_addr = &config.bind_address;
|
||||
std::env::set_var("RUST_LOG", "actix_web=info");
|
||||
env_logger::init();
|
||||
|
||||
let state = Arc::new(RwLock::new(QueryResults {
|
||||
last_update: EpochTimestamp::now(),
|
||||
refresh_time: config.refresh_time.clone(),
|
||||
config: config.clone(),
|
||||
statuses: vec![],
|
||||
}));
|
||||
let state = Arc::new(RwLock::new(QueryResults::new(config.clone())));
|
||||
|
||||
let clone_state = Arc::clone(&state);
|
||||
|
||||
HttpServer::new(move || {
|
||||
let tera = compile_templates!(concat!(env!("CARGO_MANIFEST_DIR"), "/templates/**/*"));
|
||||
let tera = compile_templates!("./templates/**/*");
|
||||
let state = Arc::clone(&state);
|
||||
|
||||
App::new()
|
||||
let mut app = App::new()
|
||||
.data(state)
|
||||
.data(tera)
|
||||
.wrap(Logger::default())
|
||||
.service(resource("/").to(index))
|
||||
.service(resource("/api").to(json_endpoint))
|
||||
.service(resource("/").to(index));
|
||||
|
||||
#[cfg(feature = "json")]
|
||||
{
|
||||
app = app.service(resource("/json").to(json_endpoint));
|
||||
}
|
||||
|
||||
#[cfg(feature = "rss_feed")]
|
||||
{
|
||||
app = app.service(resource("/rss").to(rss_endpoint));
|
||||
}
|
||||
|
||||
app
|
||||
})
|
||||
.bind(&bind_addr)
|
||||
.expect("Could not bind to address!")
|
||||
.start();
|
||||
|
||||
tokio::spawn(
|
||||
Interval::new_interval(Duration::from_millis(5000))
|
||||
Interval::new_interval(Duration::from_secs(config.refresh_time))
|
||||
.for_each(move |_| {
|
||||
let _ = update_state(clone_state.write().unwrap());
|
||||
update_state(Arc::clone(&clone_state));
|
||||
Ok(())
|
||||
})
|
||||
.map_err(|_| ()),
|
||||
|
|
|
@ -0,0 +1,201 @@
|
|||
use crate::{config::*, updater::update_status};
|
||||
use chrono::prelude::*;
|
||||
#[cfg(feature = "webhooks")]
|
||||
use reqwest::Client;
|
||||
use serde::{Serialize, Serializer};
|
||||
|
||||
#[derive(Serialize, Debug)]
|
||||
pub struct QueryResults {
|
||||
pub timestamp: DateTime<Utc>,
|
||||
pub timestamp_str: String,
|
||||
pub refresh_time: u64,
|
||||
pub config: Config,
|
||||
pub groups: Vec<StatusGroup>,
|
||||
}
|
||||
|
||||
impl QueryResults {
|
||||
pub fn new(config: Config) -> Self {
|
||||
let time = Utc::now();
|
||||
QueryResults {
|
||||
timestamp: time,
|
||||
timestamp_str: Self::format_timestamp(time),
|
||||
refresh_time: config.refresh_time,
|
||||
config: config.clone(),
|
||||
groups: update_status(&config),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn update(&mut self, updated_groups: Vec<StatusGroup>) {
|
||||
self.update_timestamp();
|
||||
#[cfg(feature = "webhooks")]
|
||||
{
|
||||
let client = Client::new();
|
||||
|
||||
// Async blocker: we will need to rewrite this part once async has
|
||||
// been stabilized, or make it so that the order of websites is an
|
||||
// invariant after implementing async. Probably use a hashmap?
|
||||
for group in 0..self.groups.len() {
|
||||
for endpoint in 0..self.groups[group].endpoints.len() {
|
||||
let old_endpoint = &self.groups[group].endpoints[endpoint];
|
||||
let new_endpoint = &updated_groups[group].endpoints[endpoint];
|
||||
if old_endpoint != new_endpoint {
|
||||
panic!("endpoint order was not maintained");
|
||||
}
|
||||
|
||||
if new_endpoint.errors != old_endpoint.errors {
|
||||
if let Some(webhooks) =
|
||||
&self.config.websites[group].endpoints[endpoint].webhooks
|
||||
{
|
||||
macro_rules! gen_hooks {
|
||||
($(($hook:ident, $cond:expr)),*) => {
|
||||
$(if let Some(url) = &webhooks.$hook {
|
||||
if new_endpoint.status == $cond {
|
||||
if let Err(e) = client.post(url).json(new_endpoint).send() {
|
||||
warn!("{}", e)
|
||||
}
|
||||
}
|
||||
})*
|
||||
};
|
||||
}
|
||||
|
||||
gen_hooks!(
|
||||
(on_change, new_endpoint.status),
|
||||
(on_ok, EndpointStatus::OK),
|
||||
(on_warn, EndpointStatus::WARN),
|
||||
(on_error, EndpointStatus::ERROR),
|
||||
(on_not_ok, EndpointStatus::OK)
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
self.groups = updated_groups;
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn update_timestamp(&mut self) {
|
||||
let current_time = Utc::now();
|
||||
self.timestamp = current_time;
|
||||
self.timestamp_str = Self::format_timestamp(current_time);
|
||||
}
|
||||
|
||||
fn format_timestamp(timestamp: DateTime<Utc>) -> String {
|
||||
timestamp.format("%Y-%m-%d %H:%M:%S").to_string()
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Serialize, Debug)]
|
||||
pub struct StatusGroup {
|
||||
pub label: String,
|
||||
pub endpoints: Vec<Endpoint>,
|
||||
}
|
||||
|
||||
/// This holds the results of pinging a single endpoint. RTT exists iff there
|
||||
/// aren't any errors.
|
||||
#[derive(Clone, Serialize, Debug)]
|
||||
pub struct Endpoint {
|
||||
pub status: EndpointStatus,
|
||||
pub location: String,
|
||||
pub label: String,
|
||||
pub rtt: Option<String>,
|
||||
pub errors: Vec<String>,
|
||||
}
|
||||
|
||||
impl PartialEq for Endpoint {
|
||||
fn eq(&self, other: &Endpoint) -> bool {
|
||||
self.location == other.location && self.label == other.label
|
||||
}
|
||||
}
|
||||
|
||||
/// Various helper functions for generating resulting statuses
|
||||
impl Endpoint {
|
||||
pub fn ok(location: String, label: String, rtt: String) -> Self {
|
||||
Endpoint {
|
||||
status: EndpointStatus::OK,
|
||||
location,
|
||||
label,
|
||||
rtt: Some(rtt),
|
||||
errors: vec![],
|
||||
}
|
||||
}
|
||||
|
||||
pub fn warn(location: String, label: String, rtt: String, errors: Vec<String>) -> Self {
|
||||
Endpoint {
|
||||
status: EndpointStatus::WARN,
|
||||
location,
|
||||
label,
|
||||
rtt: Some(rtt),
|
||||
errors,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn error(location: String, label: String, errors: Vec<String>) -> Self {
|
||||
Endpoint {
|
||||
status: EndpointStatus::ERROR,
|
||||
location,
|
||||
label,
|
||||
rtt: None,
|
||||
errors,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn maintenance(location: String, label: String, errors: Vec<String>) -> Self {
|
||||
Endpoint {
|
||||
status: EndpointStatus::MAINTENANCE,
|
||||
location,
|
||||
label,
|
||||
rtt: None,
|
||||
errors,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn unknown(location: String, label: String, errors: Vec<String>) -> Self {
|
||||
Endpoint {
|
||||
status: EndpointStatus::UNKNOWN,
|
||||
location,
|
||||
label,
|
||||
rtt: None,
|
||||
errors,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub enum EndpointStatus {
|
||||
OK,
|
||||
WARN,
|
||||
ERROR,
|
||||
MAINTENANCE,
|
||||
UNKNOWN,
|
||||
}
|
||||
|
||||
/// Custom serialization implementation, since its rendered form will be as a
|
||||
/// CSS class. The default serialization keeps things uppercase, which is
|
||||
/// discouraged as CSS class names.
|
||||
impl Serialize for EndpointStatus {
|
||||
fn serialize<S>(&self, s: S) -> Result<S::Ok, S::Error>
|
||||
where
|
||||
S: Serializer,
|
||||
{
|
||||
s.serialize_str(match *self {
|
||||
EndpointStatus::OK => "ok",
|
||||
EndpointStatus::WARN => "warn",
|
||||
EndpointStatus::ERROR => "error",
|
||||
EndpointStatus::MAINTENANCE => "maintenance",
|
||||
EndpointStatus::UNKNOWN => "unknown",
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
impl Into<String> for EndpointStatus {
|
||||
fn into(self) -> String {
|
||||
match self {
|
||||
EndpointStatus::OK => String::from("ok"),
|
||||
EndpointStatus::WARN => String::from("warn"),
|
||||
EndpointStatus::ERROR => String::from("error"),
|
||||
EndpointStatus::MAINTENANCE => String::from("maintenance"),
|
||||
EndpointStatus::UNKNOWN => String::from("unknown"),
|
||||
}
|
||||
}
|
||||
}
|
|
@ -0,0 +1,125 @@
|
|||
use crate::{
|
||||
config::*,
|
||||
results::{Endpoint, StatusGroup},
|
||||
State,
|
||||
};
|
||||
use chrono::Utc;
|
||||
use reqwest::{Client, RedirectPolicy, Url, UrlError};
|
||||
use ring::{
|
||||
digest::{digest, SHA256},
|
||||
test::from_hex,
|
||||
};
|
||||
use std::time::Duration;
|
||||
|
||||
pub fn update_state(state: State) {
|
||||
let new_statuses = { Some(update_status(&state.read().unwrap().config)) };
|
||||
let mut state = state.try_write().expect("Could not unlock");
|
||||
state.update(new_statuses.unwrap());
|
||||
}
|
||||
|
||||
pub fn update_status(config: &Config) -> Vec<StatusGroup> {
|
||||
let mut results: Vec<StatusGroup> = Vec::with_capacity(config.websites.len());
|
||||
|
||||
for website_conf in &config.websites {
|
||||
let mut group = Vec::with_capacity(website_conf.endpoints.len());
|
||||
for endpoint in &website_conf.endpoints {
|
||||
let mut client_builder = Client::builder().timeout(Some(Duration::from_secs(5)));
|
||||
|
||||
if let Some(false) = endpoint.follow_redirects {
|
||||
client_builder = client_builder.redirect(RedirectPolicy::none());
|
||||
}
|
||||
|
||||
let client = client_builder.build().unwrap();
|
||||
group.push(get_result(website_conf, &client, endpoint));
|
||||
}
|
||||
|
||||
results.push(StatusGroup {
|
||||
label: website_conf.label.clone(),
|
||||
endpoints: group,
|
||||
});
|
||||
}
|
||||
|
||||
results
|
||||
}
|
||||
|
||||
fn get_result(
|
||||
website_conf: &WebsiteConfig,
|
||||
client: &Client,
|
||||
endpoint: &EndpointConfig,
|
||||
) -> Endpoint {
|
||||
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_start = Utc::now();
|
||||
let ping_result = client.get(&url).send();
|
||||
let rtt = Utc::now() - ping_start;
|
||||
let rtt_string = if rtt.num_seconds() > 0 {
|
||||
format!("{}s", rtt.num_milliseconds() as f64 / 1000.)
|
||||
} else {
|
||||
format!("{}ms", rtt.num_milliseconds())
|
||||
};
|
||||
|
||||
match ping_result {
|
||||
Ok(mut res) => {
|
||||
let res_body = res.text().expect("could not get body of request");
|
||||
let mut errors = vec![];
|
||||
|
||||
if res.status() != code {
|
||||
errors.push(format!(
|
||||
"Status code mismatch: {} != {}",
|
||||
res.status().as_u16(),
|
||||
code
|
||||
));
|
||||
}
|
||||
|
||||
if let Some(expected_hash) = &endpoint.body_hash {
|
||||
let expected = from_hex(expected_hash).unwrap();
|
||||
let actual = digest(&SHA256, res_body.as_bytes());
|
||||
if expected != actual.as_ref() {
|
||||
errors.push(String::from("Body hash mismatch."));
|
||||
}
|
||||
} else if !body.is_empty() && res_body != body {
|
||||
errors.push(format!(
|
||||
"Body mismatch: {} != {}",
|
||||
res_body.len(),
|
||||
body.len()
|
||||
));
|
||||
}
|
||||
|
||||
if let Some(max_rtt) = endpoint.max_rtt {
|
||||
if rtt.num_milliseconds() > max_rtt {
|
||||
errors.push(format!(
|
||||
"RTT too long: {} > {}s",
|
||||
rtt_string,
|
||||
max_rtt as f64 / 1000.
|
||||
));
|
||||
}
|
||||
}
|
||||
|
||||
if !errors.is_empty() {
|
||||
Endpoint::warn(url, label, rtt_string, errors)
|
||||
} else {
|
||||
Endpoint::ok(url, label, rtt_string)
|
||||
}
|
||||
}
|
||||
Err(e) => {
|
||||
if let Some(true) = endpoint.should_err {
|
||||
Endpoint::ok(url, label, rtt_string)
|
||||
} else {
|
||||
Endpoint::error(url, label, vec![format!("{}", e)])
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn get_url(base: &Option<String>, path: &str, port: Option<u16>) -> Result<String, UrlError> {
|
||||
let mut url = if let Some(base) = base {
|
||||
Url::parse(base)?.join(path)?
|
||||
} else {
|
||||
Url::parse(path)?
|
||||
};
|
||||
if let Err(e) = url.set_port(port) {
|
||||
println!("{:?}", e);
|
||||
}
|
||||
Ok(url.into_string())
|
||||
}
|
49
src/utils.rs
49
src/utils.rs
|
@ -1,49 +0,0 @@
|
|||
use serde::{Serialize, Serializer};
|
||||
use std::{
|
||||
fmt::{Display, Formatter, Result as FmtResult},
|
||||
ops::Sub,
|
||||
time::{SystemTime, UNIX_EPOCH},
|
||||
};
|
||||
|
||||
#[derive(PartialEq, PartialOrd, Copy, Clone, Debug)]
|
||||
pub struct EpochTimestamp(SystemTime);
|
||||
|
||||
impl EpochTimestamp {
|
||||
pub fn now() -> Self {
|
||||
EpochTimestamp(SystemTime::now())
|
||||
}
|
||||
}
|
||||
|
||||
impl Sub for EpochTimestamp {
|
||||
type Output = u64;
|
||||
fn sub(self, other: EpochTimestamp) -> u64 {
|
||||
self.0.duration_since(other.0).unwrap_or_default().as_secs()
|
||||
}
|
||||
}
|
||||
|
||||
impl Display for EpochTimestamp {
|
||||
fn fmt(&self, f: &mut Formatter) -> FmtResult {
|
||||
write!(
|
||||
f,
|
||||
"{}",
|
||||
self.0
|
||||
.duration_since(UNIX_EPOCH)
|
||||
.unwrap_or_default()
|
||||
.as_secs()
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
impl Serialize for EpochTimestamp {
|
||||
fn serialize<S>(&self, s: S) -> Result<S::Ok, S::Error>
|
||||
where
|
||||
S: Serializer,
|
||||
{
|
||||
s.serialize_u64(
|
||||
self.0
|
||||
.duration_since(SystemTime::from(UNIX_EPOCH))
|
||||
.unwrap_or_default()
|
||||
.as_secs(),
|
||||
)
|
||||
}
|
||||
}
|
|
@ -3,56 +3,80 @@
|
|||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="utf-8"/>
|
||||
<title>Endstat</title>
|
||||
<title>endstat</title>
|
||||
<link href="https://fonts.googleapis.com/css?family=Montserrat:200|Source+Code+Pro:400" rel="stylesheet">
|
||||
<style>
|
||||
body {
|
||||
background-color: #212121;
|
||||
margin: 0;
|
||||
color: #fff;
|
||||
font-family: 'Montserrat', sans-serif;
|
||||
width: 700px;
|
||||
margin: 0 auto;
|
||||
margin-top: 5rem;
|
||||
}
|
||||
|
||||
main {
|
||||
width: 700px;
|
||||
margin: 0 auto;
|
||||
padding: 1rem;
|
||||
width: 100%;
|
||||
}
|
||||
|
||||
header {
|
||||
display: flex;
|
||||
align-items: flex-end;
|
||||
justify-content: space-between;
|
||||
}
|
||||
|
||||
section {
|
||||
display: flex;
|
||||
align-items: stretch;
|
||||
background-color: #424242;
|
||||
align-items: center;
|
||||
margin: 1rem 0;
|
||||
padding: 1rem;
|
||||
border-radius: 1rem;
|
||||
border-radius: .5rem;
|
||||
}
|
||||
|
||||
p { margin: 0; }
|
||||
a { color: #fff; text-decoration: none; }
|
||||
h1 { margin: 0; }
|
||||
|
||||
h1 { display: inline; }
|
||||
h3 { margin: 0; text-align: justify; flex-shrink: 0; }
|
||||
.info { display: flex; align-items: baseline; }
|
||||
.info a { text-align: right; }
|
||||
.spacer { flex: 1 0 1rem; }
|
||||
|
||||
.indicator {
|
||||
width: 1rem;
|
||||
height: 1rem;
|
||||
border-radius: 1rem;
|
||||
min-height: 100%;
|
||||
border-radius: .5rem 0 0 .5rem;
|
||||
}
|
||||
.ok { background-color: green; }
|
||||
.warn { background-color: yellow; }
|
||||
.error { background-color: red; }
|
||||
.ok { background-color: #4ed34e; }
|
||||
.warn { background-color: #fcfc64; }
|
||||
.error { background-color: #ff392e; }
|
||||
.error-msg { margin-top: 1rem; font-family: 'Source Code Pro', monospace; }
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<main>
|
||||
<h1>Welcome!</h1>
|
||||
<h1>{{ results.last_update }}</h1>
|
||||
{% for status in results.statuses -%}
|
||||
<section>
|
||||
<p>{{ status.domain }}</p>
|
||||
<p>{{ status.endpoint }}</p>
|
||||
<p>{{ status.location }}</p>
|
||||
{% if status.error %}<p>{{ status.error }}</p>{% endif %}
|
||||
<div class="indicator {% if status.status == 0 %}ok{% elif status.status == 1 %}warn{% else %}error{% endif %}"></div>
|
||||
|
||||
</section>
|
||||
<header>
|
||||
<h1>Status Overview</h1>
|
||||
<p>{{ results.timestamp_str }}</p>
|
||||
</header>
|
||||
{% for group in results.groups -%}
|
||||
<h2>{{ group.label }}</h2>
|
||||
{% for status in group.endpoints -%}
|
||||
<section>
|
||||
<aside class="indicator {{ status.status }}"></aside>
|
||||
<main>
|
||||
<div class="info">
|
||||
<h3>{{ status.label }}</h3>
|
||||
<div class="spacer"></div>
|
||||
{% if status.status != 2 %}<p>{{ status.rtt }}</p>{% endif %}
|
||||
</div>
|
||||
<a href="{{ status.location }}" target="_blank">{{ status.location }}</a>
|
||||
{% for msg in status.errors -%}
|
||||
<p class="error-msg">{{ msg }}</p>
|
||||
{% endfor -%}
|
||||
</main>
|
||||
</section>
|
||||
{% endfor -%}
|
||||
{% endfor -%}
|
||||
</main>
|
||||
</body>
|
||||
</html>
|
||||
|
|
Loading…
Reference in New Issue