forked from uutils/procps
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathvmstat.rs
More file actions
178 lines (155 loc) · 5.7 KB
/
vmstat.rs
File metadata and controls
178 lines (155 loc) · 5.7 KB
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
// This file is part of the uutils procps package.
//
// For the full copyright and license information, please view the LICENSE
// file that was distributed with this source code.
mod parser;
mod picker;
#[cfg(target_os = "linux")]
use crate::picker::{get_pickers, Picker};
use clap::value_parser;
#[allow(unused_imports)]
use clap::{arg, crate_version, ArgMatches, Command};
#[allow(unused_imports)]
pub use parser::*;
#[allow(unused_imports)]
use uucore::error::{UResult, USimpleError};
use uucore::{format_usage, help_about, help_usage};
const ABOUT: &str = help_about!("vmstat.md");
const USAGE: &str = help_usage!("vmstat.md");
#[uucore::main]
pub fn uumain(args: impl uucore::Args) -> UResult<()> {
#[allow(unused)]
let matches = uu_app().try_get_matches_from(args)?;
#[cfg(target_os = "linux")]
{
// validate unit
if let Some(unit) = matches.get_one::<String>("unit") {
if !["k", "K", "m", "M"].contains(&unit.as_str()) {
Err(USimpleError::new(
1,
"-S requires k, K, m or M (default is KiB)",
))?;
}
}
let one_header = matches.get_flag("one-header");
let no_first = matches.get_flag("no-first");
let term_height = terminal_size::terminal_size()
.map(|size| size.1 .0)
.unwrap_or(0);
if matches.get_flag("slabs") {
return print_slabs(one_header, term_height);
}
let delay = matches.get_one::<u64>("delay");
let count = matches.get_one::<u64>("count");
let mut count = count.copied().map(|c| if c == 0 { 1 } else { c });
let delay = delay.copied().unwrap_or_else(|| {
count.get_or_insert(1);
1
});
let pickers = get_pickers(&matches);
let mut proc_data = ProcData::new();
let mut line_count = 0;
print_header(&pickers);
if !no_first {
print_data(&pickers, &proc_data, None, &matches);
line_count += 1;
}
while count.is_none() || line_count < count.unwrap() {
std::thread::sleep(std::time::Duration::from_secs(delay));
let proc_data_now = ProcData::new();
if needs_header(one_header, term_height, line_count) {
print_header(&pickers);
}
print_data(&pickers, &proc_data_now, Some(&proc_data), &matches);
line_count += 1;
proc_data = proc_data_now;
}
}
Ok(())
}
#[cfg(target_os = "linux")]
fn print_slabs(one_header: bool, term_height: u16) -> UResult<()> {
let mut slab_data = uu_slabtop::SlabInfo::new()?.data;
slab_data.sort_by_key(|k| k.0.to_lowercase());
print_slab_header();
for (line_count, slab_item) in slab_data.into_iter().enumerate() {
if needs_header(one_header, term_height, line_count as u64) {
print_slab_header();
}
println!(
"{:<24} {:>6} {:>6} {:>6} {:>6}",
slab_item.0, slab_item.1[0], slab_item.1[1], slab_item.1[2], slab_item.1[3]
);
}
Ok(())
}
#[cfg(target_os = "linux")]
fn needs_header(one_header: bool, term_height: u16, line_count: u64) -> bool {
!one_header && term_height > 0 && ((line_count + 3) % term_height as u64 == 0)
}
#[cfg(target_os = "linux")]
fn print_slab_header() {
println!(
"{:<24} {:>6} {:>6} {:>6} {:>6}",
"Cache", "Num", "Total", "Size", "Pages"
);
}
#[cfg(target_os = "linux")]
fn print_header(pickers: &[Picker]) {
let mut section: Vec<&str> = vec![];
let mut title: Vec<&str> = vec![];
pickers.iter().for_each(|p| {
section.push(p.0 .0.as_str());
title.push(p.0 .1.as_str());
});
println!("{}", section.join(" "));
println!("{}", title.join(" "));
}
#[cfg(target_os = "linux")]
fn print_data(
pickers: &[Picker],
proc_data: &ProcData,
proc_data_before: Option<&ProcData>,
matches: &ArgMatches,
) {
let mut data: Vec<String> = vec![];
let mut data_len_excess = 0;
pickers.iter().for_each(|f| {
f.1(
proc_data,
proc_data_before,
matches,
&mut data,
&mut data_len_excess,
);
});
println!("{}", data.join(" "));
}
#[allow(clippy::cognitive_complexity)]
pub fn uu_app() -> Command {
Command::new(uucore::util_name())
.version(crate_version!())
.about(ABOUT)
.override_usage(format_usage(USAGE))
.infer_long_args(true)
.args([
arg!(<delay> "The delay between updates in seconds")
.required(false)
.value_parser(value_parser!(u64).range(1..)),
arg!(<count> "Number of updates")
.required(false)
.value_parser(value_parser!(u64)),
arg!(-a --active "Display active and inactive memory"),
// arg!(-f --forks "switch displays the number of forks since boot"),
arg!(-m --slabs "Display slabinfo"),
arg!(-n --"one-header" "Display the header only once rather than periodically"),
// arg!(-s --stats "Displays a table of various event counters and memory statistics"),
// arg!(-d --disk "Report disk statistics"),
// arg!(-D --"disk-sum" "Report some summary statistics about disk activity"),
// arg!(-p --partition <device> "Detailed statistics about partition"),
arg!(-S --unit <character> "Switches outputs between 1000 (k), 1024 (K), 1000000 (m), or 1048576 (M) bytes"),
arg!(-t --timestamp "Append timestamp to each line"),
arg!(-w --wide "Wide output mode"),
arg!(-y --"no-first" "Omits first report with statistics since system boot"),
])
}