1 use sysinfo
::{ ProcessExt
, SystemExt
};
2 use chrono
::{ DateTime
, Datelike
, Timelike
, Utc
};
4 #[cfg(target_os = "unix")]
7 #[derive(Clone, Debug)]
8 pub struct ValheimExe
{
10 load_average_5min
: f64, // [%].
12 world_size
: u64, // [B].
14 last_backup
: DateTime
,
18 pub fn format_memory(&self) -> String
{
19 format_byte_size(self.memory
* 1024, 2)
22 pub fn format_load_average(&self) -> String
{
23 format!("{:.2} %", self.load_average_5min
)
26 pub fn format_uptime(&self) -> String
{
27 let mins
= self.uptime
/ 60;
28 let hours
= mins
/ 60;
29 let days
= hours
/ 24;
30 format!("{}d{}h{}min", days
, hours
- 24 * days
, mins
- 60 * hours
)
33 pub fn format_world_size(&self) -> String
{
34 format_byte_size(self.world_size
, 2)
37 pub fn get_nb_of_player(&self) -> u32 {
41 pub fn format_last_backup(&self) -> String
{
46 const BINARY_PREFIXES
: [&str; 8] = ["B", "KiB", "MiB", "GiB", "TiB", "PiB", "EiB", "ZiB"];
48 fn format_byte_size(bytes
: u64, precision
: usize) -> String
{
50 let mut size
: u64 = 1;
51 size
*= 1024u64.pow(i
as u32);
54 return format!("{} {}", std
::cmp
::max(0u64, bytes
), BINARY_PREFIXES
[i
]);
56 else if bytes
< 1024 * size
{
57 return format!("{:.prec$} {}", bytes
as f64 / size
as f64, BINARY_PREFIXES
[i
], prec
= precision
);
64 const VALHEIM_PROCESS_NAME
: &str = "valheim_server";
66 #[cfg(target_os = "unix")]
67 fn get_number_of_players() -> u32 {
69 journal
::OpenOptions
::default().current_user(true).open().unwrap();
71 journal
.seek_tail().unwrap();
74 match journal
.previous_entry() {
76 if let (Some(unit
), Some(mess
)) = (entry
.get("_SYSTEMD_UNIT"), entry
.get("MESSAGE")) {
77 if unit
== "valheim.service" {
78 if let Some(pos
) = mess
.find("Connections") {
79 let nb_of_connections_str
= mess
.get(pos
+12..).unwrap();
80 if let Some(pos_end
) = nb_of_connections_str
.find(' '
) {
81 if let Ok(n
) = nb_of_connections_str
.get(0..pos_end
).unwrap().parse() {
94 #[cfg(target_os = "windows")]
95 fn get_number_of_players() -> u32 {
99 fn get_last_backup_datetime(backup_path
: &str) -> DateTime
{
103 pub fn get_valheim_executable_information(world_path
: &str, backup_path
: &str) -> Option
<ValheimExe
> {
104 let mut system
= sysinfo
::System
::new_all();
105 system
.refresh_system();
106 let processes
= system
.get_process_by_name(VALHEIM_PROCESS_NAME
);
108 if processes
.len() >= 1 {
109 let process
= processes
.first().unwrap();
111 let world_size
= match std
::fs
::metadata(world_path
) { Ok(f
) => f
.len(), Err(_
) => 0u64 };
115 memory
: process
.memory(),
116 load_average_5min
: system
.get_load_average().five
/ system
.get_processors().len() as f64 * 100.,
117 uptime
: std
::time
::SystemTime
::now().duration_since(std
::time
::UNIX_EPOCH
).unwrap().as_secs() - process
.start_time(),
119 nb_of_players
: get_number_of_players(),
120 last_backup
: get_last_backup_datetime(backup_path
)