/*
* 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_protocol_client::EmerwenProtocolClient;
use tonic::{metadata::MetadataValue, service::Interceptor, transport::Channel};
use tracing::{debug, info};
use tracing_subscriber::{prelude::*, EnvFilter};
mod monitor;
#[derive(Parser)]
#[command(version)]
struct Args {
/// Enable debug logging
#[arg(long)]
debug: bool,
/// Address of the Master
#[arg(long, default_value = "http://127.0.0.1:8000")]
master_address: String,
/// Auth token
#[arg(long, default_value = "avain_perkele")]
auth_token: String,
}
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
let args = Args::parse();
#[cfg(feature = "trace")]
{
let console_layer = console_subscriber::spawn();
tracing_subscriber::registry()
.with(console_layer)
.with(
tracing_subscriber::fmt::layer()
.with_file(true)
.with_line_number(true)
.with_level(true),
)
.with(EnvFilter::from_default_env().add_directive("trace".parse()?))
.init();
}
#[cfg(not(feature = "trace"))]
{
let mut filter = EnvFilter::from_default_env();
if args.debug {
filter = filter.add_directive("emerwen_worker=debug".parse()?);
} else {
filter = filter.add_directive("emerwen_worker=info".parse()?);
}
tracing_subscriber::registry()
.with(tracing_subscriber::fmt::layer().with_level(true))
.with(filter)
.init();
}
info!("Starting emerwen worker...");
debug!("Hello, debug!");
let channel = Channel::builder(args.master_address.parse()?)
.connect()
.await?;
// Client is cheap to clone.
let mut client = EmerwenProtocolClient::with_interceptor(
channel,
AuthInterceptor {
token: format!("Bearer {}", args.auth_token).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 {
// TODO: listen for SIGINT
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)
}
}