DEVELOPMENT ENVIRONMENT

~liljamo/emerwen

ref: 1225af8e42a83251f51013fddcb2f368c108612c emerwen/emerwen-worker/src/main.rs -rw-r--r-- 6.1 KiB
1225af8eJonni Liljamo feat: more experimentation 13 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
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
use std::time::Duration;

use clap::Parser;
use client::ClientMessage;
use emerwen_protocol::message::payload::MessagePayload;
use emerwen_types::{Target, TargetMethod};
use tokio::sync::mpsc;
use tracing::{debug, info, level_filters::LevelFilter};
use tracing_subscriber::{prelude::*, EnvFilter};

mod client;

#[derive(Parser)]
#[command(version)]
struct Args {
    /// Enable debug logging
    #[arg(long)]
    debug: bool,
}

#[tokio::main]
async fn main() {
    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!");

    // Channel for sending payloads to Master via Client
    let (payload_tx, payload_rx) = mpsc::channel(64);
    // Channel for sending messages to Client via Master
    let (worker_tx, worker_rx) = mpsc::channel(64);

    let targets = vec![
        Target {
            id: 0,
            addr: "127.0.0.1".to_owned(),
            interval: 2000,
            method: TargetMethod::Ping,
        },
        Target {
            id: 1,
            addr: "10.1.2.3".to_owned(),
            interval: 2000,
            method: TargetMethod::Ping,
        },
        Target {
            id: 2,
            addr: "https://liljamo.com/".to_owned(),
            interval: 5000,
            method: TargetMethod::GET {
                ok_codes: vec![200],
            },
        },
    ];

    for target in targets {
        let payload_tx = payload_tx.clone();
        tokio::task::spawn(async move {
            info!("Starting monitoring task for target {}", target.id);

            let sleep_duration = Duration::from_millis(target.interval.into());

            loop {
                let payload;
                match target.check().await {
                    Ok((up, _response)) => {
                        if !up {
                            info!("Target {} down!", target.id);
                            payload = MessagePayload::TargetDown {
                                target_id: target.id,
                            };
                        } else {
                            payload = MessagePayload::TargetUp {
                                target_id: target.id,
                            };
                        }
                    }
                    Err(_) => {
                        // We failed to check the state, status is unknown (grey).
                        payload = MessagePayload::TargetUnknown {
                            target_id: target.id,
                        };
                    }
                }

                let _ = payload_tx.send(payload).await;

                tokio::time::sleep(sleep_duration).await;
            }
        });
    }

    let mut client = client::Client::new("127.0.0.1:8000", worker_tx, payload_rx);
    let _ = client.run().await;

    loop {
        // read worker_rx, i guess
    }

    /*
    //tokio::task::spawn(async move {
    let worker_server = WorkerServer::new("127.0.0.1:8000");
    let _ = worker_server.run().await;
    //});
    */
}

/*
struct WorkerServer {
    addr: String,
}

impl WorkerServer {
    pub fn new(addr: impl Into<String>) -> WorkerServer {
        WorkerServer { addr: addr.into() }
    }

    pub async fn run(&self) -> Result<(), Box<dyn std::error::Error>> {
        let listener = TcpListener::bind(&self.addr).await?;
        info!("Worker Server listening on {}", self.addr);

        loop {
            let (mut socket, addr) = listener.accept().await?;

            info!("Client '{}' connected", addr);

            tokio::task::spawn(async move {
                let (socket_r, mut socket_w) = socket.split();
                let mut reader = BufReader::new(socket_r);

                loop {
                    let mut header_bytes = [0; HEADER_LENGTH];
                    if reader.read_exact(&mut header_bytes).await.is_err() {
                        break;
                    }
                    let header = match MessageHeader::decode(header_bytes) {
                        Ok(header) => header,
                        Err(e) => {
                            error!("Error reading header: {}", e.to_string());
                            continue;
                        }
                    };

                    let mut payload_bytes = vec![0; header.payload_length as usize];
                    if reader.read_exact(&mut payload_bytes).await.is_err() {
                        break;
                    }
                    let mut payload_reader = std::io::Cursor::new(payload_bytes);
                    let payload =
                        match MessagePayload::decode(header.payload_type, &mut payload_reader) {
                            Ok(payload) => payload,
                            Err(e) => {
                                error!("Error reading payload: {}", e.to_string());
                                continue;
                            }
                        };

                    info!("Received message: {:?}", payload);

                    // match payload bla bla
                    // write something back if appliccable
                }

                info!("Client '{}' disconnected", addr);

                /*
                let mut line = String::new();
                loop {
                    let bytes_read = reader.read_line(&mut line).await.unwrap();
                    if bytes_read == 0 {
                        info!("Client '{}' disconnected", addr);
                        break;
                    }

                    socket_w.write_all(&line.as_bytes()).await.unwrap();
                    line.clear();
                }
                */
            });
        }
    }
}
*/