monitor_cli 0.1.0

monitor cli | tools to setup monitor system
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
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
use std::{
    env,
    fs::{self, File},
    io::{Read, Write},
    net::IpAddr,
    path::PathBuf,
    str::FromStr,
};

use async_timing_util::Timelength;
use clap::ArgMatches;
use colored::Colorize;
use rand::{distributions::Alphanumeric, Rng};
use run_command::run_command_pipe_to_terminal;
use serde::Serialize;

use crate::types::{CoreConfig, MongoConfig, PeripheryConfig, RestartMode};

const CORE_IMAGE_NAME: &str = "mbecker20/monitor_core";
const PERIPHERY_IMAGE_NAME: &str = "mbecker20/monitor_periphery";
const PERIPHERY_CRATE: &str = "monitor_periphery";

pub fn gen_core_config(sub_matches: &ArgMatches) {
    let host = sub_matches
        .get_one::<String>("host")
        .map(|p| p.as_str())
        .unwrap_or("http://localhost:9000")
        .to_string();

    let path = sub_matches
        .get_one::<String>("path")
        .map(|p| p.as_str())
        .unwrap_or("~/.monitor/core.config.toml")
        .to_string();

    let port = sub_matches
        .get_one::<String>("port")
        .map(|p| p.as_str())
        .unwrap_or("9000")
        .parse::<u16>()
        .expect("invalid port");

    let mongo_uri = sub_matches
        .get_one::<String>("mongo_uri")
        .map(|p| p.as_str())
        .unwrap_or("mongodb://monitor-mongo")
        .to_string();

    let mongo_db_name = sub_matches
        .get_one::<String>("mongo_db_name")
        .map(|p| p.as_str())
        .unwrap_or("monitor")
        .to_string();

    let jwt_valid_for = sub_matches
        .get_one::<String>("jwt_valid_for")
        .map(|p| p.as_str())
        .unwrap_or("1-wk")
        .parse()
        .expect("invalid jwt_valid_for");

    let slack_url = sub_matches
        .get_one::<String>("slack_url")
        .map(|p| p.to_owned());

    let config = CoreConfig {
        host,
        port,
        jwt_valid_for,
        monitoring_interval: Timelength::OneMinute,
        daily_offset_hours: 0,
        keep_stats_for_days: 120,
        slack_url,
        local_auth: true,
        github_oauth: Default::default(),
        google_oauth: Default::default(),
        mongo: MongoConfig {
            uri: mongo_uri,
            db_name: mongo_db_name,
            app_name: "monitor".to_string(),
        },
        jwt_secret: generate_secret(40),
        github_webhook_secret: generate_secret(30),
    };

    write_to_toml(&path, &config);

    println!(
        "\n{} has been generated at {path}\n",
        "core config".bold()
    );
}

pub fn start_mongo(sub_matches: &ArgMatches) {
    let username = sub_matches.get_one::<String>("username");
    let password = sub_matches.get_one::<String>("password");

    if (username.is_some() && password.is_none()) {
        println!(
            "\n❌ must provide {} if username is provided ❌\n",
            "--password".bold()
        );
        return;
    }
    if (username.is_none() && password.is_some()) {
        println!(
            "\n❌ must provide {} if password is provided ❌\n",
            "--username".bold()
        );
        return;
    }

    let name = sub_matches
        .get_one::<String>("name")
        .map(|p| p.as_str())
        .unwrap_or("monitor-mongo");

    let port = sub_matches
        .get_one::<String>("port")
        .map(|p| p.as_str())
        .unwrap_or("27017")
        .parse::<u16>()
        .expect("invalid port");

    let network = sub_matches
        .get_one::<String>("network")
        .map(|p| p.as_str())
        .unwrap_or("bridge");

    let mount = sub_matches
        .get_one::<String>("mount")
        .map(|p| p.as_str())
        .unwrap_or("~/.monitor/db");

    let restart = sub_matches
        .get_one::<String>("restart")
        .map(|p| p.as_str())
        .unwrap_or("unless-stopped")
        .parse::<RestartMode>()
        .expect("invalid restart mode");

    let env = if let (Some(username), Some(password)) = (username, password) {
        format!(" --env MONGO_INITDB_ROOT_USERNAME={username} --env MONGO_INITDB_ROOT_PASSWORD={password}")
    } else {
        String::new()
    };

    println!(
        "\n====================\n    {}    \n====================\n",
        "mongo config".bold()
    );
    if let Some(username) = username {
        println!("{}: {username}", "mongo username".dimmed());
    }
    println!("{}: {name}", "container name".dimmed());
    println!("{}: {port}", "port".dimmed());
    println!("{}: {mount}", "mount".dimmed());
    println!("{}: {network}", "network".dimmed());

    println!(
        "\npress {} to start {}. {}",
        "ENTER".green().bold(),
        "MongoDB".bold(),
        "(ctrl-c to cancel)".dimmed()
    );

    let buffer = &mut [0u8];
    let res = std::io::stdin().read_exact(buffer);

    if res.is_err() {
        println!("pressed another button, exiting");
    }

    let command = format!("docker run -d --name {name} -p {port}:27017 --network {network} -v {mount}:/data/db{env} --restart {restart} mongo --quiet");

    let output = run_command_pipe_to_terminal(&command);

    if output.success() {
        println!("\n{} has been started up ✅\n", "monitor mongo".bold())
    } else {
        eprintln!("\n❌ there was some {} on startup ❌\n", "error".red())
    }
}

pub fn start_core(sub_matches: &ArgMatches) {
    let config_path = sub_matches
        .get_one::<String>("config_path")
        .map(|p| p.as_str())
        .unwrap_or("~/.monitor/core.config.toml")
        .to_string();

    let name = sub_matches
        .get_one::<String>("name")
        .map(|p| p.as_str())
        .unwrap_or("monitor-core");

    let port = sub_matches
        .get_one::<String>("port")
        .map(|p| p.as_str())
        .unwrap_or("9000")
        .parse::<u16>()
        .expect("invalid port");

    let network = sub_matches
        .get_one::<String>("network")
        .map(|p| p.as_str())
        .unwrap_or("bridge");

    let restart = sub_matches
        .get_one::<String>("restart")
        .map(|p| p.as_str())
        .unwrap_or("unless-stopped")
        .parse::<RestartMode>()
        .expect("invalid restart mode");

    println!(
        "\n===================\n    {}    \n===================\n",
        "core config".bold()
    );
    println!("{}: {name}", "container name".dimmed());
    println!("{}: {config_path}", "config path".dimmed());
    println!("{}: {port}", "port".dimmed());
    println!("{}: {network}", "network".dimmed());

    println!(
        "\npress {} to start {}. {}",
        "ENTER".green().bold(),
        "monitor core".bold(),
        "(ctrl-c to cancel)".dimmed()
    );

    let buffer = &mut [0u8];
    let res = std::io::stdin().read_exact(buffer);

    if res.is_err() {
        println!("pressed another button, exiting");
    }

    let command = format!("docker run -d --name {name} -p {port}:9000 --network {network} -v {config_path}:/config/config.toml --restart {restart} {CORE_IMAGE_NAME}");

    let output = run_command_pipe_to_terminal(&command);

    if output.success() {
        println!("\n{} has been started up ✅\n", "monitor core".bold())
    } else {
        eprintln!("\n❌ there was some {} on startup ❌\n", "error".red())
    }
}

pub fn gen_periphery_config(sub_matches: &ArgMatches) {
    let path = sub_matches
        .get_one::<String>("path")
        .map(|p| p.as_str())
        .unwrap_or("~/.monitor/periphery.config.toml")
        .to_string();

    let port = sub_matches
        .get_one::<String>("port")
        .map(|p| p.as_str())
        .unwrap_or("8000")
        .parse::<u16>()
        .expect("invalid port");

    let stats_polling_rate = sub_matches
        .get_one::<String>("stats_polling_rate")
        .map(|p| p.as_str())
        .unwrap_or("5-sec")
        .parse::<Timelength>()
        .expect("invalid timelength");

    let allowed_ips = sub_matches
        .get_one::<String>("allowed_ips")
        .map(|p| p.as_str())
        .unwrap_or("")
        .split(",")
        .filter(|ip| ip.len() > 0)
        .map(|ip| {
            ip.parse()
                .expect("given allowed ip address is not valid ip")
        })
        .collect::<Vec<IpAddr>>();

    let repo_dir = sub_matches
        .get_one::<String>("repo_dir")
        .map(|p| p.as_str())
        .unwrap_or("~/.monitor/repos")
        .to_string()
        .replace("~", env::var("HOME").unwrap().as_str());

    let config = PeripheryConfig {
        port,
        stats_polling_rate,
        allowed_ips,
        repo_dir: "/repos".to_string(),
        secrets: Default::default(),
        github_accounts: Default::default(),
        docker_accounts: Default::default(),
    };

    write_to_toml(&path, &config);

    println!(
        "\n{} generated at {path}\n",
        "periphery config".bold()
    );
}

pub fn start_periphery_daemon(sub_matches: &ArgMatches) {
    let config_path = sub_matches
        .get_one::<String>("config_path")
        .map(|p| p.as_str())
        .unwrap_or("~/.monitor/periphery.config.toml")
        .to_string();

    let stdout = sub_matches
        .get_one::<String>("stdout")
        .map(|p| p.as_str())
        .unwrap_or("~/.monitor/periphery.log.out")
        .to_string();

    let stderr = sub_matches
        .get_one::<String>("stderr")
        .map(|p| p.as_str())
        .unwrap_or("~/.monitor/periphery.log.err")
        .to_string();

    println!(
        "\n========================\n    {}    \n========================\n",
        "periphery config".bold()
    );
    println!("{}: {config_path}", "config path".dimmed());
    println!("{}: {stdout}", "stdout".dimmed());
    println!("{}: {stderr}", "stderr".dimmed());

    println!(
        "\npress {} to start {}. {}",
        "ENTER".green().bold(),
        "monitor periphery".bold(),
        "(ctrl-c to cancel)".dimmed()
    );

    let buffer = &mut [0u8];
    let res = std::io::stdin().read_exact(buffer);

    if res.is_err() {
        println!("pressed another button, exiting");
    }

    println!("\ninstalling periphery binary...\n");

    let install_output = run_command_pipe_to_terminal(&format!("cargo install {PERIPHERY_CRATE}"));

    if install_output.success() {
        println!("\ninstallation finished, starting monitor periphery daemon\n")
    } else {
        eprintln!(
            "\n❌ there was some {} during periphery installation ❌\n",
            "error".red()
        );
        return;
    }

    let command = format!("if pgrep periphery; then pkill periphery; fi && periphery --daemon --config-path {config_path} --stdout {stdout} --stderr {stderr}");

    let output = run_command_pipe_to_terminal(&command);

    if output.success() {
        println!(
            "\n{} has been started up ✅\n",
            "monitor periphery".bold()
        )
    } else {
        eprintln!("\n❌ there was some {} on startup ❌\n", "error".red())
    }
}

pub fn start_periphery_container(sub_matches: &ArgMatches) {
    let config_path = sub_matches
        .get_one::<String>("config_path")
        .map(|p| p.as_str())
        .unwrap_or("~/.monitor/periphery.config.toml")
        .to_string();

    let repo_dir = sub_matches
        .get_one::<String>("repo_dir")
        .map(|p| p.as_str())
        .unwrap_or("~/.monitor/repos")
        .to_string();

    let name = sub_matches
        .get_one::<String>("name")
        .map(|p| p.as_str())
        .unwrap_or("monitor-periphery");

    let port = sub_matches
        .get_one::<String>("port")
        .map(|p| p.as_str())
        .unwrap_or("8000")
        .parse::<u16>()
        .expect("invalid port");

    let network = sub_matches
        .get_one::<String>("network")
        .map(|p| p.as_str())
        .unwrap_or("bridge");

    let restart = sub_matches
        .get_one::<String>("restart")
        .map(|p| p.as_str())
        .unwrap_or("unless-stopped")
        .parse::<RestartMode>()
        .expect("invalid restart mode");

    println!(
        "\n========================\n    {}    \n========================\n",
        "periphery config".bold()
    );
    println!("{}: {name}", "container name".dimmed());
    println!("{}: {config_path}", "config path".dimmed());
    println!("{}: {repo_dir}", "repo folder".dimmed());
    println!("{}: {port}", "port".dimmed());
    println!("{}: {network}", "network".dimmed());

    println!(
        "\npress {} to start {}. {}",
        "ENTER".green().bold(),
        "monitor periphery".bold(),
        "(ctrl-c to cancel)".dimmed()
    );

    let buffer = &mut [0u8];
    let res = std::io::stdin().read_exact(buffer);

    if res.is_err() {
        println!("pressed another button, exiting");
    }

    let command = format!("docker run -d --name {name} -p {port}:8000 --network {network} -v {config_path}:/config/config.toml -v {repo_dir}:/repos -v /var/run/docker.sock:/var/run/docker.sock --restart {restart} {PERIPHERY_IMAGE_NAME}");

    let output = run_command_pipe_to_terminal(&command);

    if output.success() {
        println!(
            "\n{} has been started up ✅\n",
            "monitor periphery".bold()
        )
    } else {
        eprintln!("\n❌ there was some {} on startup ❌\n", "error".red())
    }
}

fn write_to_toml(path: &str, toml: impl Serialize) {
    let path = PathBuf::from_str(&path.replace("~", &std::env::var("HOME").unwrap()))
        .expect("not a valid path");
    let _ = fs::create_dir_all(pop_path(&path));
    fs::write(
        path,
        toml::to_string(&toml).expect("failed to parse config into toml"),
    )
    .expect("❌ failed to write toml to file ❌");
}

fn pop_path(path: &PathBuf) -> PathBuf {
    let mut clone = path.clone();
    clone.pop();
    clone
}

fn generate_secret(length: usize) -> String {
    rand::thread_rng()
        .sample_iter(&Alphanumeric)
        .take(length)
        .map(char::from)
        .collect()
}