Files
data-collection-terminal/management-panel/app/Filament/Widgets/NetworkMonitor.php
2024-09-12 09:43:19 +08:00

137 lines
4.2 KiB
PHP

<?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 getFilters(): array
{
return [
'upload' => '上传流量',
'download' => '下载流量',
];
}
protected function getData(): array
{
$prometheus = new PrometheusService();
// 根据用户选择的过滤器决定查询的流量类型
$selectedFilter = $this->filter ?? 'upload';
$labels = [];
$uploadData = [];
$downloadData = [];
if ($selectedFilter === 'upload') {
// 查询过去 1 分钟内每秒的上传流量
$uploadQuery = 'rate(node_network_transmit_bytes_total[1m])';
$uploadResult = $prometheus->queryRange(
$uploadQuery,
now()->subMinutes(1)->timestamp,
now()->timestamp,
'5s' // 每秒一个数据点
);
if (!empty($uploadResult['data']['result'][0]['values'])) {
$uploadValues = array_column($uploadResult['data']['result'][0]['values'], 1, 0);
// 获取最新的数据点
$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
}
}
}
if ($selectedFilter === 'download') {
// 查询过去 1 分钟内每秒的下载流量
$downloadQuery = 'rate(node_network_receive_bytes_total[1m])';
$downloadResult = $prometheus->queryRange(
$downloadQuery,
now()->subMinutes(1)->timestamp,
now()->timestamp,
'5s' // 每秒一个数据点
);
if (!empty($downloadResult['data']['result'][0]['values'])) {
$downloadValues = array_column($downloadResult['data']['result'][0]['values'], 1, 0);
// 获取最新的数据点
$timestamps = array_keys($downloadValues);
$timestamps = array_slice($timestamps, -self::MAX_POINTS);
foreach ($timestamps as $timestamp) {
$labels[] = date('H:i:s', $timestamp); // 格式化时间戳为小时:分钟:秒
$downloadData[] = round(floatval($downloadValues[$timestamp]) / (1024 * 1024), 2); // 转换为 MB/s
}
}
}
// 处理显示的数据集
$datasets = [];
if ($selectedFilter === 'upload') {
$datasets[] = [
'label' => '上传流量 (MB/s)',
'data' => $uploadData,
'borderColor' => 'rgba(255, 99, 132, 0.6)',
'backgroundColor' => 'rgba(255, 99, 132, 0.2)',
'fill' => false,
];
}
if ($selectedFilter === 'download') {
$datasets[] = [
'label' => '下载流量 (MB/s)',
'data' => $downloadData,
'borderColor' => 'rgba(54, 162, 235, 0.6)',
'backgroundColor' => 'rgba(54, 162, 235, 0.2)',
'fill' => false,
];
}
return [
'labels' => $labels,
'datasets' => $datasets,
];
}
protected function getType(): string
{
return 'line'; // 设置为折线图
}
protected function getOptions(): array
{
return [
'scales' => [
'y' => [
'beginAtZero' => true,
'min' => 0, // 设置 y 轴最小值
],
],
];
}
protected function getPollingInterval(): ?string
{
return '5s'; // 每秒更新一次
}
}