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
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
use std::path::Path;
use crate::error::{Error, Result};
use crate::util::Jiffies;
use crate::util::parse;
/// Aggregate CPU time counters for a single logical CPU or the
/// system-wide total.
///
/// All values are in jiffies (clock ticks). On Linux `/proc` the
/// tick rate is `HZ = 100` (1 jiffy = 10 ms).
#[derive(Debug)]
pub struct CpuTime {
/// Time spent in user mode.
pub user: Jiffies,
/// Time spent in user mode with low priority (nice).
pub nice: Jiffies,
/// Time spent in kernel mode.
pub system: Jiffies,
/// Time spent idle (excluding iowait).
pub idle: Jiffies,
/// Time spent waiting for I/O to complete.
pub iowait: Jiffies,
/// Time spent servicing hardware interrupts.
pub irq: Jiffies,
/// Time spent servicing software interrupts.
pub softirq: Jiffies,
/// Time stolen by the hypervisor in a virtualized environment.
pub steal: Jiffies,
/// Time spent running a virtual CPU for a guest OS (counted in
/// user time as well, so usually equal to `user` on the guest).
pub guest: Jiffies,
/// Time spent running a guest with low priority (nice).
pub guest_nice: Jiffies,
}
/// Per-CPU time counters.
#[derive(Debug)]
pub struct PerCpuTime {
/// CPU index (0-based).
pub id: u32,
/// Time counters for this CPU.
pub times: CpuTime,
}
/// System-wide statistics from `/proc/stat`.
///
/// Includes aggregate and per-CPU time counters, context switch
/// count, boot time, and process statistics.
#[derive(Debug)]
pub struct Stat {
/// Aggregate CPU time across all cores.
pub cpu_total: CpuTime,
/// Per-CPU time counters, one entry per logical CPU.
pub per_cpu: Vec<PerCpuTime>,
/// Total number of context switches since boot.
pub ctxt: u64,
/// Boot time as a Unix timestamp (seconds since epoch).
pub btime: u64,
/// Total number of forks since boot.
pub processes: u64,
/// Number of processes currently in the running state.
pub procs_running: u64,
/// Number of processes currently blocked on I/O.
pub procs_blocked: u64,
}
fn parse_cpu_times(fields: &[&[u8]]) -> Result<CpuTime> {
let get = |idx: usize| -> Result<Jiffies> {
if idx < fields.len() {
parse::parse_dec_u64_fast(fields[idx]).map(Jiffies)
} else {
Ok(Jiffies(0))
}
};
Ok(CpuTime {
user: get(0)?,
nice: get(1)?,
system: get(2)?,
idle: get(3)?,
iowait: get(4)?,
irq: get(5)?,
softirq: get(6)?,
steal: get(7)?,
guest: get(8)?,
guest_nice: get(9)?,
})
}
/// Reads `/proc/stat` and returns [`Stat`].
///
/// Parses the `cpu` aggregate line, all `cpuN` per-CPU lines, and
/// the `ctxt`, `btime`, `processes`, `procs_running`, and
/// `procs_blocked` entries. Other `/proc/stat` lines (interrupts,
/// softirqs, etc.) are intentionally ignored — they may be added in
/// future modules.
pub fn stat() -> Result<Stat> {
let path = Path::new("/proc/stat");
let bytes = parse::read_file(path)?;
let mut cpu_total = None;
let mut per_cpu = Vec::new();
let mut ctxt = None;
let mut btime = None;
let mut processes = None;
let mut procs_running = None;
let mut procs_blocked = None;
for (line_num, line) in bytes.split(|&b| b == b'\n').enumerate() {
if line.is_empty() {
continue;
}
let fields = parse::SplitFields::<16>::new(line);
if fields.is_empty() {
continue;
}
let key = fields[0];
if key == b"cpu" {
cpu_total = Some(parse_cpu_times(&fields[1..])?);
} else if key.starts_with(b"cpu") {
let id_str = &key[3..];
let id = parse::parse_dec_u32_fast(id_str).map_err(|_| Error::Parse {
path: path.to_path_buf(),
line: line_num + 1,
msg: "invalid cpu id",
})?;
let times = parse_cpu_times(&fields[1..])?;
per_cpu.push(PerCpuTime { id, times });
} else if key == b"ctxt" {
ctxt = Some(
parse::parse_dec_u64_fast(fields[1]).map_err(|_| Error::Parse {
path: path.to_path_buf(),
line: line_num + 1,
msg: "invalid ctxt",
})?,
);
} else if key == b"btime" {
btime = Some(
parse::parse_dec_u64_fast(fields[1]).map_err(|_| Error::Parse {
path: path.to_path_buf(),
line: line_num + 1,
msg: "invalid btime",
})?,
);
} else if key == b"processes" {
processes = Some(
parse::parse_dec_u64_fast(fields[1]).map_err(|_| Error::Parse {
path: path.to_path_buf(),
line: line_num + 1,
msg: "invalid processes",
})?,
);
} else if key == b"procs_running" {
procs_running =
Some(
parse::parse_dec_u64_fast(fields[1]).map_err(|_| Error::Parse {
path: path.to_path_buf(),
line: line_num + 1,
msg: "invalid procs_running",
})?,
);
} else if key == b"procs_blocked" {
procs_blocked =
Some(
parse::parse_dec_u64_fast(fields[1]).map_err(|_| Error::Parse {
path: path.to_path_buf(),
line: line_num + 1,
msg: "invalid procs_blocked",
})?,
);
}
}
Ok(Stat {
cpu_total: cpu_total.unwrap_or(CpuTime {
user: Jiffies(0),
nice: Jiffies(0),
system: Jiffies(0),
idle: Jiffies(0),
iowait: Jiffies(0),
irq: Jiffies(0),
softirq: Jiffies(0),
steal: Jiffies(0),
guest: Jiffies(0),
guest_nice: Jiffies(0),
}),
per_cpu,
ctxt: ctxt.unwrap_or(0),
btime: btime.unwrap_or(0),
processes: processes.unwrap_or(0),
procs_running: procs_running.unwrap_or(0),
procs_blocked: procs_blocked.unwrap_or(0),
})
}