60 lines
1.6 KiB
PHP
60 lines
1.6 KiB
PHP
<?php
|
|
|
|
namespace App\Filament\Widgets;
|
|
|
|
use App\Services\PrometheusService;
|
|
use Filament\Widgets\ChartWidget;
|
|
|
|
class CPUStatus extends ChartWidget
|
|
{
|
|
protected static ?string $heading = 'CPU 占用率';
|
|
|
|
protected static ?int $sort = 5;
|
|
|
|
protected int | string | array $columnSpan = '1';
|
|
|
|
protected function getData(): array
|
|
{
|
|
$prometheus = new PrometheusService();
|
|
|
|
// 查询 CPU 使用率数据,获取最近 60 秒内的平均值
|
|
$query = '100 - (avg by(instance) (rate(node_cpu_seconds_total{mode="idle"}[60s])) * 100)';
|
|
$cpuUsageResult = $prometheus->query($query);
|
|
|
|
// 计算使用率和空闲率
|
|
$cpuUsage = 0;
|
|
if (isset($cpuUsageResult['data']['result'][0]['value'][1])) {
|
|
$cpuUsage = floatval($cpuUsageResult['data']['result'][0]['value'][1]);
|
|
}
|
|
$cpuIdle = 100 - $cpuUsage;
|
|
|
|
$data = [
|
|
round($cpuUsage, 2),
|
|
round($cpuIdle, 2),
|
|
];
|
|
|
|
return [
|
|
'labels' => ['CPU 使用率', 'CPU 空闲率'],
|
|
'datasets' => [
|
|
[
|
|
'label' => 'CPU 占用情况',
|
|
'data' => $data,
|
|
'backgroundColor' => ['#FF8080', '#E0F5B9'], // 柔和颜色
|
|
'borderColor' => ['#FF8080', '#E0F5B9'], // 边框颜色
|
|
'borderWidth' => 1, // 边框宽度
|
|
],
|
|
],
|
|
];
|
|
}
|
|
|
|
protected function getType(): string
|
|
{
|
|
return 'pie'; // 设置为饼图
|
|
}
|
|
|
|
protected function getPollingInterval(): ?string
|
|
{
|
|
return '1s'; // 每秒更新一次
|
|
}
|
|
}
|