use std::{ collections::HashMap, fs, io::{self, BufRead, BufReader, Write}, os::unix::net::UnixListener, path::Path, sync::{Arc, RwLock}, thread, }; use crate::{energy::ProcessInfo, Pid}; pub struct LoggingSocketService { path: String, process_info: Arc>>, } impl LoggingSocketService { pub fn new(path: &str, process_info: Arc>>) -> 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::() { socket .write_all(self.handle_request(pid).as_bytes()) .unwrap(); } else { socket .write_all( format!("Failed to get energy for pid: {}\n", line.trim_end()) .as_bytes(), ) .unwrap(); } line.clear(); } } }); } fn handle_request(&self, pid: i32) -> String { let mut output = String::new(); use std::fmt::Write; if pid == -1 { for (pid, info) in self.process_info.read().unwrap().iter() { writeln!(&mut output, "{pid},{},{}", info.energy, info.tree_energy).unwrap(); } writeln!(&mut output, "#",).unwrap(); return output; } if let Some(info) = self.process_info.read().unwrap().get(&pid) { format!( "pid: {pid} process: {}J process tree: {}J\n", info.energy, info.tree_energy ) } else { format!("Unknown pid: {pid}\n") } } } pub fn start_logging_socket_service( path: &str, process_info: Arc>>, ) -> io::Result<()> { if Path::new(path).exists() { fs::remove_file(path)?; } let socket = LoggingSocketService::new(path, process_info); socket.run(); Ok(()) }