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>>, } 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::() { 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>>, ) -> io::Result<()> { if Path::new(path).exists() { fs::remove_file(path)?; } let socket = LoggingSocketService::new(path, process_info); socket.run(); Ok(()) }