feat(alert-center): 添加飞书Webhook通知渠道 + 告警引擎实时通知

- 后端: NotifyChannel 模型新增 feishu 类型, FeishuWebhookConfig
- 后端: TestNotifyChannel 真实发送飞书测试消息(文本格式)
- 后端: 告警引擎触发/恢复时自动发送飞书通知(sendFeishuAlert/sendFeishuRecovery)
- 后端: AlertEngine 新增 tcp_time_wait/tcp_close_wait/service_process 指标检测
- 后端: NetworkStatModel 新增 TCPCloseWait 字段
- 后端: QuickSetupRules 一键创建6条告警规则(CPU/内存/磁盘/TIME_WAIT/CLOSE_WAIT/进程)
- 后端: 注册 /alerts/quick-setup 路由
- 前端: AlertChannelDialog 新增飞书类型选项
- 前端: helpers 新增 getChannelIcon/getChannelTypeLabel 支持 feishu/dingtalk/wechat
This commit is contained in:
attacker committed 2026-06-24 08:34:43 +00:00
1 parent 7bc5169e8f
commit 5333f6f04a
30 files changed
+2406 -1001

No files matched your search

+178 -188
View File
@@ -1,4 +1,5 @@
// 主机监控详情 — 阿里云云监控风格 (Brush缩放 + avg/max/min选择器)
// 主机监控详情 — 阿里云云监控风格 + v2.0 新增指标
// 进程TOP / Swap / FD / 上下文切换
import { useState, useEffect, useCallback, useMemo } from 'react';
import { useSearchParams } from 'react-router-dom';
import { agentApi } from '@/services/api';
@@ -9,14 +10,14 @@ import { Badge } from '@/components/ui/badge';
import { Button } from '@/components/ui/button';
import {
Cpu, HardDrive, Network, Activity, Server, Loader2,
Info, Monitor, Disc, Zap, Clock
Info, Monitor, Disc, Zap, Clock, List, AlertTriangle,
} from 'lucide-react';
import {
AreaChart, Area, XAxis, YAxis, CartesianGrid, Tooltip,
ResponsiveContainer, Brush, ReferenceLine,
ResponsiveContainer, Brush,
} from 'recharts';
// 时间范围 → 聚合窗口 → 目标桶数
// 时间范围配置
const TIME_RANGES = [
{ label: '1小时', hours: 1, window: 60, buckets: 60 },
{ label: '6小时', hours: 6, window: 300, buckets: 72 },
@@ -30,15 +31,10 @@ const TIME_RANGES = [
type AggType = 'avg' | 'max' | 'min';
interface BucketPoint {
time: string;
timestamp: number;
avg: number;
max: number;
min: number;
count: number;
time: string; timestamp: number; avg: number; max: number; min: number; count: number;
}
function bucketWithStats(raw: number[], timestamps: number[], windowSec: number, targetBuckets: number): BucketPoint[] {
function bucketWithStats(raw: number[], timestamps: number[], targetBuckets: number): BucketPoint[] {
if (!raw || raw.length === 0) return [];
const perBucket = Math.max(1, Math.ceil(raw.length / targetBuckets));
const result: BucketPoint[] = [];
@@ -52,11 +48,7 @@ function bucketWithStats(raw: number[], timestamps: number[], windowSec: number,
const ts = tsSlice[Math.floor(tsSlice.length / 2)] || 0;
result.push({
time: new Date(ts * 1000).toLocaleTimeString('zh-CN', { hour: '2-digit', minute: '2-digit' }),
timestamp: ts,
avg: Number(avg.toFixed(2)),
max: Number(max.toFixed(2)),
min: Number(min.toFixed(2)),
count: slice.length,
timestamp: ts, avg: Number(avg.toFixed(2)), max: Number(max.toFixed(2)), min: Number(min.toFixed(2)), count: slice.length,
});
}
return result.slice(-targetBuckets);
@@ -91,7 +83,6 @@ export function HostMonitor() {
const timeConfig = TIME_RANGES.find(tr => tr.hours === rangeHours) || TIME_RANGES[0];
// 加载主机列表
useEffect(() => {
agentApi.getLatest().then((data: any) => {
const list = Array.isArray(data) ? data : (data?.data || data?.list || []);
@@ -100,16 +91,11 @@ export function HostMonitor() {
const m = urlHost ? list.find((h: any) => h.hostname === urlHost) : null;
setSelectedHost(m?.hostname || list[0]?.hostname || '');
}
// 切换主机时同步更新 latest / serverInfo
const cur = list.find((h: any) => h.hostname === (selectedHost || urlHost));
if (cur) {
setLatest(cur);
setServerInfo(cur);
}
if (cur) { setLatest(cur); setServerInfo(cur); }
}).catch(() => {}).finally(() => setLoading(false));
}, [selectedHost]);
// 加载历史数据
useEffect(() => {
if (!selectedHost) return;
setLoading(true);
@@ -126,25 +112,18 @@ export function HostMonitor() {
.finally(() => setLoading(false));
}, [selectedHost, rangeHours]);
// 从原始历史数据提取指标 + 分桶聚合
// 历史指标提取
const metrics = useMemo(() => {
const rawCpu: number[] = [];
const rawMem: number[] = [];
const rawLoad1: number[] = [];
const rawDisk: number[] = [];
const rawTcp: number[] = [];
const rawRx: number[] = [];
const rawTx: number[] = [];
const rawIoR: number[] = [];
const rawIoW: number[] = [];
const rawIoRops: number[] = [];
const rawIoWops: number[] = [];
const rawCpu: number[] = []; const rawMem: number[] = []; const rawLoad1: number[] = [];
const rawDisk: number[] = []; const rawTcp: number[] = []; const rawTw: number[] = [];
const rawRx: number[] = []; const rawTx: number[] = [];
const rawIoR: number[] = []; const rawIoW: number[] = [];
const rawSwap: number[] = []; const rawFD: number[] = [];
const timestamps: number[] = [];
for (const r of history) {
const ts = r.report_time ? new Date(r.report_time).getTime() / 1000 : (r.created_at ? new Date(r.created_at).getTime() / 1000 : 0);
timestamps.push(ts);
rawCpu.push(r.cpu_usage || 0);
rawMem.push(r.mem_usage || 0);
rawLoad1.push(r.load1 || 0);
@@ -152,34 +131,45 @@ export function HostMonitor() {
const net = parseJSON(r.net_info);
rawTcp.push(net.tcp_established || 0);
rawTw.push(net.tcp_time_wait || 0);
rawRx.push(net.net_rx_bps || 0);
rawTx.push(net.net_tx_bps || 0);
const dio = parseJSON(r.disk_io_info);
rawIoR.push(dio.read_bps || 0);
rawIoW.push(dio.write_bps || 0);
rawIoRops.push(dio.read_iops || 0);
rawIoWops.push(dio.write_iops || 0);
const swap = parseJSON(r.swap_info);
rawSwap.push(swap?.usage_percent || 0);
const fd = parseJSON(r.fd_info);
rawFD.push(fd?.usage_pct || 0);
}
return {
cpu: bucketWithStats(rawCpu, timestamps, timeConfig.window, timeConfig.buckets),
mem: bucketWithStats(rawMem, timestamps, timeConfig.window, timeConfig.buckets),
load1: bucketWithStats(rawLoad1, timestamps, timeConfig.window, timeConfig.buckets),
disk: bucketWithStats(rawDisk, timestamps, timeConfig.window, timeConfig.buckets),
tcpEst: bucketWithStats(rawTcp, timestamps, timeConfig.window, timeConfig.buckets),
rx: bucketWithStats(rawRx.map(v => v / 1024), timestamps, timeConfig.window, timeConfig.buckets),
tx: bucketWithStats(rawTx.map(v => v / 1024), timestamps, timeConfig.window, timeConfig.buckets),
ioRead: bucketWithStats(rawIoR.map(v => v / 1024), timestamps, timeConfig.window, timeConfig.buckets),
ioWrite: bucketWithStats(rawIoW.map(v => v / 1024), timestamps, timeConfig.window, timeConfig.buckets),
ioReadOps: bucketWithStats(rawIoRops, timestamps, timeConfig.window, timeConfig.buckets),
ioWriteOps: bucketWithStats(rawIoWops, timestamps, timeConfig.window, timeConfig.buckets),
cpu: bucketWithStats(rawCpu, timestamps, timeConfig.buckets),
mem: bucketWithStats(rawMem, timestamps, timeConfig.buckets),
load1: bucketWithStats(rawLoad1, timestamps, timeConfig.buckets),
disk: bucketWithStats(rawDisk, timestamps, timeConfig.buckets),
tcpEst: bucketWithStats(rawTcp, timestamps, timeConfig.buckets),
tcpTW: bucketWithStats(rawTw, timestamps, timeConfig.buckets),
rx: bucketWithStats(rawRx.map(v => v / 1024), timestamps, timeConfig.buckets),
tx: bucketWithStats(rawTx.map(v => v / 1024), timestamps, timeConfig.buckets),
ioRead: bucketWithStats(rawIoR.map(v => v / 1024), timestamps, timeConfig.buckets),
ioWrite: bucketWithStats(rawIoW.map(v => v / 1024), timestamps, timeConfig.buckets),
swap: bucketWithStats(rawSwap, timestamps, timeConfig.buckets),
fd: bucketWithStats(rawFD, timestamps, timeConfig.buckets),
};
}, [history, timeConfig]);
const netInfo = parseJSON(latest?.net_info);
const portInfo: any[] = Array.isArray(latest?.port_info) ? latest.port_info : (Array.isArray(parseJSON(latest?.port_info)) ? parseJSON(latest?.port_info) : []);
const diskIOInfo = parseJSON(latest?.disk_io_info);
const swapInfo = parseJSON(latest?.swap_info);
const processTop: any[] = Array.isArray(parseJSON(latest?.process_top_info)) ? parseJSON(latest?.process_top_info) : [];
const fdInfo = parseJSON(latest?.fd_info);
const csInfo = parseJSON(latest?.cs_info);
const heartbeatInfo = parseJSON(latest?.heartbeat_info);
const currentVal = (key: string, fallback = '--') => {
if (!latest) return fallback;
@@ -188,12 +178,13 @@ export function HostMonitor() {
if (key === 'disk') return latest.disk_usage != null ? `${latest.disk_usage.toFixed(1)}%` : fallback;
if (key === 'load1') return latest.load1 != null ? String(latest.load1) : fallback;
if (key === 'tcp') return netInfo.tcp_established != null ? String(netInfo.tcp_established) : fallback;
if (key === 'tw') return netInfo.tcp_time_wait != null ? String(netInfo.tcp_time_wait) : fallback;
if (key === 'rx') return netInfo.net_rx_bps != null ? `${(netInfo.net_rx_bps / 1024).toFixed(1)} KB/s` : fallback;
if (key === 'tx') return netInfo.net_tx_bps != null ? `${(netInfo.net_tx_bps / 1024).toFixed(1)} KB/s` : fallback;
if (key === 'ioR') return diskIOInfo.read_bps != null ? `${formatBPS(diskIOInfo.read_bps)}` : fallback;
if (key === 'ioW') return diskIOInfo.write_bps != null ? `${formatBPS(diskIOInfo.write_bps)}` : fallback;
if (key === 'ioR_ops') return diskIOInfo.read_iops != null ? `${diskIOInfo.read_iops.toFixed(1)} count/s` : fallback;
if (key === 'ioW_ops') return diskIOInfo.write_iops != null ? `${diskIOInfo.write_iops.toFixed(1)} count/s` : fallback;
if (key === 'swap') return swapInfo?.usage_percent != null ? `${swapInfo.usage_percent.toFixed(1)}%` : fallback;
if (key === 'fd') return fdInfo?.usage_pct != null ? `${fdInfo.usage_pct.toFixed(1)}%` : fallback;
return fallback;
};
@@ -223,9 +214,7 @@ export function HostMonitor() {
</span>
)}
</div>
<div className="flex items-center gap-2">
{/* 聚合类型选择 */}
<Select value={aggType} onValueChange={(v) => setAggType(v as AggType)}>
<SelectTrigger className="w-24 h-7 text-xs bg-[var(--dg-bg-secondary)] border-[var(--dg-border)]">
<SelectValue />
@@ -236,32 +225,23 @@ export function HostMonitor() {
<SelectItem value="min">最小值</SelectItem>
</SelectContent>
</Select>
{/* 时间范围 */}
<div className="flex items-center gap-1">
{TIME_RANGES.map(tr => (
<Button
key={tr.hours}
variant={rangeHours === tr.hours ? 'default' : 'outline'}
size="sm"
className="h-7 text-xs px-2.5"
onClick={() => setRangeHours(tr.hours)}
>
{tr.label}
</Button>
<Button key={tr.hours} variant={rangeHours === tr.hours ? 'default' : 'outline'} size="sm"
className="h-7 text-xs px-2.5" onClick={() => setRangeHours(tr.hours)}>{tr.label}</Button>
))}
</div>
<Badge variant="outline" className="text-[10px] h-6">聚合: {aggType}</Badge>
</div>
</div>
{/* 分类 Tab */}
<Tabs value={activeTab} onValueChange={setActiveTab}>
<TabsList className="h-8 bg-[var(--dg-bg-secondary)] border-[var(--dg-border)] gap-0">
<TabsList className="h-8 bg-[var(--dg-bg-secondary)] border-[var(--dg-border)] gap-0 overflow-x-auto">
{[
{ id: 'basic', label: '基础监控', icon: <Monitor className="w-3 h-3" /> },
{ id: 'disk', label: '磁盘监控', icon: <HardDrive className="w-3 h-3" /> },
{ id: 'network', label: '网络监控', icon: <Network className="w-3 h-3" /> },
{ id: 'process', label: '进程监控', icon: <List className="w-3 h-3" /> },
{ id: 'system', label: '系统信息', icon: <Info className="w-3 h-3" /> },
].map(tab => (
<TabsTrigger key={tab.id} value={tab.id} className="text-[11px] h-7 gap-1 data-[state=active]:bg-[var(--dg-bg-primary)]">
@@ -270,64 +250,135 @@ export function HostMonitor() {
))}
</TabsList>
{/* 基础监控 */}
{/* 基础监控 — 增加 Swap 卡片 */}
<TabsContent value="basic" className="mt-3 grid grid-cols-1 md:grid-cols-3 gap-3">
<MetricChartCard
title="CPU使用率(%)" value={currentVal('cpu')} icon={<Cpu className="h-4 w-4 text-blue-400" />}
data={metrics.cpu} color="#3b82f6" unit="%" domain={[0, 100]} aggType={aggType}
/>
<MetricChartCard
title="内存使用率(%)" value={currentVal('mem')} icon={<Server className="h-4 w-4 text-emerald-400" />}
data={metrics.mem} color="#10b981" unit="%" domain={[0, 100]} aggType={aggType}
/>
<MetricChartCard
title="系统平均负载(count)" value={currentVal('load1')} icon={<Activity className="h-4 w-4 text-purple-400" />}
data={metrics.load1} color="#8b5cf6" unit="" domain={[0, 'auto']} aggType={aggType}
/>
<MetricChartCard title="CPU 使用率(%)" value={currentVal('cpu')} icon={<Cpu className="h-4 w-4 text-blue-400" />}
data={metrics.cpu} color="#3b82f6" unit="%" domain={[0, 100]} aggType={aggType} />
<MetricChartCard title="内存使用率(%)" value={currentVal('mem')} icon={<Server className="h-4 w-4 text-emerald-400" />}
data={metrics.mem} color="#10b981" unit="%" domain={[0, 100]} aggType={aggType} />
<MetricChartCard title="系统负载(1m)" value={currentVal('load1')} icon={<Activity className="h-4 w-4 text-purple-400" />}
data={metrics.load1} color="#8b5cf6" unit="" domain={[0, 'auto']} aggType={aggType} />
</TabsContent>
{/* 磁盘监控 */}
<TabsContent value="disk" className="mt-3 space-y-3">
<div className="grid grid-cols-1 md:grid-cols-3 gap-3">
<MetricChartCard
title="磁盘使用率(%)" value={currentVal('disk')} icon={<HardDrive className="h-4 w-4 text-orange-400" />}
data={metrics.disk} color="#f97316" unit="%" domain={[0, 100]} aggType={aggType}
/>
<MetricChartCard
title="所有磁盘读取BPS(KB/s)" value={currentVal('ioR')} icon={<Disc className="h-4 w-4 text-blue-400" />}
data={metrics.ioRead} color="#3b82f6" unit="KB/s" domain={[0, 'auto']} aggType={aggType}
/>
<MetricChartCard
title="所有磁盘写入BPS(KB/s)" value={currentVal('ioW')} icon={<Disc className="h-4 w-4 text-emerald-400" />}
data={metrics.ioWrite} color="#10b981" unit="KB/s" domain={[0, 'auto']} aggType={aggType}
/>
</div>
<div className="grid grid-cols-1 md:grid-cols-2 gap-3">
<MetricChartCard
title="所有磁盘每秒读取次数(count/s)" value={currentVal('ioR_ops')} icon={<Zap className="h-4 w-4 text-blue-400" />}
data={metrics.ioReadOps} color="#6366f1" unit="count/s" domain={[0, 'auto']} aggType={aggType}
/>
<MetricChartCard
title="所有磁盘每秒写入次数(count/s)" value={currentVal('ioW_ops')} icon={<Zap className="h-4 w-4 text-emerald-400" />}
data={metrics.ioWriteOps} color="#22d3ee" unit="count/s" domain={[0, 'auto']} aggType={aggType}
/>
<MetricChartCard title="磁盘使用率(%)" value={currentVal('disk')} icon={<HardDrive className="h-4 w-4 text-orange-400" />}
data={metrics.disk} color="#f97316" unit="%" domain={[0, 100]} aggType={aggType} />
<MetricChartCard title="磁盘读取(KB/s)" value={currentVal('ioR')} icon={<Disc className="h-4 w-4 text-blue-400" />}
data={metrics.ioRead} color="#3b82f6" unit="KB/s" domain={[0, 'auto']} aggType={aggType} />
<MetricChartCard title="磁盘写入(KB/s)" value={currentVal('ioW')} icon={<Disc className="h-4 w-4 text-emerald-400" />}
data={metrics.ioWrite} color="#10b981" unit="KB/s" domain={[0, 'auto']} aggType={aggType} />
</div>
</TabsContent>
{/* 网络监控 */}
{/* 网络监控 — 增加 TIME_WAIT + FD 图表 */}
<TabsContent value="network" className="mt-3 grid grid-cols-1 md:grid-cols-3 gap-3">
<MetricChartCard
title="TCP连接数(个)" value={currentVal('tcp')} icon={<Network className="h-4 w-4 text-purple-400" />}
data={metrics.tcpEst} color="#8b5cf6" unit="个" domain={[0, 'auto']} aggType={aggType}
/>
<MetricChartCard
title="网络接收速率(KB/s)" value={currentVal('rx')} icon={<Network className="h-4 w-4 text-blue-400" />}
data={metrics.rx} color="#3b82f6" unit="KB/s" domain={[0, 'auto']} aggType={aggType}
/>
<MetricChartCard
title="网络发送速率(KB/s)" value={currentVal('tx')} icon={<Network className="h-4 w-4 text-emerald-400" />}
data={metrics.tx} color="#10b981" unit="KB/s" domain={[0, 'auto']} aggType={aggType}
/>
<MetricChartCard title="TCP 连接数(EST)" value={currentVal('tcp')} icon={<Network className="h-4 w-4 text-purple-400" />}
data={metrics.tcpEst} color="#8b5cf6" unit="个" domain={[0, 'auto']} aggType={aggType} />
<MetricChartCard title="TCP TIME_WAIT" value={currentVal('tw')} icon={<Clock className="h-4 w-4 text-amber-400" />}
data={metrics.tcpTW} color="#f59e0b" unit="个" domain={[0, 'auto']} aggType={aggType} />
<MetricChartCard title="网络接收(KB/s)" value={currentVal('rx')} icon={<Network className="h-4 w-4 text-blue-400" />}
data={metrics.rx} color="#3b82f6" unit="KB/s" domain={[0, 'auto']} aggType={aggType} />
</TabsContent>
{/* ═══ 进程监控 — v2.0 新增 ═══ */}
<TabsContent value="process" className="mt-3 space-y-3">
{/* 进程 TOP 表格 */}
<Card className="bg-[var(--dg-bg-secondary)] border-[var(--dg-border)]">
<CardContent className="p-4">
<h3 className="text-xs font-medium text-[var(--dg-text-primary)] mb-3 flex items-center gap-2">
<List className="h-4 w-4 text-cyan-400" />进程 TOP {processTop.length} (按内存排序)
</h3>
{processTop.length === 0 ? (
<div className="text-center py-6 text-xs text-[var(--dg-text-muted)] border border-dashed border-[var(--dg-border)] rounded-lg">
Agent v2.0+ 支持,当前无数据
</div>
) : (
<table className="w-full text-xs">
<thead>
<tr className="text-[var(--dg-text-muted)] border-b border-[var(--dg-border)]">
<th className="py-1.5 text-left font-medium">PID</th>
<th className="py-1.5 text-left font-medium">进程名</th>
<th className="py-1.5 text-right font-medium">内存 (MB)</th>
<th className="py-1.5 text-right font-medium">FD 数</th>
<th className="py-1.5 text-right font-medium">线程数</th>
</tr>
</thead>
<tbody>
{processTop.map((p: any, i: number) => (
<tr key={i} className="border-b border-[var(--dg-border)]/30 hover:bg-slate-800/30">
<td className="py-1.5 font-mono text-[var(--dg-text-muted)]">{p.pid}</td>
<td className="py-1.5 font-mono text-[var(--dg-text-primary)]">{p.name}</td>
<td className="py-1.5 text-right font-mono text-cyan-400">{(p.memory_mb ?? 0).toFixed(0)}</td>
<td className="py-1.5 text-right font-mono text-[var(--dg-text-muted)]">{p.fd_count ?? 0}</td>
<td className="py-1.5 text-right font-mono text-[var(--dg-text-muted)]">{p.threads ?? 0}</td>
</tr>
))}
</tbody>
</table>
)}
</CardContent>
</Card>
{/* Swap + FD + CS 快速卡片 */}
<div className="grid grid-cols-1 md:grid-cols-3 gap-3">
<MetricChartCard title="Swap 使用率(%)" value={currentVal('swap')}
icon={<AlertTriangle className="h-4 w-4 text-rose-400" />}
data={metrics.swap} color="#f43f5e" unit="%" domain={[0, 100]} aggType={aggType}
/>
<MetricChartCard title="FD 句柄使用率(%)" value={currentVal('fd')}
icon={<Activity className="h-4 w-4 text-cyan-400" />}
data={metrics.fd} color="#22d3ee" unit="%" domain={[0, 100]} aggType={aggType}
/>
{/* CS 当前值卡片 */}
<Card className="bg-[var(--dg-bg-secondary)] border-[var(--dg-border)]">
<CardContent className="p-3">
<div className="flex items-center gap-1.5 mb-2">
<Zap className="h-4 w-4 text-indigo-400" /><span className="text-xs text-[var(--dg-text-primary)]">上下文切换</span>
</div>
<div className="text-xl font-bold text-[var(--dg-text-primary)] tabular-nums">
{csInfo?.ctx_per_sec != null ? `${(csInfo.ctx_per_sec / 1000).toFixed(1)}K/s` : '--'}
</div>
<div className="text-[10px] text-[var(--dg-text-muted)] mt-0.5">
中断: {csInfo?.irq_per_sec != null ? `${(csInfo.irq_per_sec / 1000).toFixed(1)}K/s` : '--'}
</div>
</CardContent>
</Card>
</div>
{/* FD / Swap 详情 */}
<div className="grid grid-cols-1 md:grid-cols-2 gap-3">
{fdInfo && fdInfo.max > 0 && (
<Card className="bg-[var(--dg-bg-secondary)] border-[var(--dg-border)]">
<CardContent className="p-3">
<span className="text-[10px] text-[var(--dg-text-muted)]">文件句柄</span>
<div className="flex items-baseline gap-1">
<span className="text-lg font-bold text-[var(--dg-text-primary)]">{fdInfo.allocated}</span>
<span className="text-xs text-[var(--dg-text-muted)]">/ {fdInfo.max}</span>
</div>
<div className="mt-1 h-1.5 bg-slate-700 rounded-full overflow-hidden">
<div className="h-full rounded-full bg-cyan-500" style={{ width: `${Math.min(fdInfo.usage_pct || 0, 100)}%` }} />
</div>
</CardContent>
</Card>
)}
{swapInfo && swapInfo.total_gb > 0 && (
<Card className="bg-[var(--dg-bg-secondary)] border-[var(--dg-border)]">
<CardContent className="p-3">
<span className="text-[10px] text-[var(--dg-text-muted)]">Swap</span>
<div className="flex items-baseline gap-1">
<span className="text-lg font-bold text-[var(--dg-text-primary)]">{(swapInfo.used_gb ?? 0).toFixed(1)}</span>
<span className="text-xs text-[var(--dg-text-muted)]">/ {(swapInfo.total_gb ?? 0).toFixed(0)} GB</span>
</div>
<div className="mt-1 h-1.5 bg-slate-700 rounded-full overflow-hidden">
<div className={`h-full rounded-full ${(swapInfo.usage_percent || 0) > 50 ? 'bg-rose-500' : 'bg-amber-500'}`}
style={{ width: `${Math.min(swapInfo.usage_percent || 0, 100)}%` }} />
</div>
</CardContent>
</Card>
)}
</div>
</TabsContent>
{/* 系统信息 */}
@@ -344,9 +395,10 @@ export function HostMonitor() {
['总内存', serverInfo?.mem_total ? `${serverInfo.mem_total.toFixed(0)} GB` : '—'],
['已用内存', serverInfo?.mem_used ? `${serverInfo.mem_used.toFixed(1)} GB` : '—'],
['运行时长', serverInfo?.uptime ? `${Math.floor(serverInfo.uptime / 86400)}天 ${Math.floor((serverInfo.uptime % 86400) / 3600)}时` : '—'],
['Agent 版本', serverInfo?.agent_version || '—'],
['磁盘总容量', serverInfo?.disk_total ? `${serverInfo.disk_total} GB` : '—'],
['Agent 版本', heartbeatInfo?.version || serverInfo?.agent_version || '—'],
['Agent 序列号', heartbeatInfo?.report_seq != null ? String(heartbeatInfo.report_seq) : '—'],
['监听端口数', portInfo.length > 0 ? `${portInfo.length}` : '—'],
['Agent RSS', heartbeatInfo?.self_rss_mb ? `${heartbeatInfo.self_rss_mb.toFixed(1)} MB` : '—'],
].map(([label, val]) => (
<div key={label as string}>
<span className="text-[var(--dg-text-muted)]">{label}:</span>
@@ -374,7 +426,7 @@ export function HostMonitor() {
</Card>
)}
{/* 磁盘分区 */}
{/* 磁盘分区 + 网络接口 (保持原样) */}
{latest?.disk_info && (() => {
const disk = parseJSON(latest.disk_info);
const parts = Array.isArray(disk) ? disk : (disk.partitions || []);
@@ -382,10 +434,7 @@ export function HostMonitor() {
return (
<Card className="bg-[var(--dg-bg-secondary)] border-[var(--dg-border)]">
<CardContent className="p-4">
<div className="flex items-center gap-2 mb-2">
<HardDrive className="h-4 w-4 text-[var(--dg-text-muted)]" />
<h3 className="text-xs font-medium text-[var(--dg-text-primary)]">磁盘分区</h3>
</div>
<h3 className="text-xs font-medium text-[var(--dg-text-primary)] mb-2 flex items-center gap-2"><HardDrive className="h-4 w-4" />磁盘分区</h3>
<div className="space-y-1.5">
{parts.map((p: any, i: number) => (
<div key={i} className="flex items-center gap-2 text-xs">
@@ -402,31 +451,13 @@ export function HostMonitor() {
</Card>
);
})()}
{/* 网络接口 */}
{netInfo && (
<Card className="bg-[var(--dg-bg-secondary)] border-[var(--dg-border)]">
<CardContent className="p-4">
<div className="flex items-center gap-2 mb-2">
<Network className="h-4 w-4 text-[var(--dg-text-muted)]" />
<h3 className="text-xs font-medium text-[var(--dg-text-primary)]">网络接口</h3>
</div>
<div className="grid grid-cols-2 md:grid-cols-4 gap-3 text-xs">
<div><span className="text-[var(--dg-text-muted)]">网卡:</span><span className="text-[var(--dg-text-primary)] font-mono">{netInfo.nic_name || '—'}</span></div>
<div><span className="text-[var(--dg-text-muted)]">接收:</span><span className="text-blue-400 font-mono">{netInfo.net_rx_bps ? `${(netInfo.net_rx_bps/1024).toFixed(1)} KB/s` : '—'}</span></div>
<div><span className="text-[var(--dg-text-muted)]">发送:</span><span className="text-emerald-400 font-mono">{netInfo.net_tx_bps ? `${(netInfo.net_tx_bps/1024).toFixed(1)} KB/s` : '—'}</span></div>
<div><span className="text-[var(--dg-text-muted)]">EST/TW:</span><span className="text-[var(--dg-text-primary)] font-mono">{netInfo.tcp_established || 0}/{netInfo.tcp_time_wait || 0}</span></div>
</div>
</CardContent>
</Card>
)}
</TabsContent>
</Tabs>
</div>
);
}
// ═══════ 指标图表卡片 (带 Brush 缩放 + avg/max/min 数据) ═══════
// ═══════ 指标图表卡片 ═══════
function MetricChartCard({
title, value, icon, data, color, unit, domain, aggType,
}: {
@@ -434,38 +465,20 @@ function MetricChartCard({
data: BucketPoint[]; color: string; unit: string;
domain: [number, number | 'auto']; aggType: AggType;
}) {
// 选择当前聚合类型的值
const chartData = data.map(d => ({
...d,
value: d[aggType],
}));
const chartData = data.map(d => ({ ...d, value: d[aggType] }));
return (
<Card className="bg-[var(--dg-bg-secondary)] border-[var(--dg-border)]">
<CardContent className="p-3">
{/* 标题行 */}
<div className="flex items-center justify-between mb-1">
<div className="flex items-center gap-1.5">
{icon}
<span className="text-xs text-[var(--dg-text-primary)] font-medium truncate">{title}</span>
</div>
<span className="text-[10px] text-[var(--dg-text-muted)]">
{aggType === 'avg' ? '平均值' : aggType === 'max' ? '最大值' : '最小值'}
</span>
<div className="flex items-center gap-1.5">{icon}<span className="text-xs text-[var(--dg-text-primary)] font-medium truncate">{title}</span></div>
</div>
{/* 当前值 */}
<div className="mb-2">
<span className="text-xl font-bold text-[var(--dg-text-primary)] tabular-nums">{value}</span>
{unit && <span className="text-xs text-[var(--dg-text-muted)] ml-1">{unit}</span>}
</div>
{/* 趋势图 + Brush 缩放 */}
<div className="h-48">
{chartData.length === 0 ? (
<div className="h-full flex items-center justify-center text-xs text-[var(--dg-text-muted)] border border-dashed border-[var(--dg-border)] rounded-md">
暂无数据
</div>
<div className="h-full flex items-center justify-center text-xs text-[var(--dg-text-muted)] border border-dashed border-[var(--dg-border)] rounded-md">暂无数据</div>
) : (
<ResponsiveContainer width="100%" height="100%">
<AreaChart data={chartData} margin={{ top: 2, right: 2, bottom: 0, left: -10 }}>
@@ -478,33 +491,12 @@ function MetricChartCard({
<CartesianGrid strokeDasharray="3 3" stroke="#1e293b" strokeOpacity={0.5} />
<XAxis dataKey="time" hide />
<YAxis hide domain={domain[1] === 'auto' ? [0, (max: number) => max * 1.1] : domain as [number, number]} />
<Tooltip
contentStyle={{
backgroundColor: '#0f172a', border: '1px solid #1e293b',
borderRadius: '4px', color: '#f8fafc', fontSize: '11px', padding: '4px 8px',
}}
<Tooltip contentStyle={{ backgroundColor: '#0f172a', border: '1px solid #1e293b', borderRadius: '4px', color: '#f8fafc', fontSize: '11px', padding: '4px 8px' }}
formatter={(v: number) => [`${v.toFixed(2)} ${unit}`, title.replace(/\(.+\)/, '')]}
labelFormatter={(label) => `时间: ${label}`}
/>
labelFormatter={(label) => `时间: ${label}`} />
<Area type="monotone" dataKey="value" stroke={color} strokeWidth={1.5} fill={`url(#grad-${title})`} />
{/* Brush 缩放条 — 可拖动选择时间范围,鼠标滚轮精细调整 */}
<Brush
dataKey="time"
height={24}
stroke="#334155"
fill="#0f172a"
tickFormatter={(t: string) => t}
startIndex={Math.max(0, chartData.length - Math.min(20, chartData.length))}
/>
{/* 参考线:平均值 */}
{chartData.length > 0 && (
<ReferenceLine
y={chartData.reduce((s, d) => s + d.value, 0) / chartData.length}
stroke={color}
strokeOpacity={0.3}
strokeDasharray="4 4"
/>
)}
<Brush dataKey="time" height={24} stroke="#334155" fill="#0f172a"
startIndex={Math.max(0, chartData.length - Math.min(20, chartData.length))} />
</AreaChart>
</ResponsiveContainer>
)}
@@ -513,5 +505,3 @@ function MetricChartCard({
</Card>
);
}
export default HostMonitor;