85 lines
2.4 KiB
PHP
85 lines
2.4 KiB
PHP
<?php
|
|
|
|
namespace App\Filament\Widgets;
|
|
|
|
use App\Services\PrometheusService;
|
|
use Filament\Widgets\ChartWidget;
|
|
|
|
class PrometheusMemory extends ChartWidget
|
|
{
|
|
protected static ?int $sort = 4;
|
|
|
|
protected static ?string $heading = '内存占用率';
|
|
|
|
// 固定显示的数据点数
|
|
private const MAX_POINTS = 6;
|
|
|
|
protected function getData(): array
|
|
{
|
|
$prometheus = new PrometheusService();
|
|
|
|
// 查询过去 1 分钟内的每 6 秒一个数据点
|
|
$memoryUsageRange = $prometheus->queryRange(
|
|
'(1 - (avg_over_time(node_memory_MemAvailable_bytes[1m]) / avg_over_time(node_memory_MemTotal_bytes[1m]))) * 100',
|
|
now()->subMinutes(1)->timestamp,
|
|
now()->timestamp,
|
|
6 // 每6秒一个数据点
|
|
);
|
|
|
|
$labels = [];
|
|
$data = [];
|
|
|
|
if (!empty($memoryUsageRange['data']['result'][0]['values'])) {
|
|
|
|
// 获取内存使用率数据
|
|
$memoryValues = array_column($memoryUsageRange['data']['result'][0]['values'], 1, 0);
|
|
|
|
// 只保留最新的 MAX_POINTS 个数据点
|
|
$timestamps = array_keys($memoryValues);
|
|
$timestamps = array_slice($timestamps, -self::MAX_POINTS);
|
|
|
|
foreach ($timestamps as $timestamp) {
|
|
$labels[] = date('H:i:s', $timestamp); // 格式化时间戳为小时:分钟:秒
|
|
$data[] = round(floatval($memoryValues[$timestamp]), 2); // 取出每个时间点的内存使用率,并保留两位小数
|
|
}
|
|
}
|
|
|
|
return [
|
|
'labels' => $labels,
|
|
'datasets' => [
|
|
[
|
|
'label' => '内存占用率 (%)',
|
|
'data' => $data,
|
|
'borderColor' => '#4CAF50',
|
|
'backgroundColor' => 'rgba(76, 175, 80, 0.2)',
|
|
'fill' => true,
|
|
'tension' => 0.2,
|
|
],
|
|
],
|
|
];
|
|
}
|
|
|
|
protected function getType(): string
|
|
{
|
|
return 'line';
|
|
}
|
|
|
|
protected function getOptions(): array
|
|
{
|
|
return [
|
|
'scales' => [
|
|
'y' => [
|
|
'beginAtZero' => true,
|
|
'min' => 0, // 设置 y 轴最小值
|
|
'max' => 100, // 设置 y 轴最大值
|
|
],
|
|
],
|
|
];
|
|
}
|
|
|
|
protected function getPollingInterval(): ?string
|
|
{
|
|
return '6s'; // 每 6 秒更新一次
|
|
}
|
|
}
|