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
|
use std::{
collections::HashMap,
fs,
io::{self, BufRead, BufReader, Write},
os::unix::net::UnixListener,
path::Path,
sync::{Arc, RwLock},
thread,
time::Duration,
};
use dashmap::DashMap;
use crate::{energy::ProcessInfo, Pid};
pub struct LoggingSocketService {
path: String,
process_info: Arc<RwLock<HashMap<Pid, ProcessInfo>>>,
}
impl LoggingSocketService {
pub fn new(path: &str, process_info: Arc<RwLock<HashMap<Pid, ProcessInfo>>>) -> Self {
LoggingSocketService {
path: path.to_string(),
process_info,
}
}
pub fn run(self) {
thread::spawn(move || {
let listener = UnixListener::bind(self.path.clone()).unwrap();
for stream in listener.incoming() {
let mut socket = stream.unwrap();
let mut reader = BufReader::new(socket.try_clone().unwrap());
let mut line = String::new();
while let Ok(bytes_read) = reader.read_line(&mut line) {
if bytes_read == 0 {
break;
}
if let Ok(pid) = line.trim().parse::<Pid>() {
if let Some(info) = self.process_info.read().unwrap().get(&pid).clone() {
socket
.write_all(
format!(
"pid: {pid} process: {}J process tree: {}J\n",
info.energy, info.tree_energy
)
.as_bytes(),
)
.unwrap();
} else {
socket
.write_all(format!("Unknown pid: {pid}\n").as_bytes())
.unwrap();
}
} else {
socket
.write_all(
format!("Failed to get energy for pid: {}\n", line.trim_end())
.as_bytes(),
)
.unwrap();
}
line.clear();
}
}
});
}
}
pub fn start_logging_socket_service(
path: &str,
process_info: Arc<RwLock<HashMap<Pid, ProcessInfo>>>,
) -> io::Result<()> {
if Path::new(path).exists() {
fs::remove_file(path)?;
}
let socket = LoggingSocketService::new(path, process_info);
socket.run();
Ok(())
}
|