Display some server process information (memory, cpu usage, uptime)
[valheim_web.git] / backend / src / valheim_controller.rs
1 use std::cmp::min;
2
3 use sysinfo::{ ProcessExt, SystemExt };
4
5 #[derive(Debug)]
6 pub struct ValheimExe {
7 memory: u64, // [kB].
8 cpu_usage: f32, // [%].
9 uptime: u64, // [s].
10 }
11
12 impl ValheimExe {
13 pub fn format_memory(&self) -> String {
14 format_byte_size(self.memory * 1024, 2)
15 }
16 pub fn format_cpu_usage(&self) -> String {
17 format!("{:.2} %", self.cpu_usage)
18 }
19 pub fn format_uptime(&self) -> String {
20 let mins = self.uptime / 60;
21 let hours = mins / 60;
22 format!("{}h{}min", hours, mins - 60 * hours)
23 }
24 }
25
26 const BINARY_PREFIXES: [&str; 8] = ["B", "KiB", "MiB", "GiB", "TiB", "PiB", "EiB", "ZiB"];
27
28 fn format_byte_size(bytes: u64, precision: usize) -> String {
29 for i in 0 .. 8 {
30 let mut size: u64 = 1;
31 for j in 0 .. i {
32 size *= 1024;
33 }
34
35 if bytes < 1024 {
36 return format!("{} {}", std::cmp::max(0u64, bytes), BINARY_PREFIXES[i]);
37 }
38 else if bytes < 1024 * size {
39 return format!("{:.prec$} {}", bytes as f64 / size as f64, BINARY_PREFIXES[i], prec = precision);
40 }
41 }
42
43 String::from("")
44 }
45
46 const VALHEIM_PROCESS_NAME: &str = "valheim_server";
47
48 pub fn get_valheim_executable_information() -> Option<ValheimExe> {
49 let mut system = sysinfo::System::new_all();
50 system.refresh_all();
51 let processes = system.get_process_by_name(VALHEIM_PROCESS_NAME);
52
53 if processes.len() >= 1 {
54 let process = processes.first().unwrap();
55
56 Some(
57 ValheimExe {
58 memory: process.memory(),
59 cpu_usage: process.cpu_usage(),
60 uptime: std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).unwrap().as_secs() - process.start_time()
61 }
62 )
63 } else {
64 None
65 }
66 }