aboutsummaryrefslogtreecommitdiff
path: root/src/main.rs
blob: 706effe886cc7e1de92d0134ee6a568b3f2caeae (plain)
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
pub mod check;
pub mod log;
pub mod mail;
pub mod web;

use ::log::error;
use anyhow::{anyhow, Result};
use axum::{routing::get, Router};
use check::check_loop;
use mail::MailConfig;
use serde::Deserialize;
use std::{
    collections::BTreeMap,
    net::SocketAddr,
    sync::Arc,
    time::{Duration, SystemTime},
};
use tokio::{fs::read_to_string, sync::RwLock};
use web::send_html_page;

pub static GLOBAL_ERROR: RwLock<Option<anyhow::Error>> = RwLock::const_new(None);

#[tokio::main]
async fn main() {
    env_logger::init_from_env("LOG");
    if let Err(e) = run().await {
        error!("{e:?}")
    }
}

#[derive(Debug, Deserialize)]
pub struct Config {
    mail: Option<MailConfig>,
    title: String,
    bind: SocketAddr,
    interval: u64,
    services: Vec<Service>,
}

#[derive(Debug, Deserialize)]
pub struct Service {
    title: String,
    url: Option<String>,
    checks: Vec<Check>,
}

#[derive(Debug, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum Check {
    Systemd(String),
    Http { title: Option<String>, url: String },
    Shell { title: String, command: String },
}

#[derive(Debug, Clone)]
pub struct Success {
    pub latency: Option<Duration>,
    pub updated: SystemTime,
}
impl Default for Success {
    fn default() -> Self {
        Self {
            latency: None,
            updated: SystemTime::now(),
        }
    }
}

static STATUS: RwLock<BTreeMap<(usize, usize), Result<Success>>> =
    RwLock::const_new(BTreeMap::new());

async fn run() -> anyhow::Result<()> {
    let config = std::env::args()
        .nth(1)
        .ok_or(anyhow!("expected config path as first argument"))?;
    let config = read_to_string(config).await?;
    let config = Arc::<Config>::new(serde_yaml::from_str(&config)?);

    for i in 0..config.services.len() {
        tokio::task::spawn(check_loop(config.clone(), i));
    }

    let app = Router::new().route(
        "/",
        get({
            let config = config.clone();
            move || send_html_page(config.clone())
        }),
    );
    let listener = tokio::net::TcpListener::bind(config.bind).await?;
    axum::serve(listener, app).await?;
    Ok(())
}