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
|
use std::{
collections::HashMap,
fs,
io::{self, Write},
os::unix::net::UnixListener,
path::Path,
sync::{Arc, RwLock},
thread,
time::Duration,
};
use crate::{energy::EnergyLog, Pid};
pub struct LoggingSocketService {
path: String,
logged_energy: Arc<RwLock<HashMap<Pid, EnergyLog>>>,
update_interval: Duration,
}
impl LoggingSocketService {
pub fn new(
path: &str,
logged_energy: Arc<RwLock<HashMap<Pid, EnergyLog>>>,
update_interval: Duration,
) -> Self {
LoggingSocketService {
path: path.to_string(),
logged_energy,
update_interval,
}
}
fn generate_report(&self) -> String {
loop {
if let Ok(logged_energy) = self.logged_energy.try_read() {
let mut result = logged_energy
.iter()
.map(|(key, value)| {
format!(
"{key}: {}J",
value.energy_of_running_tasks + value.energy_of_exited_tasks
)
})
.collect::<Vec<_>>()
.join(", ");
result += "\n";
break result;
}
thread::sleep(Duration::from_millis(10));
}
}
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();
loop {
if socket
.write_all(format!("{}", self.generate_report()).as_bytes())
.is_err()
{
break;
}
thread::sleep(self.update_interval);
}
//TODO: if we ever want to read too
/*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;
}
socket.write_all(format!("got: {line}").as_bytes());
println!("got: {line}");
line.clear();
}*/
}
});
}
}
pub fn start_logging_socket_service(
path: &str,
logged_energy: Arc<RwLock<HashMap<Pid, EnergyLog>>>,
update_interval: Duration,
) -> io::Result<()> {
if Path::new(path).exists() {
fs::remove_file(path)?;
}
let socket = LoggingSocketService::new(path, logged_energy, update_interval);
socket.run();
Ok(())
}
|