1 use libc::{self, SI_LOAD_SHIFT};
2 use std::{cmp, mem};
3 use std::time::Duration;
4
5 use crate::Result;
6 use crate::errno::Errno;
7
8 /// System info structure returned by `sysinfo`.
9 #[derive(Copy, Clone, Debug, Eq, Hash, PartialEq)]
10 #[repr(transparent)]
11 pub struct SysInfo(libc::sysinfo);
12
13 // The fields are c_ulong on 32-bit linux, u64 on 64-bit linux; x32's ulong is u32
14 #[cfg(all(target_arch = "x86_64", target_pointer_width = "32"))]
15 type mem_blocks_t = u64;
16 #[cfg(not(all(target_arch = "x86_64", target_pointer_width = "32")))]
17 type mem_blocks_t = libc::c_ulong;
18
19 impl SysInfo {
20 /// Returns the load average tuple.
21 ///
22 /// The returned values represent the load average over time intervals of
23 /// 1, 5, and 15 minutes, respectively.
load_average(&self) -> (f64, f64, f64)24 pub fn load_average(&self) -> (f64, f64, f64) {
25 (
26 self.0.loads[0] as f64 / (1 << SI_LOAD_SHIFT) as f64,
27 self.0.loads[1] as f64 / (1 << SI_LOAD_SHIFT) as f64,
28 self.0.loads[2] as f64 / (1 << SI_LOAD_SHIFT) as f64,
29 )
30 }
31
32 /// Returns the time since system boot.
uptime(&self) -> Duration33 pub fn uptime(&self) -> Duration {
34 // Truncate negative values to 0
35 Duration::from_secs(cmp::max(self.0.uptime, 0) as u64)
36 }
37
38 /// Current number of processes.
process_count(&self) -> u1639 pub fn process_count(&self) -> u16 {
40 self.0.procs
41 }
42
43 /// Returns the amount of swap memory in Bytes.
swap_total(&self) -> u6444 pub fn swap_total(&self) -> u64 {
45 self.scale_mem(self.0.totalswap)
46 }
47
48 /// Returns the amount of unused swap memory in Bytes.
swap_free(&self) -> u6449 pub fn swap_free(&self) -> u64 {
50 self.scale_mem(self.0.freeswap)
51 }
52
53 /// Returns the total amount of installed RAM in Bytes.
ram_total(&self) -> u6454 pub fn ram_total(&self) -> u64 {
55 self.scale_mem(self.0.totalram)
56 }
57
58 /// Returns the amount of completely unused RAM in Bytes.
59 ///
60 /// "Unused" in this context means that the RAM in neither actively used by
61 /// programs, nor by the operating system as disk cache or buffer. It is
62 /// "wasted" RAM since it currently serves no purpose.
ram_unused(&self) -> u6463 pub fn ram_unused(&self) -> u64 {
64 self.scale_mem(self.0.freeram)
65 }
66
scale_mem(&self, units: mem_blocks_t) -> u6467 fn scale_mem(&self, units: mem_blocks_t) -> u64 {
68 units as u64 * self.0.mem_unit as u64
69 }
70 }
71
72 /// Returns system information.
73 ///
74 /// [See `sysinfo(2)`](http://man7.org/linux/man-pages/man2/sysinfo.2.html).
sysinfo() -> Result<SysInfo>75 pub fn sysinfo() -> Result<SysInfo> {
76 let mut info = mem::MaybeUninit::uninit();
77 let res = unsafe { libc::sysinfo(info.as_mut_ptr()) };
78 Errno::result(res).map(|_| unsafe{ SysInfo(info.assume_init()) })
79 }
80