Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add FreeBSD support #53

Merged
merged 4 commits into from
Oct 10, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
22 changes: 22 additions & 0 deletions .github/workflows/test.yml
Original file line number Diff line number Diff line change
Expand Up @@ -103,3 +103,25 @@ jobs:
token: ${{ secrets.CODECOV_TOKEN }}
files: lcov.info,lcov.use-gauge-on-cpu-seconds-total.info
env_vars: RUNNER

test-cross-platform-freebsd:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/cache@v4
with:
path: |
~/.cargo/bin/
~/.cargo/registry/index/
~/.cargo/registry/cache/
~/.cargo/git/db/
target/
key: ${{ runner.os }}-cargo-${{ hashFiles('**/Cargo.lock') }}
- name: Cross-platform test
uses: cross-platform-actions/action@v0.25.0
with:
operating_system: freebsd
version: '14.1'
run: |
sudo pkg update && sudo pkg install -y rust cmake rust-bindgen-cli
cargo test
3 changes: 3 additions & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,9 @@ rlimit = "0.10.0"
once_cell = "1.13.1"
procfs = { version = "0.16.0", default-features = false }

[target.'cfg(target_os = "freebsd")'.dependencies]
libc = "0.2.159"

[target.'cfg(target_os = "windows")'.dependencies.windows]
version = "0.57.0"
features = [
Expand Down
28 changes: 14 additions & 14 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -8,9 +8,9 @@
# ⏱ metrics-process

This crate provides a [Prometheus]-style [process metrics] collector for the
[metrics] crate, supporting Linux, macOS, and Windows. The collector code is
manually rewritten in Rust from the official Prometheus client for Go
([client_golang]).
[metrics] crate, supporting Linux, macOS, Windows, and FreeBSD. The original
collector code was manually rewritten in Rust from the official Prometheus
client for Go ([client_golang]), FreeBSD support was written from scratch.

[Prometheus]: https://prometheus.io/
[process metrics]: https://prometheus.io/docs/instrumenting/writing_clientlibs/#process-metrics
Expand Down Expand Up @@ -41,17 +41,17 @@ Go ([client_golang]) provides.
> Prior to version 2.0.0, the `process_cpu_seconds_total` metric was Gauge instead of Counter.
> Enable `use-gauge-on-cpu-seconds-total` feature to use the previous behavior.

| Metric name | Linux | macOS | Windows |
| ---------------------------------- | ----- | ----- | ------- |
| `process_cpu_seconds_total` | x | x | x |
| `process_open_fds` | x | x | x |
| `process_max_fds` | x | x | x |
| `process_virtual_memory_bytes` | x | x | x |
| `process_virtual_memory_max_bytes` | x | x | |
| `process_resident_memory_bytes` | x | x | x |
| `process_heap_bytes` | | | |
| `process_start_time_seconds` | x | x | x |
| `process_threads` | x | x | |
| Metric name | Linux | macOS | Windows | FreeBSD |
| ---------------------------------- | ----- | ----- | ------- | ------- |
| `process_cpu_seconds_total` | x | x | x | x |
| `process_open_fds` | x | x | x | x |
| `process_max_fds` | x | x | x | x |
| `process_virtual_memory_bytes` | x | x | x | x |
| `process_virtual_memory_max_bytes` | x | x | | x |
| `process_resident_memory_bytes` | x | x | x | x |
| `process_heap_bytes` | | | | |
| `process_start_time_seconds` | x | x | x | x |
| `process_threads` | x | x | | x |

> [!NOTE]
>
Expand Down
16 changes: 14 additions & 2 deletions src/collector.rs
Original file line number Diff line number Diff line change
@@ -1,13 +1,19 @@
#[cfg_attr(target_os = "macos", path = "collector/macos.rs")]
#[cfg_attr(target_os = "linux", path = "collector/linux.rs")]
#[cfg_attr(target_os = "windows", path = "collector/windows.rs")]
#[cfg_attr(target_os = "freebsd", path = "collector/freebsd.rs")]
#[allow(unused_attributes)]
#[cfg_attr(feature = "dummy", path = "collector/dummy.rs")]
mod collector;

#[cfg(all(
not(feature = "dummy"),
not(any(target_os = "macos", target_os = "linux", target_os = "windows"))
not(any(
target_os = "macos",
target_os = "linux",
target_os = "windows",
target_os = "freebsd"
))
))]
compile_error!(
"A feature \"dummy\" must be enabled to compile this crate on non supported platforms."
Expand Down Expand Up @@ -52,7 +58,12 @@ mod tests {
}
}

#[cfg(any(target_os = "macos", target_os = "linux", target_os = "windows"))]
#[cfg(any(
target_os = "macos",
target_os = "linux",
target_os = "windows",
target_os = "freebsd"
))]
#[test]
fn test_collect_internal_ok() {
fibonacci(40);
Expand All @@ -73,6 +84,7 @@ mod tests {
#[cfg(not(target_os = "macos"))]
#[cfg(not(target_os = "linux"))]
#[cfg(not(target_os = "windows"))]
#[cfg(not(target_os = "freebsd"))]
#[cfg(feature = "dummy")]
#[test]
fn test_collect_internal_ok_dummy() {
Expand Down
112 changes: 112 additions & 0 deletions src/collector/freebsd.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,112 @@
use super::Metrics;

fn getrusage(who: libc::c_int) -> Option<libc::rusage> {
let mut usage = std::mem::MaybeUninit::zeroed();
// SAFETY: libc call; usage is valid pointer to rusage struct
if unsafe { libc::getrusage(who, usage.as_mut_ptr()) } == 0 {
// SAFETY: libc call was success, struct must be initialized
Some(unsafe { usage.assume_init() })
} else {
None
}
}

fn getrlimit(resource: libc::c_int) -> Option<libc::rlimit> {
let mut limit = std::mem::MaybeUninit::zeroed();
// SAFETY: libc call; limit is valid pointer to rlimit struct
if unsafe { libc::getrlimit(resource, limit.as_mut_ptr()) } == 0 {
// SAFETY: libc call was success, struct must be initialized
Some(unsafe { limit.assume_init() })
} else {
None
}
}

fn translate_rlim(rlim: libc::rlim_t) -> u64 {
if rlim == libc::RLIM_INFINITY {
0
} else {
rlim as u64
}
}

fn kinfo_getproc(pid: libc::pid_t) -> Option<libc::kinfo_proc> {
// References:
// kinfo_getproc() code from FreeBSD: https://github.com/freebsd/freebsd-src/blob/b22be3bbb2de75157c97d8baa01ce6cd654caddf/lib/libutil/kinfo_getproc.c
// code from deno doing similar stuff: https://github.com/denoland/deno/blob/20ae8db50d7d48ad020b83ebe78dc0e9e9eab3b2/runtime/ops/os/mod.rs#L415
let mib = [libc::CTL_KERN, libc::KERN_PROC, libc::KERN_PROC_PID, pid];

let mut kinfo_proc = std::mem::MaybeUninit::zeroed();
let kinfo_proc_size = std::mem::size_of_val(&kinfo_proc) as libc::size_t;
let mut data_size = kinfo_proc_size;

// SAFETY: libc call; mib is statically initialized, kinfo_proc is valid pointer
// to kinfo_proc and data_size holds its size
if unsafe {
libc::sysctl(
mib.as_ptr(),
mib.len() as _,
kinfo_proc.as_mut_ptr() as *mut libc::c_void,
&mut data_size,
std::ptr::null(),
0,
)
} == 0
&& data_size == kinfo_proc_size
{
// SAFETY: libc call was success and check for struct size passed, struct must be initialized
Some(unsafe { kinfo_proc.assume_init() })
} else {
None
}
}

pub fn collect() -> Metrics {
let mut metrics = Metrics::default();

if let Some(usage) = getrusage(libc::RUSAGE_SELF) {
metrics.cpu_seconds_total = Some(
(usage.ru_utime.tv_sec + usage.ru_stime.tv_sec) as f64
+ (usage.ru_utime.tv_usec + usage.ru_stime.tv_usec) as f64 / 1000000.0,
);
}

if let Some(limit_as) = getrlimit(libc::RLIMIT_AS) {
metrics.virtual_memory_max_bytes = Some(translate_rlim(limit_as.rlim_cur));
}

if let Some(limit_as) = getrlimit(libc::RLIMIT_NOFILE) {
metrics.max_fds = Some(translate_rlim(limit_as.rlim_cur));
}

// SAFETY: libc call
let pid = unsafe { libc::getpid() };

if let Some(kinfo_proc) = kinfo_getproc(pid) {
// struct kinfo_proc layout for reference
// libc crate: https://docs.rs/libc/latest/x86_64-unknown-freebsd/libc/struct.kinfo_proc.html
// FreeBSD: https://github.com/freebsd/freebsd-src/blob/b22be3bbb2de75157c97d8baa01ce6cd654caddf/lib/libutil/kinfo_getfile.c

// SAFETY: libc call
let pagesize = unsafe { libc::sysconf(libc::_SC_PAGESIZE) } as u64;
metrics.virtual_memory_bytes = Some(kinfo_proc.ki_size as u64);
metrics.resident_memory_bytes = Some(kinfo_proc.ki_rssize as u64 * pagesize);
use std::convert::TryInto as _;
metrics.start_time_seconds = kinfo_proc.ki_start.tv_sec.try_into().ok();
metrics.threads = kinfo_proc.ki_numthreads.try_into().ok();

// note that we can't access pointers in kinfo_proc as these point to kernel space
}

// Alternative to this would be implementing kinfo_getfile() like interface, see
// https://github.com/freebsd/freebsd-src/blob/b22be3bbb2de75157c97d8baa01ce6cd654caddf/lib/libutil/kinfo_getfile.c
// it can be done similar to kinfo_getproc() implementation above, but is more cumbersome
// because we have to parse structures of varying size frow raw memory. As long as
// it's common to read /proc on Linux, it shuld be as ok to read /dev/fs (which
// is roughly the same as /proc/self/fd) on FreeBSD.
metrics.open_fds = std::fs::read_dir("/dev/fd")
.ok()
.map(|read_dir| read_dir.count() as u64);

metrics
}