DEVELOPMENT ENVIRONMENT

~liljamo/emerwen

ref: 91b99511153d9e5adb1ffba835cb0706a54676f0 emerwen/emerwen-worker/src/main.rs -rw-r--r-- 3.0 KiB
91b99511Jonni Liljamo feat(master): change to protocol Worker type 9 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
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
/*
 * 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::workertomaster::worker_to_master_client::WorkerToMasterClient;
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 = WorkerToMasterClient::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)
    }
}