| 1 |
#![allow(unknown_lints)] |
| 2 |
#![deny(rustdoc::broken_intra_doc_links, rustdoc::invalid_html_tags)] |
| 3 |
//! This crate provides to an interface into the linux `procfs` filesystem, usually mounted at |
| 4 |
//! `/proc`. |
| 5 |
//! |
| 6 |
//! This is a pseudo-filesystem which is available on most every linux system and provides an |
| 7 |
//! interface to kernel data structures. |
| 8 |
//! |
| 9 |
//! |
| 10 |
//! # Kernel support |
| 11 |
//! |
| 12 |
//! Not all fields/data are available in each kernel. Some fields were added in specific kernel |
| 13 |
//! releases, and other fields are only present in certain kernel configuration options are |
| 14 |
//! enabled. These are represented as `Option` fields in this crate. |
| 15 |
//! |
| 16 |
//! This crate aims to support all 2.6 kernels (and newer). WSL2 is also supported. |
| 17 |
//! |
| 18 |
//! # Documentation |
| 19 |
//! |
| 20 |
//! In almost all cases, the documentation is taken from the |
| 21 |
//! [`proc.5`](http://man7.org/linux/man-pages/man5/proc.5.html) manual page. This means that |
| 22 |
//! sometimes the style of writing is not very "rusty", or may do things like reference related files |
| 23 |
//! (instead of referencing related structs). Contributions to improve this are welcome. |
| 24 |
//! |
| 25 |
//! # Panicing |
| 26 |
//! |
| 27 |
//! While previous versions of the library could panic, this current version aims to be panic-free |
| 28 |
//! in a many situations as possible. Whenever the procfs crate encounters a bug in its own |
| 29 |
//! parsing code, it will return an [`InternalError`](enum.ProcError.html#variant.InternalError) error. This should be considered a |
| 30 |
//! bug and should be [reported](https://github.com/eminence/procfs). If you encounter a panic, |
| 31 |
//! please report that as well. |
| 32 |
//! |
| 33 |
//! # Cargo features |
| 34 |
//! |
| 35 |
//! The following cargo features are available: |
| 36 |
//! |
| 37 |
//! * `chrono` -- Default. Optional. This feature enables a few methods that return values as `DateTime` objects. |
| 38 |
//! * `flate2` -- Default. Optional. This feature enables parsing gzip compressed `/proc/config.gz` file via the `procfs::kernel_config` method. |
| 39 |
//! * `backtrace` -- Optional. This feature lets you get a stack trace whenever an `InternalError` is raised. |
| 40 |
//! |
| 41 |
//! # Examples |
| 42 |
//! |
| 43 |
//! Examples can be found in the various modules shown below, or in the |
| 44 |
//! [examples](https://github.com/eminence/procfs/tree/master/procfs/examples) folder of the code repository. |
| 45 |
//! |
| 46 |
|
| 47 |
pub use procfs_core::*; |
| 48 |
|
| 49 |
use bitflags::bitflags; |
| 50 |
|
| 51 |
use rustix::fd::AsFd; |
| 52 |
use rustix::fs::{Mode, OFlags}; |
| 53 |
use std::collections::HashMap; |
| 54 |
use std::fmt; |
| 55 |
use std::fs::File; |
| 56 |
use std::io::{self, BufReader, Read, Seek}; |
| 57 |
use std::path::{Path, PathBuf}; |
| 58 |
use std::str::FromStr; |
| 59 |
|
| 60 |
#[cfg(feature = "chrono")] |
| 61 |
use chrono::DateTime; |
| 62 |
|
| 63 |
const PROC_CONFIG_GZ: &str = "/proc/config.gz"; |
| 64 |
const BOOT_CONFIG: &str = "/boot/config"; |
| 65 |
|
| 66 |
/// Allows associating a specific file to parse. |
| 67 |
pub trait Current: FromRead { |
| 68 |
const PATH: &'static str; |
| 69 |
|
| 70 |
/// Parse the current value using the system file. |
| 71 |
fn current() -> ProcResult<Self> { |
| 72 |
Self::from_file(Self::PATH) |
| 73 |
} |
| 74 |
} |
| 75 |
|
| 76 |
/// A type for accessing data about the currently running machine |
| 77 |
/// |
| 78 |
/// For more details, see the [SystemInfoInterface] trait. |
| 79 |
pub struct LocalSystemInfo; |
| 80 |
|
| 81 |
impl SystemInfoInterface for LocalSystemInfo { |
| 82 |
fn boot_time_secs(&self) -> ProcResult<u64> { |
| 83 |
crate::boot_time_secs() |
| 84 |
} |
| 85 |
|
| 86 |
fn ticks_per_second(&self) -> u64 { |
| 87 |
crate::ticks_per_second() |
| 88 |
} |
| 89 |
|
| 90 |
fn page_size(&self) -> u64 { |
| 91 |
crate::page_size() |
| 92 |
} |
| 93 |
|
| 94 |
fn is_little_endian(&self) -> bool { |
| 95 |
u16::from_ne_bytes([0, 1]).to_le_bytes() == [0, 1] |
| 96 |
} |
| 97 |
} |
| 98 |
|
| 99 |
const LOCAL_SYSTEM_INFO: LocalSystemInfo = LocalSystemInfo; |
| 100 |
|
| 101 |
/// The current [SystemInfo]. |
| 102 |
pub fn current_system_info() -> &'static SystemInfo { |
| 103 |
&LOCAL_SYSTEM_INFO |
| 104 |
} |
| 105 |
|
| 106 |
/// Allows associating a specific file to parse with system information. |
| 107 |
pub trait CurrentSI: FromReadSI { |
| 108 |
const PATH: &'static str; |
| 109 |
|
| 110 |
/// Parse the current value using the system file and the current system info. |
| 111 |
fn current() -> ProcResult<Self> { |
| 112 |
Self::current_with_system_info(current_system_info()) |
| 113 |
} |
| 114 |
|
| 115 |
/// Parse the current value using the system file and the provided system info. |
| 116 |
fn current_with_system_info(si: &SystemInfo) -> ProcResult<Self> { |
| 117 |
Self::from_file(Self::PATH, si) |
| 118 |
} |
| 119 |
} |
| 120 |
|
| 121 |
/// Allows `impl WithSystemInfo` to use the current system info. |
| 122 |
pub trait WithCurrentSystemInfo<'a>: WithSystemInfo<'a> + Sized { |
| 123 |
/// Get the value using the current system info. |
| 124 |
fn get(self) -> Self::Output { |
| 125 |
self.with_system_info(current_system_info()) |
| 126 |
} |
| 127 |
} |
| 128 |
|
| 129 |
impl<'a, T: WithSystemInfo<'a>> WithCurrentSystemInfo<'a> for T {} |
| 130 |
|
| 131 |
/// Extension traits useful for importing wholesale. |
| 132 |
pub mod prelude { |
| 133 |
pub use super::{Current, CurrentSI, WithCurrentSystemInfo}; |
| 134 |
pub use procfs_core::prelude::*; |
| 135 |
} |
| 136 |
|
| 137 |
macro_rules! wrap_io_error { |
| 138 |
($path:expr, $expr:expr) => { |
| 139 |
match $expr { |
| 140 |
Ok(v) => Ok(v), |
| 141 |
Err(e) => { |
| 142 |
let kind = e.kind(); |
| 143 |
Err(::std::io::Error::new( |
| 144 |
kind, |
| 145 |
crate::IoErrorWrapper { |
| 146 |
path: $path.to_owned(), |
| 147 |
inner: e.into(), |
| 148 |
}, |
| 149 |
)) |
| 150 |
} |
| 151 |
} |
| 152 |
}; |
| 153 |
} |
| 154 |
|
| 155 |
pub(crate) fn read_file<P: AsRef<Path>>(path: P) -> ProcResult<String> { |
| 156 |
std::fs::read_to_string(path.as_ref()) |
| 157 |
.map_err(|e| e.into()) |
| 158 |
.error_path(path.as_ref()) |
| 159 |
} |
| 160 |
|
| 161 |
pub(crate) fn write_file<P: AsRef<Path>, T: AsRef<[u8]>>(path: P, buf: T) -> ProcResult<()> { |
| 162 |
std::fs::write(path.as_ref(), buf) |
| 163 |
.map_err(|e| e.into()) |
| 164 |
.error_path(path.as_ref()) |
| 165 |
} |
| 166 |
|
| 167 |
pub(crate) fn read_value<P, T, E>(path: P) -> ProcResult<T> |
| 168 |
where |
| 169 |
P: AsRef<Path>, |
| 170 |
T: FromStr<Err = E>, |
| 171 |
ProcError: From<E>, |
| 172 |
{ |
| 173 |
read_file(path).and_then(|s| s.trim().parse().map_err(ProcError::from)) |
| 174 |
} |
| 175 |
|
| 176 |
pub(crate) fn write_value<P: AsRef<Path>, T: fmt::Display>(path: P, value: T) -> ProcResult<()> { |
| 177 |
write_file(path, value.to_string().as_bytes()) |
| 178 |
} |
| 179 |
|
| 180 |
mod cgroups; |
| 181 |
pub use crate::cgroups::*; |
| 182 |
|
| 183 |
mod crypto; |
| 184 |
pub use crate::crypto::*; |
| 185 |
|
| 186 |
pub mod keyring; |
| 187 |
|
| 188 |
mod iomem; |
| 189 |
pub use iomem::*; |
| 190 |
|
| 191 |
mod kpageflags; |
| 192 |
pub use kpageflags::*; |
| 193 |
|
| 194 |
mod kpagecount; |
| 195 |
pub use kpagecount::*; |
| 196 |
|
| 197 |
pub mod net; |
| 198 |
|
| 199 |
pub mod process; |
| 200 |
|
| 201 |
pub mod sys; |
| 202 |
pub use crate::sys::kernel::BuildInfo as KernelBuildInfo; |
| 203 |
pub use crate::sys::kernel::Type as KernelType; |
| 204 |
pub use crate::sys::kernel::Version as KernelVersion; |
| 205 |
|
| 206 |
/// A wrapper around a `File` that remembers the name of the path |
| 207 |
struct FileWrapper { |
| 208 |
inner: File, |
| 209 |
path: PathBuf, |
| 210 |
} |
| 211 |
|
| 212 |
impl FileWrapper { |
| 213 |
fn open<P: AsRef<Path>>(path: P) -> Result<FileWrapper, io::Error> { |
| 214 |
let p = path.as_ref(); |
| 215 |
let f = wrap_io_error!(p, File::open(p))?; |
| 216 |
Ok(FileWrapper { |
| 217 |
inner: f, |
| 218 |
path: p.to_owned(), |
| 219 |
}) |
| 220 |
} |
| 221 |
fn open_at_flags<P, Q, Fd: AsFd>(root: P, dirfd: Fd, path: Q, flags: OFlags) -> Result<FileWrapper, io::Error> |
| 222 |
where |
| 223 |
P: AsRef<Path>, |
| 224 |
Q: AsRef<Path>, |
| 225 |
{ |
| 226 |
let p = root.as_ref().join(path.as_ref()); |
| 227 |
let fd = wrap_io_error!(p, rustix::fs::openat(dirfd, path.as_ref(), flags, Mode::empty()))?; |
| 228 |
Ok(FileWrapper { |
| 229 |
inner: File::from(fd), |
| 230 |
path: p, |
| 231 |
}) |
| 232 |
} |
| 233 |
|
| 234 |
fn open_at<P, Q, Fd: AsFd>(root: P, dirfd: Fd, path: Q) -> Result<FileWrapper, io::Error> |
| 235 |
where |
| 236 |
P: AsRef<Path>, |
| 237 |
Q: AsRef<Path>, |
| 238 |
{ |
| 239 |
Self::open_at_flags(root, dirfd, path, OFlags::RDONLY | OFlags::CLOEXEC) |
| 240 |
} |
| 241 |
|
| 242 |
/// Returns the inner file |
| 243 |
fn inner(self) -> File { |
| 244 |
self.inner |
| 245 |
} |
| 246 |
} |
| 247 |
|
| 248 |
impl Read for FileWrapper { |
| 249 |
fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> { |
| 250 |
wrap_io_error!(self.path, self.inner.read(buf)) |
| 251 |
} |
| 252 |
fn read_to_end(&mut self, buf: &mut Vec<u8>) -> io::Result<usize> { |
| 253 |
wrap_io_error!(self.path, self.inner.read_to_end(buf)) |
| 254 |
} |
| 255 |
fn read_to_string(&mut self, buf: &mut String) -> io::Result<usize> { |
| 256 |
wrap_io_error!(self.path, self.inner.read_to_string(buf)) |
| 257 |
} |
| 258 |
fn read_exact(&mut self, buf: &mut [u8]) -> io::Result<()> { |
| 259 |
wrap_io_error!(self.path, self.inner.read_exact(buf)) |
| 260 |
} |
| 261 |
} |
| 262 |
|
| 263 |
impl Seek for FileWrapper { |
| 264 |
fn seek(&mut self, pos: io::SeekFrom) -> io::Result<u64> { |
| 265 |
wrap_io_error!(self.path, self.inner.seek(pos)) |
| 266 |
} |
| 267 |
} |
| 268 |
|
| 269 |
/// Return the number of ticks per second. |
| 270 |
/// |
| 271 |
/// This isn't part of the proc file system, but it's a useful thing to have, since several fields |
| 272 |
/// count in ticks. This is calculated from `sysconf(_SC_CLK_TCK)`. |
| 273 |
pub fn ticks_per_second() -> u64 { |
| 274 |
rustix::param::clock_ticks_per_second() |
| 275 |
} |
| 276 |
|
| 277 |
/// The boot time of the system, as a `DateTime` object. |
| 278 |
/// |
| 279 |
/// This is calculated from `/proc/stat`. |
| 280 |
/// |
| 281 |
/// This function requires the "chrono" features to be enabled (which it is by default). |
| 282 |
#[cfg(feature = "chrono")] |
| 283 |
pub fn boot_time() -> ProcResult<DateTime<chrono::Local>> { |
| 284 |
use chrono::TimeZone; |
| 285 |
let secs = boot_time_secs()?; |
| 286 |
|
| 287 |
let date_time = expect!(chrono::Local.timestamp_opt(secs as i64, 0).single()); |
| 288 |
|
| 289 |
Ok(date_time) |
| 290 |
} |
| 291 |
|
| 292 |
/// The boottime of the system, in seconds since the epoch |
| 293 |
/// |
| 294 |
/// This is calculated from `/proc/stat`. |
| 295 |
/// |
| 296 |
#[cfg_attr( |
| 297 |
not(feature = "chrono"), |
| 298 |
doc = "If you compile with the optional `chrono` feature, you can use the `boot_time()` method to get the boot time as a `DateTime` object." |
| 299 |
)] |
| 300 |
#[cfg_attr( |
| 301 |
feature = "chrono", |
| 302 |
doc = "See also [boot_time()] to get the boot time as a `DateTime`" |
| 303 |
)] |
| 304 |
pub fn boot_time_secs() -> ProcResult<u64> { |
| 305 |
BOOT_TIME.with(|x| { |
| 306 |
let mut btime = x.borrow_mut(); |
| 307 |
if let Some(btime) = *btime { |
| 308 |
Ok(btime) |
| 309 |
} else { |
| 310 |
// KernelStats doesn't call `boot_time_secs()`, so it's safe to call |
| 311 |
// KernelStats::current() (which uses the local system info). |
| 312 |
let stat = KernelStats::current()?; |
| 313 |
*btime = Some(stat.btime); |
| 314 |
Ok(stat.btime) |
| 315 |
} |
| 316 |
}) |
| 317 |
} |
| 318 |
|
| 319 |
thread_local! { |
| 320 |
static BOOT_TIME : std::cell::RefCell<Option<u64>> = std::cell::RefCell::new(None); |
| 321 |
} |
| 322 |
|
| 323 |
/// Memory page size, in bytes. |
| 324 |
/// |
| 325 |
/// This is calculated from `sysconf(_SC_PAGESIZE)`. |
| 326 |
pub fn page_size() -> u64 { |
| 327 |
rustix::param::page_size() as u64 |
| 328 |
} |
| 329 |
|
| 330 |
impl Current for LoadAverage { |
| 331 |
const PATH: &'static str = "/proc/loadavg"; |
| 332 |
} |
| 333 |
|
| 334 |
impl Current for KernelConfig { |
| 335 |
const PATH: &'static str = PROC_CONFIG_GZ; |
| 336 |
|
| 337 |
/// Returns a configuration options used to build the currently running kernel |
| 338 |
/// |
| 339 |
/// If CONFIG_KCONFIG_PROC is available, the config is read from `/proc/config.gz`. |
| 340 |
/// Else look in `/boot/config-$(uname -r)` or `/boot/config` (in that order). |
| 341 |
/// |
| 342 |
/// # Notes |
| 343 |
/// Reading the compress `/proc/config.gz` is only supported if the `flate2` feature is enabled |
| 344 |
/// (which it is by default). |
| 345 |
#[cfg_attr(feature = "flate2", doc = "The flate2 feature is currently enabled")] |
| 346 |
#[cfg_attr(not(feature = "flate2"), doc = "The flate2 feature is NOT currently enabled")] |
| 347 |
fn current() -> ProcResult<Self> { |
| 348 |
let reader: Box<dyn Read> = if Path::new(PROC_CONFIG_GZ).exists() && cfg!(feature = "flate2") { |
| 349 |
#[cfg(feature = "flate2")] |
| 350 |
{ |
| 351 |
let file = FileWrapper::open(PROC_CONFIG_GZ)?; |
| 352 |
let decoder = flate2::read::GzDecoder::new(file); |
| 353 |
Box::new(decoder) |
| 354 |
} |
| 355 |
#[cfg(not(feature = "flate2"))] |
| 356 |
{ |
| 357 |
unreachable!("flate2 feature not enabled") |
| 358 |
} |
| 359 |
} else { |
| 360 |
let kernel = rustix::system::uname(); |
| 361 |
|
| 362 |
let filename = format!("{}-{}", BOOT_CONFIG, kernel.release().to_string_lossy()); |
| 363 |
|
| 364 |
match FileWrapper::open(filename) { |
| 365 |
Ok(file) => Box::new(BufReader::new(file)), |
| 366 |
Err(e) => match e.kind() { |
| 367 |
io::ErrorKind::NotFound => { |
| 368 |
let file = FileWrapper::open(BOOT_CONFIG)?; |
| 369 |
Box::new(file) |
| 370 |
} |
| 371 |
_ => return Err(e.into()), |
| 372 |
}, |
| 373 |
} |
| 374 |
}; |
| 375 |
|
| 376 |
Self::from_read(reader) |
| 377 |
} |
| 378 |
} |
| 379 |
|
| 380 |
/// Returns a configuration options used to build the currently running kernel |
| 381 |
/// |
| 382 |
/// If CONFIG_KCONFIG_PROC is available, the config is read from `/proc/config.gz`. |
| 383 |
/// Else look in `/boot/config-$(uname -r)` or `/boot/config` (in that order). |
| 384 |
/// |
| 385 |
/// # Notes |
| 386 |
/// Reading the compress `/proc/config.gz` is only supported if the `flate2` feature is enabled |
| 387 |
/// (which it is by default). |
| 388 |
pub fn kernel_config() -> ProcResult<HashMap<String, ConfigSetting>> { |
| 389 |
KernelConfig::current().map(|c| c.0) |
| 390 |
} |
| 391 |
|
| 392 |
impl CurrentSI for KernelStats { |
| 393 |
const PATH: &'static str = "/proc/stat"; |
| 394 |
} |
| 395 |
|
| 396 |
impl Current for VmStat { |
| 397 |
const PATH: &'static str = "/proc/vmstat"; |
| 398 |
} |
| 399 |
|
| 400 |
/// Get various virtual memory statistics |
| 401 |
/// |
| 402 |
/// Since the exact set of statistics will vary from kernel to kernel, and because most of them are |
| 403 |
/// not well documented, this function returns a HashMap instead of a struct. Consult the kernel |
| 404 |
/// source code for more details of this data. |
| 405 |
/// |
| 406 |
/// This data is taken from the /proc/vmstat file. |
| 407 |
/// |
| 408 |
/// (since Linux 2.6.0) |
| 409 |
pub fn vmstat() -> ProcResult<HashMap<String, i64>> { |
| 410 |
VmStat::current().map(|s| s.0) |
| 411 |
} |
| 412 |
|
| 413 |
impl Current for KernelModules { |
| 414 |
const PATH: &'static str = "/proc/modules"; |
| 415 |
} |
| 416 |
|
| 417 |
/// Get a list of loaded kernel modules |
| 418 |
/// |
| 419 |
/// This corresponds to the data in `/proc/modules`. |
| 420 |
pub fn modules() -> ProcResult<HashMap<String, KernelModule>> { |
| 421 |
KernelModules::current().map(|m| m.0) |
| 422 |
} |
| 423 |
|
| 424 |
impl Current for KernelCmdline { |
| 425 |
const PATH: &'static str = "/proc/cmdline"; |
| 426 |
} |
| 427 |
|
| 428 |
/// Get a list of the arguments passed to the Linux kernel at boot time |
| 429 |
/// |
| 430 |
/// This corresponds to the data in `/proc/cmdline`. |
| 431 |
pub fn cmdline() -> ProcResult<Vec<String>> { |
| 432 |
KernelCmdline::current().map(|c| c.0) |
| 433 |
} |
| 434 |
|
| 435 |
impl Current for CpuInfo { |
| 436 |
const PATH: &'static str = "/proc/cpuinfo"; |
| 437 |
} |
| 438 |
|
| 439 |
impl Current for Devices { |
| 440 |
const PATH: &'static str = "/proc/devices"; |
| 441 |
} |
| 442 |
|
| 443 |
impl Current for DiskStats { |
| 444 |
const PATH: &'static str = "/proc/diskstats"; |
| 445 |
} |
| 446 |
|
| 447 |
/// Get disk IO stat info from /proc/diskstats |
| 448 |
pub fn diskstats() -> ProcResult<Vec<DiskStat>> { |
| 449 |
DiskStats::current().map(|d| d.0) |
| 450 |
} |
| 451 |
|
| 452 |
impl Current for Vec<MountEntry> { |
| 453 |
const PATH: &'static str = "/proc/mounts"; |
| 454 |
} |
| 455 |
|
| 456 |
/// Get a list of mountpoints from `/proc/mounts` |
| 457 |
pub fn mounts() -> ProcResult<Vec<MountEntry>> { |
| 458 |
Vec::<MountEntry>::current() |
| 459 |
} |
| 460 |
|
| 461 |
impl Current for Vec<PartitionEntry> { |
| 462 |
const PATH: &'static str = "/proc/partitions"; |
| 463 |
} |
| 464 |
|
| 465 |
/// Get a list of partitions from `/proc/partitions` |
| 466 |
pub fn partitions() -> ProcResult<Vec<PartitionEntry>> { |
| 467 |
Vec::<PartitionEntry>::current() |
| 468 |
} |
| 469 |
|
| 470 |
impl Current for Locks { |
| 471 |
const PATH: &'static str = "/proc/locks"; |
| 472 |
} |
| 473 |
|
| 474 |
/// Get a list of current file locks and leases |
| 475 |
/// |
| 476 |
/// Since Linux 4.9, the list of locks is filtered to show just the locks |
| 477 |
/// for the processes in the PID namespace for which the `/proc` filesystem |
| 478 |
/// was mounted. |
| 479 |
pub fn locks() -> ProcResult<Vec<Lock>> { |
| 480 |
Locks::current().map(|l| l.0) |
| 481 |
} |
| 482 |
|
| 483 |
impl Current for Meminfo { |
| 484 |
const PATH: &'static str = "/proc/meminfo"; |
| 485 |
} |
| 486 |
|
| 487 |
impl Current for CpuPressure { |
| 488 |
const PATH: &'static str = "/proc/pressure/cpu"; |
| 489 |
} |
| 490 |
|
| 491 |
impl Current for MemoryPressure { |
| 492 |
const PATH: &'static str = "/proc/pressure/memory"; |
| 493 |
} |
| 494 |
|
| 495 |
impl Current for IoPressure { |
| 496 |
const PATH: &'static str = "/proc/pressure/io"; |
| 497 |
} |
| 498 |
|
| 499 |
impl Current for SharedMemorySegments { |
| 500 |
const PATH: &'static str = "/proc/sysvipc/shm"; |
| 501 |
} |
| 502 |
|
| 503 |
impl Current for Uptime { |
| 504 |
const PATH: &'static str = "/proc/uptime"; |
| 505 |
} |
| 506 |
|
| 507 |
#[cfg(test)] |
| 508 |
mod tests { |
| 509 |
use super::*; |
| 510 |
|
| 511 |
#[test] |
| 512 |
fn test_statics() { |
| 513 |
println!("{:?}", crate::sys::kernel::Version::cached()); |
| 514 |
} |
| 515 |
|
| 516 |
#[test] |
| 517 |
fn test_loadavg() { |
| 518 |
let load = LoadAverage::current().unwrap(); |
| 519 |
println!("{:?}", load); |
| 520 |
} |
| 521 |
|
| 522 |
#[test] |
| 523 |
fn test_kernel_config() { |
| 524 |
// TRAVIS |
| 525 |
// we don't have access to the kernel_config on travis, so skip that test there |
| 526 |
match std::env::var("TRAVIS") { |
| 527 |
Ok(ref s) if s == "true" => return, |
| 528 |
_ => {} |
| 529 |
} |
| 530 |
if !Path::new(PROC_CONFIG_GZ).exists() && !Path::new(BOOT_CONFIG).exists() { |
| 531 |
return; |
| 532 |
} |
| 533 |
|
| 534 |
let config = KernelConfig::current().unwrap(); |
| 535 |
println!("{:#?}", config); |
| 536 |
} |
| 537 |
|
| 538 |
#[test] |
| 539 |
fn test_file_io_errors() { |
| 540 |
fn inner<P: AsRef<Path>>(p: P) -> Result<(), ProcError> { |
| 541 |
let mut file = FileWrapper::open(p)?; |
| 542 |
|
| 543 |
let mut buf = [0; 128]; |
| 544 |
file.read_exact(&mut buf[0..128])?; |
| 545 |
|
| 546 |
Ok(()) |
| 547 |
} |
| 548 |
|
| 549 |
let err = inner("/this_should_not_exist").unwrap_err(); |
| 550 |
println!("{}", err); |
| 551 |
|
| 552 |
match err { |
| 553 |
ProcError::NotFound(Some(p)) => { |
| 554 |
assert_eq!(p, Path::new("/this_should_not_exist")); |
| 555 |
} |
| 556 |
x => panic!("Unexpected return value: {:?}", x), |
| 557 |
} |
| 558 |
|
| 559 |
match inner("/proc/loadavg") { |
| 560 |
Err(ProcError::Io(_, Some(p))) => { |
| 561 |
assert_eq!(p, Path::new("/proc/loadavg")); |
| 562 |
} |
| 563 |
x => panic!("Unexpected return value: {:?}", x), |
| 564 |
} |
| 565 |
} |
| 566 |
|
| 567 |
#[test] |
| 568 |
fn test_kernel_stat() { |
| 569 |
let stat = KernelStats::current().unwrap(); |
| 570 |
println!("{:#?}", stat); |
| 571 |
|
| 572 |
// the boottime from KernelStats should match the boottime from /proc/uptime |
| 573 |
let boottime = boot_time_secs().unwrap(); |
| 574 |
|
| 575 |
let diff = (boottime as i32 - stat.btime as i32).abs(); |
| 576 |
assert!(diff <= 1); |
| 577 |
|
| 578 |
let cpuinfo = CpuInfo::current().unwrap(); |
| 579 |
assert_eq!(cpuinfo.num_cores(), stat.cpu_time.len()); |
| 580 |
|
| 581 |
// the sum of each individual CPU should be equal to the total cpu entry |
| 582 |
// note: on big machines with 128 cores, it seems that the differences can be rather high, |
| 583 |
// especially when heavily loaded. So this test tolerates a 6000-tick discrepancy |
| 584 |
// (60 seconds in a 100-tick-per-second kernel) |
| 585 |
|
| 586 |
let user: u64 = stat.cpu_time.iter().map(|i| i.user).sum(); |
| 587 |
let nice: u64 = stat.cpu_time.iter().map(|i| i.nice).sum(); |
| 588 |
let system: u64 = stat.cpu_time.iter().map(|i| i.system).sum(); |
| 589 |
assert!( |
| 590 |
(stat.total.user as i64 - user as i64).abs() < 6000, |
| 591 |
"sum:{} total:{} diff:{}", |
| 592 |
stat.total.user, |
| 593 |
user, |
| 594 |
stat.total.user - user |
| 595 |
); |
| 596 |
assert!( |
| 597 |
(stat.total.nice as i64 - nice as i64).abs() < 6000, |
| 598 |
"sum:{} total:{} diff:{}", |
| 599 |
stat.total.nice, |
| 600 |
nice, |
| 601 |
stat.total.nice - nice |
| 602 |
); |
| 603 |
assert!( |
| 604 |
(stat.total.system as i64 - system as i64).abs() < 6000, |
| 605 |
"sum:{} total:{} diff:{}", |
| 606 |
stat.total.system, |
| 607 |
system, |
| 608 |
stat.total.system - system |
| 609 |
); |
| 610 |
|
| 611 |
let diff = stat.total.idle as i64 - (stat.cpu_time.iter().map(|i| i.idle).sum::<u64>() as i64).abs(); |
| 612 |
assert!(diff < 1000, "idle time difference too high: {}", diff); |
| 613 |
} |
| 614 |
|
| 615 |
#[test] |
| 616 |
fn test_vmstat() { |
| 617 |
let stat = VmStat::current().unwrap(); |
| 618 |
println!("{:?}", stat); |
| 619 |
} |
| 620 |
|
| 621 |
#[test] |
| 622 |
fn test_modules() { |
| 623 |
let KernelModules(mods) = KernelModules::current().unwrap(); |
| 624 |
for module in mods.values() { |
| 625 |
println!("{:?}", module); |
| 626 |
} |
| 627 |
} |
| 628 |
|
| 629 |
#[test] |
| 630 |
fn tests_tps() { |
| 631 |
let tps = ticks_per_second(); |
| 632 |
println!("{} ticks per second", tps); |
| 633 |
} |
| 634 |
|
| 635 |
#[test] |
| 636 |
fn test_cmdline() { |
| 637 |
let KernelCmdline(cmdline) = KernelCmdline::current().unwrap(); |
| 638 |
|
| 639 |
for argument in cmdline { |
| 640 |
println!("{}", argument); |
| 641 |
} |
| 642 |
} |
| 643 |
|
| 644 |
/// Test that our error type can be easily used with the `failure` crate |
| 645 |
#[test] |
| 646 |
fn test_failure() { |
| 647 |
fn inner() -> Result<(), failure::Error> { |
| 648 |
let _load = crate::LoadAverage::current()?; |
| 649 |
Ok(()) |
| 650 |
} |
| 651 |
let _ = inner(); |
| 652 |
|
| 653 |
fn inner2() -> Result<(), failure::Error> { |
| 654 |
let proc = crate::process::Process::new(1)?; |
| 655 |
let _io = proc.maps()?; |
| 656 |
Ok(()) |
| 657 |
} |
| 658 |
|
| 659 |
let _ = inner2(); |
| 660 |
// Unwrapping this failure should produce a message that looks like: |
| 661 |
// thread 'tests::test_failure' panicked at 'called `Result::unwrap()` on an `Err` value: PermissionDenied(Some("/proc/1/maps"))', src/libcore/result.rs:997:5 |
| 662 |
} |
| 663 |
|
| 664 |
/// Test that an ESRCH error gets mapped into a ProcError::NotFound |
| 665 |
#[test] |
| 666 |
fn test_esrch() { |
| 667 |
let mut command = std::process::Command::new("sleep") |
| 668 |
.arg("10000") |
| 669 |
.spawn() |
| 670 |
.expect("Failed to start sleep"); |
| 671 |
let p = crate::process::Process::new(command.id() as i32).expect("Failed to create Process"); |
| 672 |
command.kill().expect("Failed to kill sleep"); |
| 673 |
command.wait().expect("Failed to wait for sleep"); |
| 674 |
let e = p.stat().unwrap_err(); |
| 675 |
println!("{:?}", e); |
| 676 |
|
| 677 |
assert!(matches!(e, ProcError::NotFound(_))); |
| 678 |
} |
| 679 |
|
| 680 |
#[test] |
| 681 |
fn test_cpuinfo() { |
| 682 |
let info = CpuInfo::current().unwrap(); |
| 683 |
println!("{:#?}", info.flags(0)); |
| 684 |
for num in 0..info.num_cores() { |
| 685 |
info.model_name(num).unwrap(); |
| 686 |
info.vendor_id(num).unwrap(); |
| 687 |
// May not be available on some old kernels: |
| 688 |
info.physical_id(num); |
| 689 |
} |
| 690 |
|
| 691 |
//assert_eq!(info.num_cores(), 8); |
| 692 |
} |
| 693 |
|
| 694 |
#[test] |
| 695 |
fn test_devices() { |
| 696 |
let devices = Devices::current().unwrap(); |
| 697 |
println!("{:#?}", devices); |
| 698 |
} |
| 699 |
|
| 700 |
#[test] |
| 701 |
fn test_diskstats() { |
| 702 |
for disk in super::diskstats().unwrap() { |
| 703 |
println!("{:?}", disk); |
| 704 |
} |
| 705 |
} |
| 706 |
|
| 707 |
#[test] |
| 708 |
fn test_locks() { |
| 709 |
for lock in locks().unwrap() { |
| 710 |
println!("{:?}", lock); |
| 711 |
if let LockType::Other(s) = lock.lock_type { |
| 712 |
panic!("Found an unknown lock type {:?}", s); |
| 713 |
} |
| 714 |
if let LockKind::Other(s) = lock.kind { |
| 715 |
panic!("Found an unknown lock kind {:?}", s); |
| 716 |
} |
| 717 |
if let LockMode::Other(s) = lock.mode { |
| 718 |
panic!("Found an unknown lock mode {:?}", s); |
| 719 |
} |
| 720 |
} |
| 721 |
} |
| 722 |
|
| 723 |
#[allow(clippy::cognitive_complexity)] |
| 724 |
#[allow(clippy::blocks_in_if_conditions)] |
| 725 |
#[test] |
| 726 |
fn test_meminfo() { |
| 727 |
// TRAVIS |
| 728 |
// we don't have access to the kernel_config on travis, so skip that test there |
| 729 |
match ::std::env::var("TRAVIS") { |
| 730 |
Ok(ref s) if s == "true" => return, |
| 731 |
_ => {} |
| 732 |
} |
| 733 |
|
| 734 |
let kernel = KernelVersion::current().unwrap(); |
| 735 |
let config = KernelConfig::current().ok(); |
| 736 |
|
| 737 |
let meminfo = Meminfo::current().unwrap(); |
| 738 |
println!("{:#?}", meminfo); |
| 739 |
|
| 740 |
// for the fields that are only present in some kernel versions, make sure our |
| 741 |
// actual kernel agrees |
| 742 |
|
| 743 |
if kernel >= KernelVersion::new(3, 14, 0) { |
| 744 |
assert!(meminfo.mem_available.is_some()); |
| 745 |
} |
| 746 |
|
| 747 |
if kernel >= KernelVersion::new(2, 6, 28) { |
| 748 |
assert!(meminfo.active_anon.is_some()); |
| 749 |
assert!(meminfo.inactive_anon.is_some()); |
| 750 |
assert!(meminfo.active_file.is_some()); |
| 751 |
assert!(meminfo.inactive_file.is_some()); |
| 752 |
} else { |
| 753 |
assert!(meminfo.active_anon.is_none()); |
| 754 |
assert!(meminfo.inactive_anon.is_none()); |
| 755 |
assert!(meminfo.active_file.is_none()); |
| 756 |
assert!(meminfo.inactive_file.is_none()); |
| 757 |
} |
| 758 |
|
| 759 |
if kernel >= KernelVersion::new(2, 6, 28) |
| 760 |
&& kernel <= KernelVersion::new(2, 6, 30) |
| 761 |
&& meminfo.unevictable.is_some() |
| 762 |
{ |
| 763 |
if let Some(KernelConfig(ref config)) = config { |
| 764 |
assert!(config.get("CONFIG_UNEVICTABLE_LRU").is_some()); |
| 765 |
} |
| 766 |
} |
| 767 |
|
| 768 |
if kernel >= KernelVersion::new(2, 6, 19) |
| 769 |
&& config |
| 770 |
.as_ref() |
| 771 |
.map_or(false, |KernelConfig(cfg)| cfg.contains_key("CONFIG_HIGHMEM")) |
| 772 |
{ |
| 773 |
assert!(meminfo.high_total.is_some()); |
| 774 |
assert!(meminfo.high_free.is_some()); |
| 775 |
assert!(meminfo.low_total.is_some()); |
| 776 |
assert!(meminfo.low_free.is_some()); |
| 777 |
} else { |
| 778 |
assert!(meminfo.high_total.is_none()); |
| 779 |
assert!(meminfo.high_free.is_none()); |
| 780 |
assert!(meminfo.low_total.is_none()); |
| 781 |
assert!(meminfo.low_free.is_none()); |
| 782 |
} |
| 783 |
|
| 784 |
// Possible bug in procfs documentation: |
| 785 |
// The man page says that MmapCopy requires CONFIG_MMU, but if you look at the |
| 786 |
// source, MmapCopy is only included if CONFIG_MMU is *missing*: |
| 787 |
// https://github.com/torvalds/linux/blob/v4.17/fs/proc/meminfo.c#L80 |
| 788 |
//if kernel >= KernelVersion::new(2, 6, 29) && config.contains_key("CONFIG_MMU") { |
| 789 |
// assert!(meminfo.mmap_copy.is_some()); |
| 790 |
//} else { |
| 791 |
// assert!(meminfo.mmap_copy.is_none()); |
| 792 |
//} |
| 793 |
|
| 794 |
if kernel >= KernelVersion::new(2, 6, 18) { |
| 795 |
assert!(meminfo.anon_pages.is_some()); |
| 796 |
assert!(meminfo.page_tables.is_some()); |
| 797 |
assert!(meminfo.nfs_unstable.is_some()); |
| 798 |
assert!(meminfo.bounce.is_some()); |
| 799 |
} else { |
| 800 |
assert!(meminfo.anon_pages.is_none()); |
| 801 |
assert!(meminfo.page_tables.is_none()); |
| 802 |
assert!(meminfo.nfs_unstable.is_none()); |
| 803 |
assert!(meminfo.bounce.is_none()); |
| 804 |
} |
| 805 |
|
| 806 |
if kernel >= KernelVersion::new(2, 6, 32) { |
| 807 |
assert!(meminfo.shmem.is_some()); |
| 808 |
assert!(meminfo.kernel_stack.is_some()); |
| 809 |
} else { |
| 810 |
assert!(meminfo.shmem.is_none()); |
| 811 |
assert!(meminfo.kernel_stack.is_none()); |
| 812 |
} |
| 813 |
|
| 814 |
if kernel >= KernelVersion::new(2, 6, 19) { |
| 815 |
assert!(meminfo.s_reclaimable.is_some()); |
| 816 |
assert!(meminfo.s_unreclaim.is_some()); |
| 817 |
} else { |
| 818 |
assert!(meminfo.s_reclaimable.is_none()); |
| 819 |
assert!(meminfo.s_unreclaim.is_none()); |
| 820 |
} |
| 821 |
|
| 822 |
if kernel >= KernelVersion::new(2, 6, 27) |
| 823 |
&& config |
| 824 |
.as_ref() |
| 825 |
.map_or(false, |KernelConfig(cfg)| cfg.contains_key("CONFIG_QUICKLIST")) |
| 826 |
{ |
| 827 |
assert!(meminfo.quicklists.is_some()); |
| 828 |
} else { |
| 829 |
assert!(meminfo.quicklists.is_none()); |
| 830 |
} |
| 831 |
|
| 832 |
if kernel >= KernelVersion::new(2, 6, 26) { |
| 833 |
assert!(meminfo.writeback_tmp.is_some()); |
| 834 |
} else { |
| 835 |
assert!(meminfo.writeback_tmp.is_none()); |
| 836 |
} |
| 837 |
|
| 838 |
if kernel >= KernelVersion::new(2, 6, 10) { |
| 839 |
assert!(meminfo.commit_limit.is_some()); |
| 840 |
} else { |
| 841 |
assert!(meminfo.commit_limit.is_none()); |
| 842 |
} |
| 843 |
|
| 844 |
if kernel >= KernelVersion::new(2, 6, 32) |
| 845 |
&& config.as_ref().map_or( |
| 846 |
std::path::Path::new("/proc/kpagecgroup").exists(), |
| 847 |
|KernelConfig(cfg)| cfg.contains_key("CONFIG_MEMORY_FAILURE"), |
| 848 |
) |
| 849 |
{ |
| 850 |
assert!(meminfo.hardware_corrupted.is_some()); |
| 851 |
} else { |
| 852 |
assert!(meminfo.hardware_corrupted.is_none()); |
| 853 |
} |
| 854 |
|
| 855 |
if kernel >= KernelVersion::new(2, 6, 38) |
| 856 |
&& config.as_ref().map_or(false, |KernelConfig(cfg)| { |
| 857 |
cfg.contains_key("CONFIG_TRANSPARENT_HUGEPAGE") |
| 858 |
}) |
| 859 |
{ |
| 860 |
assert!(meminfo.anon_hugepages.is_some()); |
| 861 |
} else { |
| 862 |
// SOme distributions may backport this option into older kernels |
| 863 |
// assert!(meminfo.anon_hugepages.is_none()); |
| 864 |
} |
| 865 |
|
| 866 |
if kernel >= KernelVersion::new(4, 8, 0) |
| 867 |
&& config.as_ref().map_or(true, |KernelConfig(cfg)| { |
| 868 |
cfg.contains_key("CONFIG_TRANSPARENT_HUGEPAGE") |
| 869 |
}) |
| 870 |
{ |
| 871 |
assert!(meminfo.shmem_hugepages.is_some()); |
| 872 |
assert!(meminfo.shmem_pmd_mapped.is_some()); |
| 873 |
} else { |
| 874 |
assert!(meminfo.shmem_hugepages.is_none()); |
| 875 |
assert!(meminfo.shmem_pmd_mapped.is_none()); |
| 876 |
} |
| 877 |
|
| 878 |
if kernel >= KernelVersion::new(3, 1, 0) |
| 879 |
&& config |
| 880 |
.as_ref() |
| 881 |
.map_or(true, |KernelConfig(cfg)| cfg.contains_key("CONFIG_CMA")) |
| 882 |
{ |
| 883 |
assert!(meminfo.cma_total.is_some()); |
| 884 |
assert!(meminfo.cma_free.is_some()); |
| 885 |
} else { |
| 886 |
assert!(meminfo.cma_total.is_none()); |
| 887 |
assert!(meminfo.cma_free.is_none()); |
| 888 |
} |
| 889 |
|
| 890 |
if config |
| 891 |
.as_ref() |
| 892 |
.map_or(true, |KernelConfig(cfg)| cfg.contains_key("CONFIG_HUGETLB_PAGE")) |
| 893 |
{ |
| 894 |
assert!(meminfo.hugepages_total.is_some()); |
| 895 |
assert!(meminfo.hugepages_free.is_some()); |
| 896 |
assert!(meminfo.hugepagesize.is_some()); |
| 897 |
} else { |
| 898 |
assert!(meminfo.hugepages_total.is_none()); |
| 899 |
assert!(meminfo.hugepages_free.is_none()); |
| 900 |
assert!(meminfo.hugepagesize.is_none()); |
| 901 |
} |
| 902 |
|
| 903 |
if kernel >= KernelVersion::new(2, 6, 17) |
| 904 |
&& config |
| 905 |
.as_ref() |
| 906 |
.map_or(true, |KernelConfig(cfg)| cfg.contains_key("CONFIG_HUGETLB_PAGE")) |
| 907 |
{ |
| 908 |
assert!(meminfo.hugepages_rsvd.is_some()); |
| 909 |
} else { |
| 910 |
assert!(meminfo.hugepages_rsvd.is_none()); |
| 911 |
} |
| 912 |
|
| 913 |
if kernel >= KernelVersion::new(2, 6, 24) |
| 914 |
&& config |
| 915 |
.as_ref() |
| 916 |
.map_or(true, |KernelConfig(cfg)| cfg.contains_key("CONFIG_HUGETLB_PAGE")) |
| 917 |
{ |
| 918 |
assert!(meminfo.hugepages_surp.is_some()); |
| 919 |
} else { |
| 920 |
assert!(meminfo.hugepages_surp.is_none()); |
| 921 |
} |
| 922 |
} |
| 923 |
|
| 924 |
#[allow(clippy::manual_range_contains)] |
| 925 |
fn valid_percentage(value: f32) -> bool { |
| 926 |
value >= 0.00 && value < 100.0 |
| 927 |
} |
| 928 |
|
| 929 |
#[test] |
| 930 |
fn test_mem_pressure() { |
| 931 |
if !Path::new("/proc/pressure/memory").exists() { |
| 932 |
return; |
| 933 |
} |
| 934 |
|
| 935 |
let mem_psi = MemoryPressure::current().unwrap(); |
| 936 |
assert!(valid_percentage(mem_psi.some.avg10)); |
| 937 |
assert!(valid_percentage(mem_psi.some.avg60)); |
| 938 |
assert!(valid_percentage(mem_psi.some.avg300)); |
| 939 |
|
| 940 |
assert!(valid_percentage(mem_psi.full.avg10)); |
| 941 |
assert!(valid_percentage(mem_psi.full.avg60)); |
| 942 |
assert!(valid_percentage(mem_psi.full.avg300)); |
| 943 |
} |
| 944 |
|
| 945 |
#[test] |
| 946 |
fn test_io_pressure() { |
| 947 |
if !Path::new("/proc/pressure/io").exists() { |
| 948 |
return; |
| 949 |
} |
| 950 |
|
| 951 |
let io_psi = IoPressure::current().unwrap(); |
| 952 |
assert!(valid_percentage(io_psi.some.avg10)); |
| 953 |
assert!(valid_percentage(io_psi.some.avg60)); |
| 954 |
assert!(valid_percentage(io_psi.some.avg300)); |
| 955 |
|
| 956 |
assert!(valid_percentage(io_psi.full.avg10)); |
| 957 |
assert!(valid_percentage(io_psi.full.avg60)); |
| 958 |
assert!(valid_percentage(io_psi.full.avg300)); |
| 959 |
} |
| 960 |
|
| 961 |
#[test] |
| 962 |
fn test_cpu_pressure() { |
| 963 |
if !Path::new("/proc/pressure/cpu").exists() { |
| 964 |
return; |
| 965 |
} |
| 966 |
|
| 967 |
let cpu_psi = CpuPressure::current().unwrap(); |
| 968 |
assert!(valid_percentage(cpu_psi.some.avg10)); |
| 969 |
assert!(valid_percentage(cpu_psi.some.avg60)); |
| 970 |
assert!(valid_percentage(cpu_psi.some.avg300)); |
| 971 |
} |
| 972 |
} |