Skip to main content

sys_lib/
lib.rs

1//! # sys_lib
2//!
3//! System facts for Rust services, container-aware by default, plus the boot
4//! kit every long-running service needs in its first milliseconds: build info,
5//! instance info, and a process guard.
6//!
7//! Every reading is a file read or a system call. sys-lib never starts a
8//! thread or a timer, never runs another program, and has no third-party
9//! runtime dependencies.
10//!
11//! ## Tier 1
12//!
13//! Add it with Cargo's rename, `sys = { package = "sys-lib", version = "0.4" }`,
14//! and every file writes `sys::`; without the rename, `use sys_lib as sys;`
15//! does the same (the examples use that form so they compile either way).
16//! One plain call per fact; static facts are read once and cached:
17//!
18//! ```
19//! use sys_lib as sys;
20//!
21//! println!("{}", sys::os::name());         // "Ubuntu 24.04.1 LTS", "macOS 15.1 Sequoia", "Windows 11 Pro"
22//! println!("{}", sys::os::distro());       // "Ubuntu"; "Windows", "macOS" elsewhere
23//! println!("{}", sys::cpu::name());        // "AMD Ryzen 9 7950X"
24//! println!("{} cores, {} threads", sys::cpu::physical(), sys::cpu::logical());
25//! let workers = sys::cpu::available();     // what this process may use: affinity, cpuset, quota
26//! # assert!(workers >= 1);
27//! println!("{} of {} used", sys::mem::used()?, sys::mem::total()?);  // the container's limit inside one
28//! println!("{} free here", sys::disk::space(".")?.available);
29//! # Ok::<(), sys_lib::Error>(())
30//! ```
31//!
32//! The boot kit:
33//!
34//! ```no_run
35//! # #[cfg(all(feature = "instance", feature = "guard"))]
36//! # fn main() -> Result<(), sys_lib::Error> {
37//! use sys_lib as sys;
38//!
39//! let _guard = sys::process::guard("site")?;   // single-instance lock, umask, open-file limit
40//! let build = sys::build_info!();              // with `sys::build::emit()` in build.rs
41//! let instance = sys::Instance::start();
42//! println!("{build}\n{instance}");
43//! # Ok(())
44//! # }
45//! # #[cfg(not(all(feature = "instance", feature = "guard")))]
46//! # fn main() {}
47//! ```
48//!
49//! ## Status
50//!
51//! `0.4.0`, live readings: the boot kit ([`os`], [`cpu`], [`host`],
52//! [`process`], [`build`], and instance info), [`mem`], [`disk`], [`net`], and
53//! CPU usage, load, pressure, and features. Virtualization, power, device
54//! identity, and the environment reports arrive through `0.6`; the complete
55//! approved API, each item with the version it arrives in, is `docs/API.md` in
56//! the [repository](https://github.com/jamesgober/sys-lib).
57
58#![doc(html_root_url = "https://docs.rs/sys-lib")]
59#![cfg_attr(docsrs, feature(doc_cfg))]
60// `deny`, not `forbid`: the per-platform `sys` modules lift it locally to call
61// the OS where std has no API. Nowhere else.
62#![deny(unsafe_code)]
63#![deny(unsafe_op_in_unsafe_fn)]
64#![deny(missing_docs)]
65#![deny(
66    clippy::undocumented_unsafe_blocks,
67    clippy::multiple_unsafe_ops_per_block,
68    clippy::ptr_as_ptr,
69    clippy::cast_ptr_alignment
70)]
71#![cfg_attr(
72    not(test),
73    deny(
74        clippy::unwrap_used,
75        clippy::expect_used,
76        clippy::panic,
77        clippy::todo,
78        clippy::unimplemented,
79        clippy::unreachable,
80        clippy::dbg_macro
81    )
82)]
83
84/// Crate version string, populated by Cargo at build time.
85pub const VERSION: &str = env!("CARGO_PKG_VERSION");
86
87pub mod build;
88pub mod cpu;
89pub mod disk;
90pub mod host;
91#[cfg(feature = "instance")]
92#[cfg_attr(docsrs, doc(cfg(feature = "instance")))]
93pub mod instance;
94pub mod mem;
95pub mod net;
96pub mod os;
97pub mod process;
98
99mod error;
100mod fmt;
101#[cfg(fuzzing)]
102#[doc(hidden)]
103pub mod __fuzz {
104    //! Parser entry points for `fuzz/`; not part of the API.
105    pub use crate::fuzz::*;
106}
107#[cfg(fuzzing)]
108mod fuzz;
109#[cfg(any(target_os = "linux", target_os = "android", test))]
110mod linux;
111mod parse;
112mod pressure;
113mod sys;
114mod units;
115
116pub use build::{BuildInfo, PublicBuild};
117pub use error::{Error, Result};
118#[cfg(feature = "instance")]
119#[cfg_attr(docsrs, doc(cfg(feature = "instance")))]
120pub use instance::{Instance, InstanceId};
121pub use pressure::{Pressure, PressureLevel, Stall};
122pub use units::{Bytes, Mhz, Percent, Rate, Units};
123
124#[cfg(test)]
125mod tests {
126    use super::VERSION;
127
128    #[test]
129    fn test_version_matches_manifest() {
130        assert_eq!(VERSION, env!("CARGO_PKG_VERSION"));
131        // Pre-release and build metadata (`1.0.0-rc.1`, `+build`) follow the core.
132        let core = VERSION.split(['-', '+']).next().unwrap_or_default();
133        assert_eq!(core.split('.').count(), 3, "expected MAJOR.MINOR.PATCH");
134        assert!(
135            core.split('.').all(|part| part.parse::<u64>().is_ok()),
136            "every version component is a number"
137        );
138    }
139}