DEVELOPMENT ENVIRONMENT

~liljamo/emerwen

ref: 5d06034fa4cfa5f508c43edfa532d1ddcb54beec emerwen/emerwen-master/src/main.rs -rw-r--r-- 3.8 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
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
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
use clap::Parser;
use emerwen_protocol::{
    emerwen_protocol_server::{EmerwenProtocol, EmerwenProtocolServer},
    target::{MethodGet, MethodPing},
    SetTargetStateRequest, Target, TargetsResponse,
};
use tonic::{transport::Server, Request, Response, Status};
use tracing::{debug, info, level_filters::LevelFilter};
use tracing_subscriber::{prelude::*, EnvFilter};

#[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();

    let addr = "127.0.0.1:8000";

    info!(message = "Starting emerwen master...", %addr);
    debug!("Hello, debug!");

    let workers = vec![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()),
            },
        ],
    }];

    let server = MasterServer::new(workers);

    Server::builder()
        .add_service(EmerwenProtocolServer::with_interceptor(
            server,
            move |req: Request<()>| {
                match req.metadata().get("authorization") {
                    Some(_token) => {
                        // TODO: check
                        Ok(req)
                    }
                    None => Err(Status::unauthenticated("invalid auth")),
                }
            },
        ))
        .serve(addr.parse()?)
        .await?;

    Ok(())
}

struct MasterServer {
    workers: Vec<Worker>,
}

impl MasterServer {
    fn new(workers: Vec<Worker>) -> MasterServer {
        MasterServer { workers }
    }
}

#[tonic::async_trait]
impl EmerwenProtocol for MasterServer {
    async fn get_targets(&self, request: Request<()>) -> Result<Response<TargetsResponse>, Status> {
        // We should not get here without valid authorization.
        let token = request
            .metadata()
            .get("authorization")
            .expect("request had no authorization, when it should")
            .to_str()
            .unwrap()
            .trim_start_matches("Bearer ");

        // Like we really really shouldn't get here if the target doesn't exist.
        let targets = self
            .workers
            .iter()
            .find(|worker| *worker.auth_token == *token)
            .expect("dafuq")
            .targets
            .clone();

        Ok(Response::new(TargetsResponse { targets }))
    }

    async fn set_target_state(
        &self,
        request: Request<SetTargetStateRequest>,
    ) -> Result<Response<()>, Status> {
        info!("{:?}", request.into_inner());

        Ok(Response::new(()))
    }
}

struct Worker {
    pub id: u32,
    pub auth_token: String,
    pub targets: Vec<Target>,
}