cf18e08c3afec715b3de660e47959137cd29a860
[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 let days = hours / 24;
23 format!("{}d{}h{}min", days, hours - 24 * days, mins - 60 * hours)
24 }
25 }
26
27 const BINARY_PREFIXES: [&str; 8] = ["B", "KiB", "MiB", "GiB", "TiB", "PiB", "EiB", "ZiB"];
28
29 fn format_byte_size(bytes: u64, precision: usize) -> String {
30 for i in 0 .. 8 {
31 let mut size: u64 = 1;
32 for j in 0 .. i {
33 size *= 1024;
34 }
35
36 if bytes < 1024 {
37 return format!("{} {}", std::cmp::max(0u64, bytes), BINARY_PREFIXES[i]);
38 }
39 else if bytes < 1024 * size {
40 return format!("{:.prec$} {}", bytes as f64 / size as f64, BINARY_PREFIXES[i], prec = precision);
41 }
42 }
43
44 String::from("")
45 }
46
47 const VALHEIM_PROCESS_NAME: &str = "valheim_server";
48
49 pub fn get_valheim_executable_information() -> Option<ValheimExe> {
50 let mut system = sysinfo::System::new_all();
51 system.refresh_all();
52 let processes = system.get_process_by_name(VALHEIM_PROCESS_NAME);
53
54 if processes.len() >= 1 {
55 let process = processes.first().unwrap();
56
57 Some(
58 ValheimExe {
59 memory: process.memory(),
60 cpu_usage: process.cpu_usage(),
61 uptime: std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).unwrap().as_secs() - process.start_time()
62 }
63 )
64 } else {
65 None
66 }
67 }