System info
This commit is contained in:
85
cli/src/Service/SystemInfo.php
Normal file
85
cli/src/Service/SystemInfo.php
Normal file
@ -0,0 +1,85 @@
|
||||
<?php
|
||||
namespace Incoviba\Service;
|
||||
|
||||
class SystemInfo
|
||||
{
|
||||
public function getAllInfo(): array
|
||||
{
|
||||
return [
|
||||
'memory' => [
|
||||
'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) . '%';
|
||||
}
|
||||
}
|
Reference in New Issue
Block a user