[增添]增添了网络流量监控的widget组件

This commit is contained in:
makotocc0107
2024-08-30 14:26:12 +08:00
committed by Coding
parent a70f667e9e
commit 2bfbd6d956
2 changed files with 119 additions and 5 deletions

View File

@@ -0,0 +1,105 @@
<?php
namespace App\Filament\Widgets;
use App\Services\PrometheusService;
use Filament\Widgets\ChartWidget;
class NetworkMonitor extends ChartWidget
{
protected static ?string $heading = '网络流量监控';
protected static ?int $sort = 5;
// 固定显示的数据点数
private const MAX_POINTS = 6;
protected function getData(): array
{
$prometheus = new PrometheusService();
// 查询过去 1 分钟内每秒的上传流量
$uploadQuery = 'rate(node_network_transmit_bytes_total[1m])';
$uploadResult = $prometheus->queryRange(
$uploadQuery,
now()->subMinutes(1)->timestamp,
now()->timestamp,
'5s' // 每秒一个数据点
);
// 查询过去 1 分钟内每秒的下载流量
$downloadQuery = 'rate(node_network_receive_bytes_total[1m])';
$downloadResult = $prometheus->queryRange(
$downloadQuery,
now()->subMinutes(1)->timestamp,
now()->timestamp,
'5s' // 每秒一个数据点
);
$labels = [];
$uploadData = [];
$downloadData = [];
if (!empty($uploadResult['data']['result'][0]['values']) && !empty($downloadResult['data']['result'][0]['values'])) {
date_default_timezone_set('Asia/Shanghai');
$uploadValues = array_column($uploadResult['data']['result'][0]['values'], 1, 0);
$downloadValues = array_column($downloadResult['data']['result'][0]['values'], 1, 0);
// 获取最新的数据点
$latestTimestamp = max(array_keys($uploadValues));
// 只保留最新的 MAX_POINTS 个数据点
$timestamps = array_keys($uploadValues);
$timestamps = array_slice($timestamps, -self::MAX_POINTS);
foreach ($timestamps as $timestamp) {
$labels[] = date('H:i:s', $timestamp); // 格式化时间戳为小时:分钟:秒
$uploadData[] = round(floatval($uploadValues[$timestamp]) / (1024 * 1024), 2); // 转换为 MB/s
$downloadData[] = round(floatval($downloadValues[$timestamp]) / (1024 * 1024), 2); // 转换为 MB/s
}
}
return [
'labels' => $labels,
'datasets' => [
[
'label' => '上传流量 (MB/s)',
'data' => $uploadData,
'borderColor' => 'rgba(255, 99, 132, 0.6)',
'backgroundColor' => 'rgba(255, 99, 132, 0.2)',
'fill' => false,
],
[
'label' => '下载流量 (MB/s)',
'data' => $downloadData,
'borderColor' => 'rgba(54, 162, 235, 0.6)',
'backgroundColor' => 'rgba(54, 162, 235, 0.2)',
'fill' => false,
],
],
];
}
protected function getType(): string
{
return 'line'; // 设置为折线图
}
protected function getOptions(): array
{
return [
'scales' => [
'y' => [
'beginAtZero' => true,
'min' => 0, // 设置 y 轴最小值
],
],
];
}
protected function getPollingInterval(): ?string
{
return '5s'; // 每秒更新一次
}
}