Files
data-collection-terminal/management-panel/app/Livewire/MetricWidgetChart.php
2024-09-09 14:40:59 +08:00

70 lines
2.1 KiB
PHP

<?php
namespace App\Livewire;
use App\Services\PrometheusService;
use Filament\Support\RawJs;
use LaraZeus\InlineChart\InlineChartWidget;
use phpDocumentor\Reflection\Types\Null_;
class MetricWidgetChart extends InlineChartWidget
{
private const MAX_POINTS = 24;
protected static ?string $maxHeight = '65px';
// public int $maxWidth = 1000;
protected function getData(): array
{
$prometheus = new PrometheusService();
date_default_timezone_set('Asia/Shanghai');
$query1 = $this->record->name . '{data="real"}';
$start = now()->now()->subMinutes(2)->timestamp;
$end = now()->timestamp;
$step = 5;
$realdata = $prometheus->queryRange($query1, $start, $end, $step);
// 检查查询结果是否有数据
if (empty($realdata['data']['result'])) {
// 如果没有数据,返回一个空数据集或提示信息
return [
'labels' => [],
'datasets' => [],
];
}
if (!empty($realdata['data']['result'][0]['values'][1])) {
// 获取内存使用率数据
$realdataValue = array_column($realdata['data']['result'][0]['values'], 1, 0);
// 只保留最新的 MAX_POINTS 个数据点
$timestamps = array_keys($realdataValue);
$timestamps = array_slice($timestamps, -self::MAX_POINTS);
foreach ($timestamps as $timestamp) {
$labels[] = date('H:i:s', $timestamp); // 格式化时间戳为小时:分钟:秒
$data[] = round(floatval($realdataValue[$timestamp]), 2); // 取出每个时间点的内存使用率,并保留两位小数
}
}
return [
'labels' => $labels,
'datasets' => [
[
'label' => $this->record->name,
'data' => $data,
'borderColor' => '#4CAF50',
'backgroundColor' => 'rgba(76, 175, 80, 0.2)',
'fill' => true,
'tension' => 0.2,
],
],
];
}
}