DEVELOPMENT ENVIRONMENT

~liljamo/emerwen

ref: 5d06034fa4cfa5f508c43edfa532d1ddcb54beec emerwen/emerwen-worker/src/main.rs -rw-r--r-- 2.2 KiB
5d06034fJonni Liljamo feat: kinda MVP 12 days ago
                                                                                
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
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)
    }
}