/*
* Copyright (C) 2024 Jonni Liljamo <jonni@liljamo.com>
*
* This file is licensed under GPL-3.0-or-later, see NOTICE and LICENSE for
* more information.
*/
use clap::Parser;
use emerwen_protocol::emerwen::shared::{
target::{MethodGet, MethodPing},
Target, Worker,
};
use tokio::sync::mpsc;
use tracing::{debug, info, level_filters::LevelFilter};
use tracing_subscriber::{prelude::*, EnvFilter};
mod db;
use db::DatabaseHandle;
mod ipc_server;
mod worker_server;
#[derive(Parser)]
#[command(version)]
struct Args {
/// Enable debug logging
#[arg(long)]
debug: bool,
/// Location of the database file
#[arg(long, default_value = "./tmp/db.redb")]
database_file: String,
/// Location of the "IPC" socket
#[arg(long, default_value = "./tmp/master.sock")]
ipc_socket_location: String,
/// IPC auth token
#[arg(long, default_value = "ipc_avain_prkl")]
ipc_auth_token: String,
}
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
let args = Args::parse();
tracing_subscriber::registry()
.with(
tracing_subscriber::fmt::layer()
.with_file(args.debug)
.with_line_number(args.debug)
.with_level(true),
)
.with(
EnvFilter::builder()
.with_default_directive(if args.debug {
LevelFilter::DEBUG.into()
} else {
LevelFilter::INFO.into()
})
.from_env_lossy(),
)
.init();
let addr = "127.0.0.1:8000";
info!(msg = "Starting emerwen master...", %addr);
debug!("Hello, debug!");
let db_handle = DatabaseHandle::new(std::path::Path::new(&args.database_file))?;
let db_handle_worker_server = db_handle.clone();
let (worker_server_tx, worker_server_rx) = mpsc::channel::<worker_server::Message>(8);
tokio::spawn(async move {
let _ = worker_server::run(addr.into(), db_handle_worker_server, worker_server_rx).await;
});
let db_handle_ipc_server = db_handle.clone();
let (_ipc_server_tx, ipc_server_rx) = mpsc::channel::<ipc_server::Message>(8);
tokio::spawn(async move {
let _ = ipc_server::run(
std::path::Path::new(&args.ipc_socket_location),
db_handle_ipc_server,
ipc_server_rx,
)
.await;
});
let _ = db_handle
.write_worker(Worker {
id: 0,
auth_token: "avain_perkele".into(),
targets: vec![
Target {
id: 0,
addr: "127.0.0.1".into(),
interval: 2000,
method: Some(MethodPing {}.into()),
},
Target {
id: 1,
addr: "https://liljamo.com/".into(),
interval: 2000,
method: Some(
MethodGet {
ok_codes: vec![200],
}
.into(),
),
},
Target {
id: 2,
addr: "10.1.2.30".into(),
interval: 2000,
method: Some(MethodPing {}.into()),
},
],
})
.await;
worker_server_tx
.send(worker_server::Message::ReloadWorkers)
.await?;
loop {
let _ = tokio::time::sleep(std::time::Duration::from_millis(5000)).await;
}
//Ok(())
}