aboutsummaryrefslogtreecommitdiff
path: root/src/main.rs
blob: 7f550898d1b080968ab91ead12ac636a414b6fa1 (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
#![feature(exit_status_error)]
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, Check};
use chrono::{DateTime, Utc};
use mail::MailConfig;
use serde::Deserialize;
use std::{collections::BTreeMap, net::SocketAddr, process::exit, sync::Arc};
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:?}");
        exit(1);
    }
}

#[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>,
    #[serde(default)]
    mail_to: Vec<String>,
}

#[derive(Debug, Clone)]
pub struct Status {
    pub time: DateTime<Utc>,
    pub status: Result<String, String>,
}

static STATUS: RwLock<BTreeMap<(usize, usize), Status>> = 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(())
}