use clap::Parser;
use emerwen_protocol::emerwen_protocol_client::EmerwenProtocolClient;
use tonic::{metadata::MetadataValue, service::Interceptor, transport::Channel};
use tracing::{debug, info, level_filters::LevelFilter};
use tracing_subscriber::{prelude::*, EnvFilter};
mod monitor;
#[derive(Parser)]
#[command(version)]
struct Args {
/// Enable debug logging
#[arg(long)]
debug: bool,
}
#[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();
info!("Starting emerwen worker...");
debug!("Hello, debug!");
// TODO: token from cli, also addr from cli
// Client is cheap to clone, clone one to every monitoring task
let mut client = EmerwenProtocolClient::with_interceptor(
Channel::from_static("http://127.0.0.1:8000")
.connect()
.await?,
AuthInterceptor {
token: "Bearer avain_perkele".parse()?,
},
);
let targets_response = client.get_targets(()).await?.into_inner();
info!("{:?}", targets_response);
for target in targets_response.targets {
let mut monitor = monitor::TargetMonitor::new(target, client.clone());
tokio::task::spawn(async move {
let _ = monitor.run().await;
});
}
loop {
tokio::time::sleep(std::time::Duration::new(5, 0)).await;
}
}
#[derive(Clone)]
struct AuthInterceptor {
token: MetadataValue<tonic::metadata::Ascii>,
}
impl Interceptor for AuthInterceptor {
fn call(
&mut self,
mut request: tonic::Request<()>,
) -> Result<tonic::Request<()>, tonic::Status> {
request
.metadata_mut()
.insert("authorization", self.token.clone());
Ok(request)
}
}