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