-
Notifications
You must be signed in to change notification settings - Fork 0
/
socket.rs
60 lines (57 loc) · 1.81 KB
/
socket.rs
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
use crate::subprocesses::Processes;
use regex::Regex;
use std::fs;
use std::io::Read;
use std::os::unix::net::UnixListener;
struct Msg<'a> {
command: &'a str,
sub: &'a str,
}
fn parse_msg(msg: &str) -> Option<Msg> {
let msg_regex = Regex::new(r"(\S+) (\S+)").unwrap();
msg_regex.captures(msg).map(|capture| {
let groups = (capture.get(1), capture.get(2));
match groups {
(Some(command), Some(name)) => Some(Msg {
command: command.as_str(),
sub: name.as_str(),
}),
_ => None,
}
})?
}
pub fn manage(
mut processes: Processes,
options: crate::options::Options,
) -> Result<(), std::io::Error> {
let sock_path = options.sock_path.clone();
fs::remove_file(&sock_path).unwrap_or_default();
let sock = UnixListener::bind(&sock_path)?;
for stream in sock.incoming() {
let mut buf = vec![];
stream?.read_to_end(&mut buf)?;
let string = String::from_utf8(buf).unwrap();
let msg = parse_msg(string.as_str());
match msg {
Some(msg) => {
let sub = processes.get_mut(msg.sub);
match sub {
Some(sub) => {
if msg.command == "restart" {
sub.start(&options.program)?;
} else {
println!("recieved unusual command: {}", msg.command)
}
}
None => println!("recieved unusual person: {}", msg.sub),
}
}
None => println!(
"recieved unusual message. message should be <command> <sub>. got: {}",
string
),
}
}
fs::remove_file(&sock_path).unwrap_or_default();
Ok(())
}