Weave Code
Weaver
Helps Laravel developers discover, compare, and choose open-source packages. See popularity, security, maintainers, and scores at a glance to make better decisions.
Feedback
Share your thoughts, report bugs, or suggest improvements.
Subject
Message

System Metrics Laravel Package

cboxdk/system-metrics

Get real-time system metrics from Linux and macOS in pure PHP. No extensions or dependencies—just type-safe, readonly classes covering CPU, memory, storage, network, load, uptime, and container metrics with explicit Result-based error handling.

View on GitHub
Deep Wiki
Context7
v3.0.0

Breaking Changes

  • SystemLimits::$cpuCores: Changed from int to float to support fractional CPU quotas (e.g. 200m = 0.2 cores, 1500m = 1.5 cores).
  • SystemLimits::$currentCpuCores: Changed from int to float.
  • SystemLimits::availableCpuCores(): Now returns float instead of int.
  • SystemLimits::canScaleCpu(): Parameter changed from int to float.
  • ContainerLimits::cpuUtilizationPercentage(): No longer capped at 100%. Can exceed 100% during over-quota burst scenarios.
  • ContainerLimits::memoryUtilizationPercentage(): No longer capped at 100%. Can exceed 100% if memory usage exceeds limit before OOM kill.

Bug Fixes

  • Fix CPU limit using headroom instead of quota: CompositeSystemLimitsSource was using availableCpuCores() (quota − usage) to populate the cpuCores limit field. The limit now correctly uses cpuQuota directly. Same fix for memory: uses memoryLimitBytes instead of availableMemoryBytes().
  • Fix delta-based CPU usage sampling permanently broken: CompositeContainerMetricsSource was creating a new LinuxCgroupMetricsSource on every read() call, resetting the parser's delta cache. cpuUsageCores was always null. The source instance is now persisted across calls.
  • Fix fractional CPU precision loss: Removed (int) ceil() casts that rounded cgroup CPU quotas to whole cores (e.g. 200m/0.2 cores became 1).
  • Fix test: container appears in overview: The FakeSystemMetricsTest container-in-overview test now correctly configures insideContainer: true on the fake environment.

Migration Guide

Downstream consumers that use SystemLimits CPU fields need to handle float instead of int:

// Before (v2.x)
$cores = $limits->cpuCores;        // int: 1, 2, 4, 8
$available = $limits->availableCpuCores(); // int

// After (v3.0)
$cores = $limits->cpuCores;        // float: 0.2, 1.5, 4.0, 8.0
$available = $limits->availableCpuCores(); // float

If you relied on cpuUtilizationPercentage() or memoryUtilizationPercentage() never exceeding 100%, add your own capping:

$util = min(100.0, $container->cpuUtilizationPercentage());

Full Changelog: https://github.com/cboxdk/system-metrics/compare/v2.3.1...v3.0.0

v2.3.1

What's Changed

Bug Fixes

  • Rewrite container detection to use allowlist strategy: Replaced fragile cgroup path heuristics with clean allowlist approach. Only known container indicators trigger detection. No more false positives on VMs with systemd/cgroup v2.
  • Fix OS version showing "unknown": /etc/os-release is a symlink to /usr/lib/os-release on systemd distros. The realpath() security check resolved the symlink but /usr/lib/ was not in the FileReader whitelist, silently blocking the read. Added /usr/lib/os-release to the whitelist.
  • Use PRETTY_NAME as primary OS name for more descriptive output (e.g. "Ubuntu 24.04.3 LTS").
  • Fall back through VERSION_ID → VERSION → BUILD_ID for the version field.
  • Added LXC detection via cgroup keywords.

Full Changelog: https://github.com/cboxdk/system-metrics/compare/v2.3.0...v2.3.1

v2.3.0

What's Changed

Bug Fixes

  • SystemOverviewAction: Only populates the container field when environment detection confirms insideContainer is true. Previously, any Linux system with cgroup v2 would report container metrics.
  • LinuxEnvironmentDetector: Added /proc/1/environ check for systemd container markers (LXC/nspawn).

Deprecations

  • SystemLimits::isContainerized(): Deprecated. Use SystemMetrics::environment()->containerization->insideContainer for accurate container detection. The cgroup source alone is not a reliable indicator of containerization on modern Linux.

Full Changelog: https://github.com/cboxdk/system-metrics/compare/v2.2.0...v2.3.0

v2.2.0

What's Changed

New Features

  • Testing Support: New src/Testing/ namespace with fake sources for all metric types

    • FakeSystemMetrics::install() / uninstall() — one-line test setup and teardown
    • Fake sources for all 9 metric types with set() and failWith() methods
    • FakeContainerMetricsSource::asContainer() for simulating containerized environments
    • Sensible defaults representing a healthy 4-core, 8 GB Linux server
  • Full SystemMetricsConfig Support: All metric sources are now configurable via SystemMetricsConfig

    • Added setters/getters for LoadAverageSource, StorageMetricsSource, NetworkMetricsSource, UptimeSource, ContainerMetricsSource, SystemLimitsSource
    • SystemMetrics facade routes all methods through SystemMetricsConfig

Full Changelog: https://github.com/cboxdk/system-metrics/compare/v2.1.0...v2.2.0

v2.1.0

What's Changed

New Features

  • Comprehensive SystemOverview: SystemMetrics::overview() now returns all available metrics in a single call

    • Added loadAverage (?LoadAverageSnapshot) — system load averages
    • Added uptime (?UptimeSnapshot) — system uptime and boot time
    • Added limits (?SystemLimits) — unified resource limits (cgroup-aware)
    • Added container (?ContainerLimits) — container-specific cgroup data
  • Graceful Partial Failures: Optional metrics (storage, network, load average, uptime, limits, container) now return null instead of failing the entire overview. Core metrics (environment, CPU, memory) remain required.

  • Fallback Sources: Added FallbackLoadAverageSource and FallbackUptimeSource for graceful degradation when FFI is unavailable (e.g., PHP-FPM with ffi.enable=preload)

  • Absolute Command Path Resolution: ProcessRunner now resolves commands to absolute paths, fixing metric collection in restricted environments like PHP-FPM where PATH may not include /usr/sbin

Breaking Changes

  • SystemOverview::$storage and SystemOverview::$network are now nullable (?StorageSnapshot, ?NetworkSnapshot). Previously they were required and would fail the entire overview if unavailable.

Full Changelog: https://github.com/cboxdk/system-metrics/compare/v2.0.1...v2.1.0

v2.0.1

What's Changed

Performance

  • Command Caching: Added static caching to ProcessRunner::commandExists to eliminate redundant shell execution checks (~1-5ms savings per call)
  • Parsing Optimization: Replaced regex splitting with explode in LinuxProcStatParser and LinuxProcPidStatParser for reduced CPU overhead

Documentation

  • Link Fixes: Fixed internal documentation links to include .md extension for correct navigation on Cbox.dk and GitHub
  • Rebranding: Updated documentation URLs and references from PHPeek to Cbox

Full Changelog: https://github.com/cboxdk/system-metrics/compare/v2.0.0...v2.0.1

v2.0.0

Breaking Changes

  • Namespace Changed: PHPeek\SystemMetrics → Cbox\SystemMetrics
  • Package Renamed: gophpeek/system-metrics → cboxdk/system-metrics

Migration Guide

Update your composer.json:

composer remove gophpeek/system-metrics
composer require cboxdk/system-metrics

Update your imports:

// Before
use PHPeek\SystemMetrics\SystemMetrics;

// After
use Cbox\SystemMetrics\SystemMetrics;

Full Changelog: https://github.com/cboxdk/system-metrics/compare/v1.6.0...v2.0.0

v1.6.0

What's Changed

New Features

  • PHP 8.5 Support: Added PHP 8.5 to CI test matrix for early compatibility testing

Security Improvements

  • FileReader Windows Whitelist: Added Windows-specific path patterns to security whitelist
  • ProcessRunner Hardening: Improved command handling across platforms

Bug Fixes

  • Fixed PHPStan configuration issues
  • Fixed cross-platform test compatibility (Windows/macOS/Linux)
  • Fixed risky tests that didn't make assertions on Windows

Testing

  • All 660+ tests pass across PHP 8.3, 8.4, and 8.5
  • Full CI coverage on Ubuntu, macOS, and Windows
  • E2E tests in Docker containers

Full Changelog: https://github.com/cboxdk/system-metrics/compare/v1.5.0...v1.6.0

v1.5.0

What's Changed

Full Changelog: https://github.com/cboxdk/system-metrics/compare/v1.4.0...v1.5.0

v1.4.0

What's Changed

Full Changelog: https://github.com/cboxdk/system-metrics/compare/v1.3.0...v1.4.0

v1.2.0
v1.1.0

What's Changed

Full Changelog: https://github.com/cboxdk/system-metrics/compare/v1.0.0...v1.1.0

v1.0.0

What's Changed

New Contributors

Full Changelog: https://github.com/cboxdk/system-metrics/compare/v0.1.0...v1.0.0

0.1.0

Added

  • CPU Usage Percentage: Calculate CPU usage percentage over time intervals

    • SystemMetrics::cpuUsage(float $intervalSeconds = 1.0) facade method for automatic measurement

    • CpuSnapshot::calculateDelta(CpuSnapshot $before, CpuSnapshot $after) for manual two-snapshot calculation

    • CpuDelta DTO with comprehensive percentage calculations:

      • usagePercentage() - Total system load (0-100%, normalized)
      • usagePercentagePerCore() - Per-core average usage (0-100%)
      • userPercentage() - User-mode CPU time percentage
      • systemPercentage() - System-mode (kernel) CPU time percentage
      • idlePercentage() - Idle time percentage
      • iowaitPercentage() - I/O wait time percentage
      • coreUsagePercentage(int $coreIndex) - Usage for specific core
      • busiestCore() - Get busiest core during interval
      • idlestCore() - Get least busy core during interval
    • CpuCoreDelta DTO for per-core delta calculations

    • ⚠️ Important: CPU percentage requires TWO snapshots with time elapsed between them

    • Convenience method blocks execution; manual method allows non-blocking patterns

    • 15 comprehensive unit tests for CPU delta calculations

  • System Uptime Metrics: Track system uptime since last boot

    • SystemMetrics::uptime() facade method
    • UptimeSnapshot DTO with boot time, total seconds, and timestamp
    • Helper methods: days(), hours(), minutes(), totalHours(), totalMinutes(), humanReadable()
    • Linux support via /proc/uptime parsing
    • macOS support via sysctl kern.boottime
    • LinuxProcUptimeParser and MacOsSysctlBoottimeParser
    • LinuxProcUptimeSource, MacOsSysctlUptimeSource, CompositeUptimeSource
    • ReadUptimeAction for uptime retrieval
    • 13 comprehensive unit tests for uptime
  • DX Finder Methods: Developer experience enhancements for targeted metric access

    • CpuSnapshot Finders: Find specific CPU cores with smart filtering

      • findCore(int $coreIndex) - Find specific core by index
      • findBusyCores(float $threshold) - Find cores above busy threshold
      • findIdleCores(float $threshold) - Find cores above idle threshold
      • busiestCore() - Get core with highest busy percentage
      • idlestCore() - Get core with lowest busy percentage
    • StorageSnapshot Finders: Find specific mount points and filesystem types

      • findMountPoint(string $path) - Find mount containing path (most specific match)
      • findDevice(string $device) - Find mount by device name
      • findByFilesystemType(FileSystemType $type) - Find all mounts by filesystem type
    • NetworkSnapshot Finders: Find specific network interfaces with filtering

      • findInterface(string $name) - Find interface by exact name
      • findByType(NetworkInterfaceType $type) - Find interfaces by type
      • findActiveInterfaces() - Find all interfaces that are up
      • findByMacAddress(string $mac) - Find interface by MAC address
    • 46 comprehensive unit tests for all finder methods

  • Unified Limits API: Single source for resource limits regardless of environment

    • SystemMetrics::limits() facade method for unified limits and current usage

    • SystemLimits DTO with complete resource limits and current consumption

    • LimitSource enum: HOST (bare metal/VM), CGROUP_V1, CGROUP_V2

    • Scaling Decision Helpers:

      • availableCpuCores() - Calculate available CPU cores for scaling
      • availableMemoryBytes() - Calculate available memory for scaling
      • canScaleCpu(int $additionalCores) - Check if can scale CPU by amount
      • canScaleMemory(int $additionalBytes) - Check if can scale memory by amount
    • Utilization Helpers:

      • cpuUtilization() - CPU usage as percentage (0-100+)
      • memoryUtilization() - Memory usage as percentage (0-100+)
      • swapUtilization() - Swap usage as percentage (null if no swap)
    • Headroom Helpers:

      • cpuHeadroom() - CPU headroom percentage (100 - utilization)
      • memoryHeadroom() - Memory headroom percentage (100 - utilization)
    • Pressure Detection:

      • isMemoryPressure(float $threshold = 80.0) - Detect memory pressure
      • isCpuPressure(float $threshold = 80.0) - Detect CPU pressure
    • Environment Detection:

      • isContainerized() - Check if running in container (cgroup v1/v2)
    • CompositeSystemLimitsSource with intelligent decision logic:

      • Checks if running in container with cgroup limits first
      • Uses cgroup limits if available (container-aware)
      • Falls back to host limits (bare metal/VM)
      • Integrates with ContainerMetricsSource, CpuMetricsSource, MemoryMetricsSource
    • ReadSystemLimitsAction for limits retrieval

    • 25 comprehensive unit tests for SystemLimits

Changed

  • Updated README with System Uptime section including examples and use cases
  • Updated README with DX Finder Methods section showing targeted metric access
  • Updated README with Unified Limits API section including vertical scaling examples

Technical Details

  • PHPStan Level 9 compliance maintained (0 errors)

  • Human-readable uptime format: "5 days, 3 hours, 42 minutes"

  • Proper singular/plural forms ("1 day" vs "2 days")

  • Finder methods use smart filtering and sorting for optimal results

  • Most specific mount point matching for nested paths

  • Busy/idle percentage calculations based on CPU time ratios

  • Unified limits provide current usage alongside limits for safe scaling decisions

  • Container-aware: respects cgroup limits, not host resources when containerized

  • Graceful handling of over-provisioned scenarios (usage > limits)

  • Zero headroom when at or over capacity

  • Immutable readonly DTOs throughout

  • Railway-oriented programming with Result pattern

  • 618 total tests, 1514 assertions (15 new CPU delta tests)

  • Container Metrics (Cgroups): Full Docker/Kubernetes resource monitoring

    • SystemMetrics::container() facade method for container metrics
    • ContainerLimits: Complete container resource limits and usage
    • CgroupVersion enum: V1, V2, NONE
    • Cgroup v1 support: CPU quota (cpu.cfs_quota_us), memory limits (memory.limit_in_bytes)
    • Cgroup v2 support: CPU quota (cpu.max), memory limits (memory.max)
    • CPU usage tracking with delta calculations for accurate utilization
    • Memory usage tracking (memory.current, memory.usage_in_bytes)
    • CPU throttling detection (nr_throttled counter)
    • OOM kill tracking (oom_kill, under_oom counters)
    • Helper methods: hasCpuLimit(), hasMemoryLimit(), cpuUtilizationPercentage(), memoryUtilizationPercentage()
    • Helper methods: availableCpuCores(), availableMemoryBytes(), isCpuThrottled(), hasOomKills()
    • CgroupParser: Parse cgroup v1 and v2 files from /sys/fs/cgroup and /proc/self/cgroup
    • LinuxCgroupMetricsSource: Linux cgroup metrics source
    • CompositeContainerMetricsSource: Auto-detection with graceful fallback
    • ReadContainerMetricsAction: Action for container metrics retrieval
    • ContainerMetricsSource contract interface
  • Storage Metrics: Complete filesystem and disk I/O monitoring system

    • SystemMetrics::storage() facade method for storage metrics
    • StorageSnapshot: Complete storage state with filesystem and I/O data
    • MountPoint: Filesystem mount information with usage statistics
    • DiskIOStats: Disk I/O counters (reads, writes, bytes, I/O time)
    • Helper methods: usedPercentage(), availablePercentage(), totalBytes()
    • FileSystemType enum: ext4, xfs, btrfs, zfs, apfs, hfs+, ntfs, fat32, tmpfs, devtmpfs
    • Linux support via /proc/mounts and /proc/diskstats parsing
    • macOS support via df and iostat commands
    • Composite source with automatic platform detection
    • ReadStorageMetricsAction for storage retrieval
    • Parsers: LinuxMountsParser, LinuxDiskstatsParser, MacOsDfParser, MacOsIostatParser
    • Sources: LinuxProcStorageMetricsSource, MacOsDfStorageMetricsSource, CompositeStorageMetricsSource
    • StorageMetricsSource contract interface
  • Network Metrics: Complete network interface and connection monitoring system

    • SystemMetrics::network() facade method for network metrics
    • NetworkSnapshot: Complete network state with interfaces and connections
    • NetworkInterface: Interface statistics and configuration
    • NetworkInterfaceStats: Detailed traffic counters (bytes, packets, errors, drops)
    • NetworkConnectionStats: TCP/UDP connection state counters
    • Helper methods: totalBytes(), totalPackets(), totalErrors(), totalDrops()
    • NetworkInterfaceType enum: ethernet, wifi, loopback, bridge, vlan, vpn, cellular, bluetooth, other
    • Linux support via /proc/net/dev and /proc/net/tcp|udp parsing
    • macOS support via netstat commands
    • Composite source with automatic platform detection
    • ReadNetworkMetricsAction for network retrieval
    • Parsers: LinuxProcNetDevParser, LinuxProcNetTcpParser, MacOsNetstatParser, MacOsNetstatInterfaceParser
    • Sources: LinuxProcNetworkMetricsSource, MacOsNetstatNetworkMetricsSource, CompositeNetworkMetricsSource
    • NetworkMetricsSource contract interface
  • Load Average Metrics: System load average support without requiring delta calculations

    • SystemMetrics::loadAverage() facade method for instant load metrics
    • LoadAverageSnapshot: Raw load average values (1, 5, 15 minute intervals)
    • NormalizedLoadAverage: Load normalized by core count with percentage helpers
    • Helper methods: oneMinutePercentage(), fiveMinutesPercentage(), fifteenMinutesPercentage()
    • normalized(CpuSnapshot) method for capacity percentage calculation
    • Linux support via /proc/loadavg parsing
    • macOS support via sysctl vm.loadavg command
    • Composite source with automatic platform detection
    • ReadLoadAverageAction for load average retrieval
    • LinuxProcLoadavgParser and MacOsSysctlLoadavgParser
    • LinuxProcLoadAverageSource, MacOsSysctlLoadAverageSource, CompositeLoadAverageSource
    • LoadAverageSource contract interface
  • Process-Level Monitoring: Complete process resource tracking system

    • ProcessMetrics facade for stateful tracking with start/sample/stop workflow
    • ProcessTracker class for object-oriented process monitoring
    • Support for tracking individual processes and process groups (parent + children)
    • Statistical aggregation: current, peak, and average resource usage
    • Manual sampling support for detailed statistics
    • ProcessSnapshot: Point-in-time process metrics (PID, PPID, CPU, memory, threads)
    • ProcessDelta: Delta calculations with CPU usage percentage
    • ProcessStats: Statistical aggregation with sample count and duration
    • ProcessGroupSnapshot: Process group metrics with aggregation methods
    • Linux support via /proc/{pid}/stat parsing
    • macOS support via ps and pgrep commands
    • Composite source with automatic platform detection
    • Actions: ReadProcessMetricsAction, ReadProcessGroupMetricsAction
  • Environment Detection: Comprehensive system environment information

    • Virtualization detection (KVM, QEMU, VMware, Hyper-V, VirtualBox, Parallels, etc.)
    • Containerization detection (Docker, Kubernetes, containerd, cri-o, Podman, LXC)
    • Cgroup v1 and v2 detection with paths
  • CPU Metrics: Raw time counters with per-core support

    • Total and per-core CPU times (user, nice, system, idle, iowait, irq, softirq, steal)
    • Helper methods: total(), busy(), coreCount()
  • Memory Metrics: Complete memory and swap information

    • Total, free, available, used, buffers, and cached memory
    • Swap memory metrics (total, free, used)
    • Helper methods: usedPercentage(), availablePercentage()

Changed

  • Updated README with comprehensive examples and use cases
  • Added documentation for all metric types

Technical Details

  • PHP 8.3+ requirement for modern readonly class support
  • PHPStan Level 9 compliance (0 errors)
  • Pure PHP implementation with no external dependencies
  • Strict types throughout (declare(strict_types=1))
  • Result pattern for explicit error handling without exceptions
  • Immutable DTOs using readonly classes
  • Action pattern for well-defined use cases
  • Interface-driven architecture for swappable implementations
  • Composite sources with graceful fallback mechanism
  • PSR-4 autoloading
  • Laravel Pint for code style enforcement
  • Pest v4 for testing framework
  • 618 tests with 1514 assertions (100% pass rate)

Platform Support

  • Linux: Full support via /proc and /sys filesystems
  • macOS: Full support via sysctl, vm_stat, ps, netstat, df, iostat
  • Windows: Not supported (will return appropriate errors)

Known Limitations

  • Modern macOS (especially Apple Silicon) may return zero values for CPU metrics due to deprecated kern.cp_time sysctl
  • macOS swap metrics are best-effort due to dynamic swap management
  • Container environments may have restricted access to certain metrics
  • CPU usage percentage requires delta calculations (two snapshots)
Weaver

How can I help you explore Laravel packages today?

Conversation history is not saved when not logged in.
Prompt
Add packages to context
No packages found.
gmostafa/php-graphql-client
xeviant/paystack
snowsoft/faker
meditationsteps/blogetc
animalyoung/laravel-influxdb
onix-solutions/sms-telera
lonely-lights/prosetta
oxygen/data
oxygen/core
jengo/base
xiloryx/log-collector
a21ns1g4ts/filament-stripe
la-php/laravel-admin
artisan-build/community-prompts
vleroy/smart
ayles-software/laravel-australian-public-holidays
cboxdk/laravel-id-spatie
cboxdk/laravel-id-billing
cboxdk/laravel-id-billing-bridge
simple-as-fuck/php-performance-log