summaryrefslogtreecommitdiffstats
path: root/src/app/data_harvester/processes/freebsd.rs
blob: 4c5a9e45c53b9e6f6f0be689d44fa5c1d1c1dea3 (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
60
61
62
63
64
65
66
67
68
69
70
71
72
73
//! Process data collection for FreeBSD.  Uses sysinfo.

use std::io;

use serde::{Deserialize, Deserializer};
use sysinfo::System;

use super::ProcessHarvest;
use crate::data_harvester::deserialize_xo;
use crate::data_harvester::processes::UserTable;

#[derive(Deserialize, Debug, Default)]
#[serde(rename_all = "kebab-case")]
struct ProcessInformation {
    process: Vec<ProcessRow>,
}

#[derive(Deserialize, Debug)]
#[serde(rename_all = "kebab-case")]
struct ProcessRow {
    #[serde(deserialize_with = "pid")]
    pid: i32,
    #[serde(deserialize_with = "percent_cpu")]
    percent_cpu: f64,
}

pub fn get_process_data(
    sys: &System, use_current_cpu_total: bool, unnormalized_cpu: bool, mem_total_kb: u64,
    user_table: &mut UserTable,
) -> crate::utils::error::Result<Vec<ProcessHarvest>> {
    super::macos_freebsd::get_process_data(
        sys,
        use_current_cpu_total,
        unnormalized_cpu,
        mem_total_kb,
        user_table,
        get_freebsd_process_cpu_usage,
    )
}

fn get_freebsd_process_cpu_usage(pids: &[i32]) -> io::Result<std::collections::HashMap<i32, f64>> {
    if pids.is_empty() {
        return Ok(std::collections::HashMap::new());
    }

    let output = std::process::Command::new("ps")
        .args(["--libxo", "json", "-o", "pid,pcpu", "-p"])
        .args(pids.iter().map(i32::to_string))
        .output()?;
    deserialize_xo("process-information", &output.stdout).map(|process_info: ProcessInformation| {
        process_info
            .process
            .into_iter()
            .map(|row| (row.pid, row.percent_cpu))
            .collect()
    })
}

fn pid<'de, D>(deserializer: D) -> Result<i32, D::Error>
where
    D: Deserializer<'de>,
{
    let s = String::deserialize(deserializer)?;
    s.parse().map_err(serde::de::Error::custom)
}

fn percent_cpu<'de, D>(deserializer: D) -> Result<f64, D::Error>
where
    D: Deserializer<'de>,
{
    let s = String::deserialize(deserializer)?;
    s.parse().map_err(serde::de::Error::custom)
}