|
| 1 | +// This file is part of the uutils procps package. |
| 2 | +// |
| 3 | +// For the full copyright and license information, please view the LICENSE |
| 4 | +// file that was distributed with this source code. |
| 5 | + |
| 6 | +use clap::{arg, crate_version, ArgAction, Command}; |
| 7 | +use std::env; |
| 8 | +use std::fs; |
| 9 | +use std::io::Error; |
| 10 | +use std::path::Path; |
| 11 | +use std::process; |
| 12 | +use uu_pmap::smaps_format_parser::parse_smap_entries; |
| 13 | +use uu_pmap::smaps_format_parser::SmapEntry; |
| 14 | +use uu_top::header; |
| 15 | +use uucore::uptime::get_formatted_time; |
| 16 | +use uucore::{error::UResult, format_usage, help_about, help_usage}; |
| 17 | + |
| 18 | +const ABOUT: &str = help_about!("hugetop.md"); |
| 19 | +const USAGE: &str = help_usage!("hugetop.md"); |
| 20 | + |
| 21 | +#[derive(Debug)] |
| 22 | +struct ProcessHugepageInfo { |
| 23 | + pid: u32, |
| 24 | + name: String, |
| 25 | + entries: Vec<SmapEntry>, |
| 26 | +} |
| 27 | + |
| 28 | +#[derive(Default, Debug)] |
| 29 | +struct HugePageSizeInfo { |
| 30 | + size_kb: u64, |
| 31 | + free: u64, |
| 32 | + total: u64, |
| 33 | +} |
| 34 | + |
| 35 | +impl std::fmt::Display for HugePageSizeInfo { |
| 36 | + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { |
| 37 | + let size_str = match self.size_kb { |
| 38 | + 2048 => "2Mi", |
| 39 | + 1048576 => "1Gi", |
| 40 | + _ => panic!("{}", self.size_kb), |
| 41 | + }; |
| 42 | + |
| 43 | + write!(f, "{} - {}/{}", size_str, self.free, self.total) |
| 44 | + } |
| 45 | +} |
| 46 | + |
| 47 | +fn parse_hugepage() -> Result<Vec<HugePageSizeInfo>, Error> { |
| 48 | + let parse_hugepage_value = |p: &Path| -> Result<u64, Error> { |
| 49 | + fs::read_to_string(p)?.trim().parse().map_err(|_| { |
| 50 | + std::io::Error::new( |
| 51 | + std::io::ErrorKind::InvalidData, |
| 52 | + "Invalid memory info format", |
| 53 | + ) |
| 54 | + }) |
| 55 | + }; |
| 56 | + |
| 57 | + let info_dir = fs::read_dir("/sys/kernel/mm/hugepages")?; |
| 58 | + |
| 59 | + let mut sizes = Vec::new(); |
| 60 | + |
| 61 | + for entry in info_dir { |
| 62 | + let entry = entry?; |
| 63 | + |
| 64 | + let mut info = HugePageSizeInfo::default(); |
| 65 | + |
| 66 | + info.total = parse_hugepage_value(&entry.path().join("nr_hugepages"))?; |
| 67 | + info.free = parse_hugepage_value(&entry.path().join("free_hugepages"))?; |
| 68 | + info.size_kb = entry |
| 69 | + .file_name() |
| 70 | + .into_string() |
| 71 | + .unwrap() |
| 72 | + .split("-") |
| 73 | + .nth(1) |
| 74 | + .unwrap() |
| 75 | + .replace("kB", "") |
| 76 | + .parse() |
| 77 | + .map_err(|_| { |
| 78 | + std::io::Error::new( |
| 79 | + std::io::ErrorKind::InvalidData, |
| 80 | + "Invalid memory info format", |
| 81 | + ) |
| 82 | + })?; |
| 83 | + |
| 84 | + sizes.push(info); |
| 85 | + } |
| 86 | + |
| 87 | + Ok(sizes) |
| 88 | +} |
| 89 | + |
| 90 | +fn parse_process_info(p: &fs::DirEntry) -> Option<ProcessHugepageInfo> { |
| 91 | + let pid_str = p.file_name().into_string().unwrap_or_default(); |
| 92 | + |
| 93 | + // Skip non-PID directories |
| 94 | + let pid = pid_str.parse::<u32>().ok()?; |
| 95 | + |
| 96 | + // Parse name |
| 97 | + let name = fs::read_to_string(p.path().join("status")) |
| 98 | + .ok()? |
| 99 | + .lines() |
| 100 | + .nth(0) |
| 101 | + .unwrap_or_default() |
| 102 | + .split(":") |
| 103 | + .nth(1) |
| 104 | + .unwrap_or_default() |
| 105 | + .trim() |
| 106 | + .to_string(); |
| 107 | + |
| 108 | + let contents = fs::read_to_string(p.path().join("smaps")).ok()?; |
| 109 | + let smap_entries = parse_smap_entries(&contents).ok()?; |
| 110 | + let smap_entries: Vec<_> = smap_entries |
| 111 | + .into_iter() |
| 112 | + .filter(|entry| entry.kernel_page_size_in_kb >= 2024) |
| 113 | + .collect(); |
| 114 | + |
| 115 | + if smap_entries.is_empty() { |
| 116 | + return None; |
| 117 | + } |
| 118 | + |
| 119 | + Some(ProcessHugepageInfo { |
| 120 | + name, |
| 121 | + pid, |
| 122 | + entries: smap_entries, |
| 123 | + }) |
| 124 | +} |
| 125 | + |
| 126 | +#[cfg(target_os = "linux")] |
| 127 | +fn parse_process_hugepages() -> Result<Vec<ProcessHugepageInfo>, Error> { |
| 128 | + let mut processes = Vec::new(); |
| 129 | + let proc_dir = fs::read_dir("/proc")?; |
| 130 | + |
| 131 | + for entry in proc_dir { |
| 132 | + let entry = entry?; |
| 133 | + if let Some(info) = parse_process_info(&entry) { |
| 134 | + processes.push(info); |
| 135 | + } |
| 136 | + } |
| 137 | + |
| 138 | + Ok(processes) |
| 139 | +} |
| 140 | + |
| 141 | +#[uucore::main] |
| 142 | +pub fn uumain(args: impl uucore::Args) -> UResult<()> { |
| 143 | + match parse_hugepage() { |
| 144 | + Ok(sys_info) => match parse_process_hugepages() { |
| 145 | + Ok(p_info) => { |
| 146 | + print!("{}", construct_str(sys_info, &p_info,)); |
| 147 | + } |
| 148 | + Err(e) => { |
| 149 | + eprintln!("hugetop: failed to read process hugepage info: {}", e); |
| 150 | + process::exit(1); |
| 151 | + } |
| 152 | + }, |
| 153 | + Err(e) => { |
| 154 | + eprintln!("hugetop: failed to read hugepage info: {}", e); |
| 155 | + process::exit(1); |
| 156 | + } |
| 157 | + } |
| 158 | + |
| 159 | + Ok(()) |
| 160 | +} |
| 161 | + |
| 162 | +pub fn uu_app() -> Command { |
| 163 | + Command::new(uucore::util_name()) |
| 164 | + .version(crate_version!()) |
| 165 | + .about(ABOUT) |
| 166 | + .override_usage(format_usage(USAGE)) |
| 167 | + .args_override_self(true) |
| 168 | + .infer_long_args(true) |
| 169 | + .disable_help_flag(true) |
| 170 | + .arg(arg!(--help "display this help and exit").action(ArgAction::SetTrue)) |
| 171 | +} |
| 172 | + |
| 173 | +fn construct_str(sys: Vec<HugePageSizeInfo>, processes: &[ProcessHugepageInfo]) -> String { |
| 174 | + let mut output = String::new(); |
| 175 | + |
| 176 | + output.push_str(&construct_system_str(sys)); |
| 177 | + output.push_str(&format_process_str(processes)); |
| 178 | + |
| 179 | + output |
| 180 | +} |
| 181 | + |
| 182 | +fn format_process_str(processes: &[ProcessHugepageInfo]) -> String { |
| 183 | + let mut output = String::new(); |
| 184 | + let header = format!( |
| 185 | + "{:<8} {:<12} {:<12} {:<12}\n", |
| 186 | + "PID", "Private", "Shared", "Process" |
| 187 | + ); |
| 188 | + |
| 189 | + output.push_str(&header); |
| 190 | + |
| 191 | + for process in processes { |
| 192 | + for smap_entry in &process.entries { |
| 193 | + output.push_str(&format!( |
| 194 | + "{:<8} {:<12} {:<12} {:<12}\n", |
| 195 | + process.pid, |
| 196 | + smap_entry.private_hugetlb_in_kb, |
| 197 | + smap_entry.shared_hugetlb_in_kb, |
| 198 | + process.name |
| 199 | + )); |
| 200 | + } |
| 201 | + } |
| 202 | + |
| 203 | + output |
| 204 | +} |
| 205 | + |
| 206 | +fn construct_system_str(sys: Vec<HugePageSizeInfo>) -> String { |
| 207 | + let mut output = String::new(); |
| 208 | + output.push_str(&format!( |
| 209 | + "top - {time} {uptime}, {user}\n", |
| 210 | + time = get_formatted_time(), |
| 211 | + uptime = header::uptime(), |
| 212 | + user = header::user(), |
| 213 | + )); |
| 214 | + |
| 215 | + for (i, info) in sys.iter().enumerate() { |
| 216 | + if i < sys.len() - 1 { |
| 217 | + output.push_str(&format!("{}, ", info.to_string())); |
| 218 | + } else { |
| 219 | + output.push_str(&info.to_string()); |
| 220 | + output.push('\n'); |
| 221 | + } |
| 222 | + } |
| 223 | + |
| 224 | + output |
| 225 | +} |
0 commit comments