From 2db23a6dffe434d41dc77953893e50c5c0634ac7 Mon Sep 17 00:00:00 2001 From: makotocc0107 <1424018999@qq.com> Date: Fri, 30 Aug 2024 15:15:22 +0800 Subject: [PATCH] =?UTF-8?q?[=E5=A2=9E=E6=B7=BB]=E5=A2=9E=E5=8A=A0=E4=BA=86?= =?UTF-8?q?=E7=9B=91=E6=B5=8B=E8=B4=9F=E8=BD=BD=E7=9A=84widget?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../app/Filament/Widgets/LoadWidget.php | 121 ++++++++++++++++++ 1 file changed, 121 insertions(+) create mode 100644 management-panel/app/Filament/Widgets/LoadWidget.php diff --git a/management-panel/app/Filament/Widgets/LoadWidget.php b/management-panel/app/Filament/Widgets/LoadWidget.php new file mode 100644 index 0000000..20013ae --- /dev/null +++ b/management-panel/app/Filament/Widgets/LoadWidget.php @@ -0,0 +1,121 @@ + '1 分钟平均负载', + 'load5' => '5 分钟平均负载', + 'load15' => '15 分钟平均负载', + ]; + } + + protected function getData(): array + { + $prometheus = new PrometheusService(); + + // 根据用户选择的过滤器决定查询的指标和时间范围 + $selectedLoad = $this->filter ?? 'load1'; + switch ($selectedLoad) { + case 'load5': + $query = 'node_load5'; + $range = now()->subMinutes(5)->timestamp; + $step = '60s'; // 每分钟更新一次 + break; + case 'load15': + $query = 'node_load15'; + $range = now()->subMinutes(15)->timestamp; + $step = '300s'; // 每5分钟更新一次 + break; + case 'load1': + default: + $query = 'node_load1'; + $range = now()->subMinutes(1)->timestamp; + $step = '15s'; // 每15秒更新一次 + break; + } + + // 查询对应时间范围内的数据 + $loadResult = $prometheus->queryRange( + $query, + $range, + now()->timestamp, + $step + ); + + $labels = []; + $data = []; + + if (!empty($loadResult['data']['result'][0]['values'])) { + $loadValues = array_column($loadResult['data']['result'][0]['values'], 1, 0); + + // 获取最新的数据点 + $timestamps = array_keys($loadValues); + $timestamps = array_slice($timestamps, -self::MAX_POINTS); + + foreach ($timestamps as $timestamp) { + $labels[] = date('H:i:s', $timestamp); // 格式化时间戳为小时:分钟:秒 + $data[] = round(floatval($loadValues[$timestamp]), 2); // 保留两位小数 + } + } + + return [ + 'labels' => $labels, + 'datasets' => [ + [ + 'label' => $this->getFilters()[$selectedLoad], + 'data' => $data, + 'borderColor' => 'rgba(75, 192, 192, 0.6)', + 'backgroundColor' => 'rgba(75, 192, 192, 0.2)', + 'fill' => true, + ], + ], + ]; + } + + protected function getType(): string + { + return 'line'; // 设置为折线图 + } + + protected function getOptions(): array + { + return [ + 'scales' => [ + 'y' => [ + 'beginAtZero' => true, + 'min' => 0, // 设置 y 轴最小值 + ], + ], + ]; + } + + protected function getPollingInterval(): ?string + { + // 根据选中的负载类型设置不同的更新间隔 + $selectedLoad = $this->filter ?? 'load1'; + switch ($selectedLoad) { + case 'load5': + return '60s'; // 每分钟更新一次 + case 'load15': + return '300s'; // 每5分钟更新一次 + case 'load1': + default: + return '15s'; // 每15秒更新一次 + } + } +}