diff --git a/cli/src/Service/SystemInfo.php b/cli/src/Service/SystemInfo.php new file mode 100644 index 0000000..02cfb78 --- /dev/null +++ b/cli/src/Service/SystemInfo.php @@ -0,0 +1,85 @@ + [ + 'usage' => $this->getMemoryUsage(), + 'peak' => $this->getPeakMemoryUsage() + ], + 'cpu' => [ + 'usage' => $this->getCpuUsage(), + 'last_15minutes' => $this->getCpuUsageLast15minutes(), + 'cores' => $this->getCpuCores() + ] + ]; + } + public function get(string $name): int|null|float + { + return match ($name) { + 'memory' => $this->getMemoryUsage(), + 'peak_memory' => $this->getPeakMemoryUsage(), + 'cpu' => $this->getCpuUsage(), + 'cpu_last_15minutes' => $this->getCpuUsageLast15minutes(), + 'cpu_cores' => $this->getCpuCores(), + default => null + }; + } + public function getMemoryUsage(): float + { + return memory_get_usage(true); + } + public function getPeakMemoryUsage(): float + { + return memory_get_peak_usage(true); + } + public function getCpuUsage(): float + { + return $this->getCpuLoad()[0]; + } + public function getCpuUsageLast15minutes(): float + { + return $this->getCpuLoad()[1]; + } + + protected array $cpuLoad; + protected function getCpuLoad(): array + { + if (isset($this->cpuLoad)) { + $load = sys_getloadavg(); + $cores = $this->getCpuCores(); + array_walk($load, function (&$value) use ($cores) { + $value = $value / $cores; + }); + $this->cpuLoad = $load; + unset($load); + } + return $this->cpuLoad; + } + protected function getCpuCores(): int + { + $cpu_cores = 1; + if (is_file('/proc/cpuinfo')) { + $cpuinfo = file('/proc/cpuinfo'); + preg_match_all('/^processor/m', $cpuinfo, $matches); + $cpu_cores = count($matches[0]); + } + return $cpu_cores; + } + public function formatMemoryUsage(float $usage, string $unit = 'MB'): string + { + $sizeFactor = match ($unit) { + 'MB' => 1024 * 1024, + 'GB' => 1024 * 1024 * 1024, + default => 1 + }; + return number_format($usage / $sizeFactor, 2) . " {$unit}"; + } + public function formatCpuLoad(float $load): string + { + return number_format($load * 100, 2) . '%'; + } +} \ No newline at end of file