summaryrefslogtreecommitdiffstats
path: root/src/data_collection/memory/sysinfo.rs
blob: 330bb9b005ef2fa8d0bb498c201c42f4ce71cf2f (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
//! Collecting memory data using sysinfo.

use sysinfo::System;

use crate::data_collection::memory::MemHarvest;

/// Returns RAM usage.
pub(crate) fn get_ram_usage(sys: &System) -> Option<MemHarvest> {
    let mem_used = sys.used_memory();
    let mem_total = sys.total_memory();

    Some(MemHarvest {
        used_bytes: mem_used,
        total_bytes: mem_total,
        use_percent: if mem_total == 0 {
            None
        } else {
            Some(mem_used as f64 / mem_total as f64 * 100.0)
        },
    })
}

/// Returns SWAP usage.
pub(crate) fn get_swap_usage(sys: &System) -> Option<MemHarvest> {
    let mem_used = sys.used_swap();
    let mem_total = sys.total_swap();

    Some(MemHarvest {
        used_bytes: mem_used,
        total_bytes: mem_total,
        use_percent: if mem_total == 0 {
            None
        } else {
            Some(mem_used as f64 / mem_total as f64 * 100.0)
        },
    })
}

/// Returns cache usage. sysinfo has no way to do this directly but it should equal the difference
/// between the available and free memory. Free memory is defined as memory not containing any data,
/// which means cache and buffer memory are not "free". Available memory is defined as memory able
/// to be allocated by processes, which includes cache and buffer memory. On Windows, this will
/// always be 0. For more information, see [docs](https://docs.rs/sysinfo/latest/sysinfo/struct.System.html#method.available_memory)
/// and [memory explanation](https://askubuntu.com/questions/867068/what-is-available-memory-while-using-free-command)
#[cfg(not(target_os = "windows"))]
pub(crate) fn get_cache_usage(sys: &System) -> Option<MemHarvest> {
    let mem_used = sys.available_memory().saturating_sub(sys.free_memory());
    let mem_total = sys.total_memory();

    Some(MemHarvest {
        total_bytes: mem_total,
        used_bytes: mem_used,
        use_percent: if mem_total == 0 {
            None
        } else {
            Some(mem_used as f64 / mem_total as f64 * 100.0)
        },
    })
}