[增添]添加了CPU占用率饼图

This commit is contained in:
makotocc0107
2024-08-29 14:35:40 +08:00
committed by Coding
parent 9862f9eb53
commit a3566a1449
3 changed files with 87 additions and 18 deletions

View File

@@ -0,0 +1,59 @@
<?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' => ['#FBD1B7', '#E0F5B9'], // 柔和颜色
'borderColor' => ['#FBD1B7', '#E0F5B9'], // 边框颜色
'borderWidth' => 1, // 边框宽度
],
],
];
}
protected function getType(): string
{
return 'pie'; // 设置为饼图
}
protected function getPollingInterval(): ?string
{
return '1s'; // 每秒更新一次
}
}

View File

@@ -56,7 +56,7 @@ class SystemStats extends BaseWidget
return $item['value'][1] ?? 0;
}, $networkReceiveResult['data']['result'])) / (1024 * 1024), 2);
$networkDisplay = ": {$networkTransmit} MB/s\n: {$networkReceive} MB/s";
$networkDisplay = ": {$networkTransmit} MB/s\n: {$networkReceive} MB/s";
return [
BaseWidget\Stat::make('内存占用', $memoryDisplay),