3c2bab6e35d6a34a08629e33fa49b067fa5957bb
1 use sysinfo
::{ ProcessExt
, SystemExt
};
3 #[cfg(target_os = "unix")]
6 #[derive(Clone, Debug)]
7 pub struct ValheimExe
{
9 load_average_5min
: f64, // [%].
11 world_size
: u64, // [B].
16 pub fn format_memory(&self) -> String
{
17 format_byte_size(self.memory
* 1024, 2)
20 pub fn format_load_average(&self) -> String
{
21 format!("{:.2} %", self.load_average_5min
)
24 pub fn format_uptime(&self) -> String
{
25 let mins
= self.uptime
/ 60;
26 let hours
= mins
/ 60;
27 let days
= hours
/ 24;
28 format!("{}d{}h{}min", days
, hours
- 24 * days
, mins
- 60 * hours
)
31 pub fn format_world_size(&self) -> String
{
32 format_byte_size(self.world_size
, 2)
35 pub fn get_nb_of_player(&self) -> u32 {
40 const BINARY_PREFIXES
: [&str; 8] = ["B", "KiB", "MiB", "GiB", "TiB", "PiB", "EiB", "ZiB"];
42 fn format_byte_size(bytes
: u64, precision
: usize) -> String
{
44 let mut size
: u64 = 1;
45 size
*= 1024u64.pow(i
as u32);
48 return format!("{} {}", std
::cmp
::max(0u64, bytes
), BINARY_PREFIXES
[i
]);
50 else if bytes
< 1024 * size
{
51 return format!("{:.prec$} {}", bytes
as f64 / size
as f64, BINARY_PREFIXES
[i
], prec
= precision
);
58 const VALHEIM_PROCESS_NAME
: &str = "valheim_server";
60 #[cfg(target_os = "unix")]
61 fn get_number_of_players() -> u32 {
63 journal
::OpenOptions
::default().current_user(true).open().unwrap();
65 journal
.seek_tail().unwrap();
68 match journal
.previous_entry() {
70 if let (Some(unit
), Some(mess
)) = (entry
.get("_SYSTEMD_UNIT"), entry
.get("MESSAGE")) {
71 if unit
== "valheim.service" {
72 if let Some(pos
) = mess
.find("Connections") {
73 let nb_of_connections_str
= mess
.get(pos
+12..).unwrap();
74 if let Some(pos_end
) = nb_of_connections_str
.find(' '
) {
75 if let Ok(n
) = nb_of_connections_str
.get(0..pos_end
).unwrap().parse() {
88 #[cfg(target_os = "windows")]
89 fn get_number_of_players() -> u32 {
93 pub fn get_valheim_executable_information(world_path
: &str) -> Option
<ValheimExe
> {
94 let mut system
= sysinfo
::System
::new_all();
95 system
.refresh_system();
96 let processes
= system
.get_process_by_name(VALHEIM_PROCESS_NAME
);
98 if processes
.len() >= 1 {
99 let process
= processes
.first().unwrap();
101 let world_size
= match std
::fs
::metadata(world_path
) { Ok(f
) => f
.len(), Err(_
) => 0u64 };
105 memory
: process
.memory(),
106 load_average_5min
: system
.get_load_average().five
/ system
.get_processors().len() as f64 * 100.,
107 uptime
: std
::time
::SystemTime
::now().duration_since(std
::time
::UNIX_EPOCH
).unwrap().as_secs() - process
.start_time(),
109 nb_of_players
: get_number_of_players()