8c04e238f21e022a84810ee11640013ca724907c
[valheim_web.git] / backend / src / valheim_controller.rs
1 use sysinfo::{ ProcessExt, SystemExt };
2
3 use std::{ fs, time::SystemTime };
4
5 use chrono::{ DateTime, offset::Local };
6
7 #[cfg(target_os = "linux")]
8 use systemd::journal;
9
10 #[derive(Clone, Debug)]
11 pub struct ValheimExe {
12 memory: u64, // [kB].
13 load_average_5min: f64, // [%].
14 uptime: u64, // [s].
15 world_size: u64, // [B].
16 active_players: Vec<String>,
17 last_backup: Option<SystemTime>,
18 }
19
20 impl ValheimExe {
21 pub fn format_memory(&self) -> String {
22 format_byte_size(self.memory * 1024, 2)
23 }
24
25 pub fn format_load_average(&self) -> String {
26 format!("{:.2} %", self.load_average_5min)
27 }
28
29 pub fn format_uptime(&self) -> String {
30 let mins = self.uptime / 60;
31 let hours = mins / 60;
32 let days = hours / 24;
33 format!("{}d {}h {}min", days, hours - 24 * days, mins - 60 * hours)
34 }
35
36 pub fn format_world_size(&self) -> String {
37 format_byte_size(self.world_size, 2)
38 }
39
40 pub fn format_active_players(&self) -> String {
41 if self.active_players.len() == 0 {
42 String::from("<none>")
43 } else {
44 self.active_players.join(", ")
45 }
46 }
47
48 pub fn format_last_backup(&self) -> String {
49 match self.last_backup {
50 Some(t) => {
51 let datetime: DateTime<Local> = t.into();
52 datetime.format("%d/%m/%Y %T").to_string()
53 },
54 None => String::from("?")
55 }
56 }
57 }
58
59 const BINARY_PREFIXES: [&str; 8] = ["B", "KiB", "MiB", "GiB", "TiB", "PiB", "EiB", "ZiB"];
60
61 fn format_byte_size(bytes: u64, precision: usize) -> String {
62 for i in 0 .. 8 {
63 let mut size: u64 = 1;
64 size *= 1024u64.pow(i as u32);
65
66 if bytes < 1024 {
67 return format!("{} {}", std::cmp::max(0u64, bytes), BINARY_PREFIXES[i]);
68 }
69 else if bytes < 1024 * size {
70 return format!("{:.prec$} {}", bytes as f64 / size as f64, BINARY_PREFIXES[i], prec = precision);
71 }
72 }
73
74 String::from("")
75 }
76
77 const VALHEIM_PROCESS_NAME: &str = "valheim_server";
78 const STRING_BEFORE_CHARACTER_NAME: &str = "Got character ZDOID from";
79 const STRING_BEFORE_NB_OF_CONNECTIONS: &str = "Connections";
80
81 #[cfg(target_os = "linux")]
82 fn get_active_players() -> Vec<String> {
83 let mut journal =
84 journal::OpenOptions::default().current_user(true).open().unwrap();
85
86 journal.seek_tail().unwrap();
87
88 let mut number_of_connections = -1i32;
89 let mut players : Vec<String> = Vec::new();
90
91 loop {
92 match journal.previous_entry() {
93 Ok(Some(entry)) => {
94 if let (Some(unit), Some(mess)) = (entry.get("_SYSTEMD_UNIT"), entry.get("MESSAGE")) {
95 if unit == "valheim.service" {
96 if let Some(pos) = mess.find(STRING_BEFORE_CHARACTER_NAME) {
97 let character_str = mess.get(pos+STRING_BEFORE_CHARACTER_NAME.len()+1..).unwrap();
98 if let Some(pos_end) = character_str.find(" : ") {
99 let player_name = String::from(character_str.get(0..pos_end).unwrap());
100 if !players.contains(&player_name) {
101 players.push(player_name);
102 if players.len() as i32 == number_of_connections {
103 return players;
104 }
105 }
106 }
107 }
108 else if let Some(pos) = mess.find(STRING_BEFORE_NB_OF_CONNECTIONS) {
109 let nb_of_connections_str = mess.get(pos+STRING_BEFORE_NB_OF_CONNECTIONS.len()+1..).unwrap();
110 if let Some(pos_end) = nb_of_connections_str.find(' ') {
111 if let Ok(n) = nb_of_connections_str.get(0..pos_end).unwrap().parse() {
112 if number_of_connections == -1 {
113 number_of_connections = n as i32
114
115 if players.len() as i32 >= number_of_connections {
116 return players;
117 }
118 }
119 }
120 }
121 }
122 }
123 }
124 },
125 _ => return players
126 }
127 }
128 }
129
130 #[cfg(target_os = "windows")]
131 fn get_active_players() -> Vec<String> {
132 Vec::new()
133 }
134
135 fn get_last_backup_datetime(backup_path: &str) -> Option<SystemTime> {
136 let mut times =
137 fs::read_dir(backup_path).ok()?.filter_map(
138 |e| {
139 let dir = e.ok()?;
140 if dir.path().is_file() { Some(dir.metadata().ok()?.modified().ok()?) } else { None }
141 }
142 )
143 .collect::<Vec<SystemTime>>();
144
145 times.sort();
146
147 Some(times.last()?.clone())
148 }
149
150 pub fn get_valheim_executable_information(world_path: &str, backup_path: &str) -> Option<ValheimExe> {
151 let mut system = sysinfo::System::new_all();
152 system.refresh_system();
153 let processes = system.get_process_by_name(VALHEIM_PROCESS_NAME);
154
155 if processes.len() >= 1 {
156 let process = processes.first().unwrap();
157
158 let world_size = match std::fs::metadata(world_path) { Ok(f) => f.len(), Err(_) => 0u64 };
159
160 Some(
161 ValheimExe {
162 memory: process.memory(),
163 load_average_5min: system.get_load_average().five / system.get_processors().len() as f64 * 100.,
164 uptime: std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).unwrap().as_secs() - process.start_time(),
165 world_size,
166 active_players: get_active_players(),
167 last_backup: get_last_backup_datetime(backup_path)
168 }
169 )
170 } else {
171 None
172 }
173 }