commit 2855bbad646bb5fb1792d01f0fbe55454dc0c38e Author: Xory Date: Sat Sep 14 00:23:46 2024 +0300 init: add code diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..4fffb2f --- /dev/null +++ b/.gitignore @@ -0,0 +1,2 @@ +/target +/Cargo.lock diff --git a/Cargo.toml b/Cargo.toml new file mode 100644 index 0000000..3d5fce8 --- /dev/null +++ b/Cargo.toml @@ -0,0 +1,6 @@ +[package] +name = "servercam" +version = "0.1.0" +edition = "2021" + +[dependencies] diff --git a/src/hardwaremon.rs b/src/hardwaremon.rs new file mode 100644 index 0000000..8db818c --- /dev/null +++ b/src/hardwaremon.rs @@ -0,0 +1,50 @@ +use std::fs::File; +use std::io::{self, BufRead, BufReader, Read}; + +pub fn get_memory_usage() -> io::Result<(u64, u64)> { + let file = File::open("/proc/meminfo")?; + let reader = BufReader::new(file); + let mut total_memory = 0; + let mut free_memory = 0; + + for line in reader.lines() { + let line = line?; + if line.starts_with("MemTotal:") { + total_memory = line.split_whitespace().nth(1).unwrap().parse().unwrap(); + } else if line.starts_with("MemFree:") { + free_memory = line.split_whitespace().nth(1).unwrap().parse().unwrap(); + } + if total_memory != 0 && free_memory != 0 { + break; + } + } + + Ok((total_memory, free_memory)) +} + +pub fn get_cpu_usage() -> io::Result { + let file = File::open("/proc/stat")?; + let mut reader = BufReader::new(file); + let mut line = String::new(); + reader.read_line(&mut line)?; + + let values: Vec = line.split_whitespace() + .skip(1) // Skip "cpu" prefix + .take(7) // We need the first 7 values + .map(|val| val.parse().unwrap()) + .collect(); + + let total = values.iter().sum::(); + let idle = values[3]; + let usage = 100.0 * (1.0 - (idle as f64 / total as f64)); + + Ok(usage) +} + + +pub fn get_hostname() -> io::Result { + let mut hostname = String::new(); + File::open("/etc/hostname")?.read_to_string(&mut hostname)?; + hostname = hostname.trim().to_string(); + Ok(hostname) +} diff --git a/src/main.rs b/src/main.rs new file mode 100644 index 0000000..3bcc153 --- /dev/null +++ b/src/main.rs @@ -0,0 +1,30 @@ +use std::io::Write; +use std::net; +use std::error::Error; +use std::thread::sleep; +use std::time::Duration; +mod hardwaremon; +use hardwaremon::get_cpu_usage; +use hardwaremon::get_hostname; +use hardwaremon::get_memory_usage; + +pub fn handle_connection(mut connection: net::TcpStream) -> Result<(), Box> { + loop { + let cpu_usage = get_cpu_usage()?; + let ram_usage = get_memory_usage()?; + let hostname = get_hostname()?; + + let response = format!("{}:{}:T{},F{}\n", hostname, cpu_usage.to_string(), ram_usage.0.to_string(), ram_usage.1.to_string()); + connection.write_all(response.as_bytes())?; + sleep(Duration::from_secs(5)); + } + Ok(()) +} + +fn main() -> Result<(), Box> { + let stream = net::TcpListener::bind("0.0.0.0:2048")?; + for connection in stream.incoming() { + handle_connection(connection?)?; + } + Ok(()) +}