feat: Agent采集uptime, 后端持久化kernel/uptime/diskIO, 前端磁盘BPS+IOPS展示
- Agent: system.go 添加 readUptime(), SystemStat 携带 Uptime - Backend: Server 模型新增 Kernel 字段, ReceiveReport 持久化 kernel+uptime - Backend: /agent/latest 返回 kernel/uptime/port_info/disk_io_info/disk_total - Frontend: 磁盘监控改为 BPS+IOPS (4张卡片), 系统信息修复内核/运行时长/监听端口/磁盘容量 - 图表单位从 MB/s 改为 KB/s, 添加 formatBPS 工具函数
This commit is contained in:
1 parent
31c2e338a3
commit
5949ec5d0c
48 files changed
+2182
-956
No files matched your search
+397
-387
@@ -1,454 +1,464 @@
|
||||
// 主机监控 — Agent 采集指标展示 (CPU/内存/TCP/磁盘IO/趋势图) // Logan.Li
|
||||
import { useState, useEffect, useRef, useCallback } from 'react';
|
||||
// 主机监控详情 — 阿里云云监控风格 (分类指标 + 时间范围 + 时序图表)
|
||||
import { useState, useEffect, useCallback, useMemo } from 'react';
|
||||
import { useSearchParams } from 'react-router-dom';
|
||||
import { agentApi } from '@/services/api';
|
||||
import { useUserStore } from '@/store';
|
||||
import { asList, isOnline, timeAgo } from '@/components/agent/agentUtils';
|
||||
import { Card, CardContent } from '@/components/ui/card';
|
||||
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';
|
||||
import { Cpu, HardDrive, Network, Activity, Server, Loader2, TrendingUp } from 'lucide-react';
|
||||
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs';
|
||||
import { Badge } from '@/components/ui/badge';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import {
|
||||
AreaChart,
|
||||
Area,
|
||||
XAxis,
|
||||
YAxis,
|
||||
CartesianGrid,
|
||||
Tooltip,
|
||||
ResponsiveContainer,
|
||||
Cpu, HardDrive, Network, Activity, Server, Loader2,
|
||||
Info, Monitor, Disc, Zap, Clock
|
||||
} from 'lucide-react';
|
||||
import {
|
||||
AreaChart, Area, XAxis, YAxis, CartesianGrid, Tooltip, ResponsiveContainer, LineChart, Line,
|
||||
} from 'recharts';
|
||||
|
||||
// Tailwind 不支持动态 class,用颜色映射表
|
||||
const colorMap: Record<string, string> = {
|
||||
blue: 'bg-blue-500/10',
|
||||
emerald: 'bg-emerald-500/10',
|
||||
purple: 'bg-purple-500/10',
|
||||
orange: 'bg-orange-500/10',
|
||||
};
|
||||
// 时间范围配置
|
||||
const TIME_RANGES = [
|
||||
{ label: '1小时', hours: 1 },
|
||||
{ label: '6小时', hours: 6 },
|
||||
{ label: '12小时', hours: 12 },
|
||||
{ label: '1天', hours: 24 },
|
||||
{ label: '3天', hours: 72 },
|
||||
{ label: '7天', hours: 168 },
|
||||
{ label: '14天', hours: 336 },
|
||||
] as const;
|
||||
|
||||
function parseJSON(raw: string): Record<string, any> {
|
||||
// 聚合:把原始数据压缩到 targetBuckets 个桶
|
||||
function bucketData(data: number[], targetBuckets: number = 48): { time: string; value: number }[] {
|
||||
if (!data || data.length === 0) return [];
|
||||
const perBucket = Math.max(1, Math.ceil(data.length / targetBuckets));
|
||||
const result: { time: string; value: number }[] = [];
|
||||
for (let i = 0; i < data.length; i += perBucket) {
|
||||
const slice = data.slice(i, i + perBucket);
|
||||
const avg = slice.reduce((a, b) => a + b, 0) / slice.length;
|
||||
result.push({ time: `-${Math.round((data.length - i) * 10 / 3600)}h`, value: Number(avg.toFixed(1)) });
|
||||
}
|
||||
return result.slice(-targetBuckets);
|
||||
}
|
||||
|
||||
function parseJSON(raw: any): any {
|
||||
if (!raw) return {};
|
||||
if (typeof raw === 'object') return raw;
|
||||
try { return JSON.parse(raw); } catch { return {}; }
|
||||
}
|
||||
|
||||
function fmtBps(bps: number): string {
|
||||
if (!bps || bps === 0) return '--';
|
||||
if (bps > 1e9) return `${(bps / 1e9).toFixed(1)} GB/s`;
|
||||
if (bps > 1e6) return `${(bps / 1e6).toFixed(1)} MB/s`;
|
||||
if (bps > 1e3) return `${(bps / 1e3).toFixed(1)} KB/s`;
|
||||
function formatBPS(bps: number): string {
|
||||
if (bps >= 1024 * 1024 * 1024) return `${(bps / 1024 / 1024 / 1024).toFixed(1)} GB/s`;
|
||||
if (bps >= 1024 * 1024) return `${(bps / 1024 / 1024).toFixed(1)} MB/s`;
|
||||
if (bps >= 1024) return `${(bps / 1024).toFixed(1)} KB/s`;
|
||||
return `${bps.toFixed(1)} B/s`;
|
||||
}
|
||||
|
||||
function fmtNum(n: number): string {
|
||||
return n != null && !Number.isNaN(n) ? String(Math.round(n)) : '--';
|
||||
}
|
||||
|
||||
export function HostMonitor() {
|
||||
const [searchParams] = useSearchParams();
|
||||
const urlHost = searchParams.get('host') || '';
|
||||
const [hosts, setHosts] = useState<any[]>([]);
|
||||
const [selectedHost, setSelectedHost] = useState(urlHost);
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [activeTab, setActiveTab] = useState('basic');
|
||||
const [rangeHours, setRangeHours] = useState(1);
|
||||
|
||||
// 原始历史数据
|
||||
const [history, setHistory] = useState<any[]>([]);
|
||||
|
||||
// 最新快照
|
||||
const [latest, setLatest] = useState<any>(null);
|
||||
const [cpuKlines, setCpuKlines] = useState<any[]>([]);
|
||||
const [memKlines, setMemKlines] = useState<any[]>([]);
|
||||
const [cardLoading, setCardLoading] = useState(true);
|
||||
const [chartLoading, setChartLoading] = useState(false);
|
||||
|
||||
// Top 5 排行
|
||||
const [topCPU, setTopCPU] = useState<any[]>([]);
|
||||
const [topMem, setTopMem] = useState<any[]>([]);
|
||||
const [topDisk, setTopDisk] = useState<any[]>([]);
|
||||
// 服务器信息(来自 asset_servers):OS、内核、总内存等,不与 history 混淆
|
||||
const [serverInfo, setServerInfo] = useState<any>(null);
|
||||
|
||||
// 加载主机列表
|
||||
useEffect(() => {
|
||||
import('@/services/http').then(async ({ http }) => {
|
||||
try {
|
||||
const [cpu, mem, disk] = await Promise.all([
|
||||
http.get('/metrics/top?metric=cpu&limit=5'),
|
||||
http.get('/metrics/top?metric=memory&limit=5'),
|
||||
http.get('/metrics/top?metric=disk&limit=5'),
|
||||
]);
|
||||
setTopCPU(Array.isArray(cpu) ? cpu : []);
|
||||
setTopMem(Array.isArray(mem) ? mem : []);
|
||||
setTopDisk(Array.isArray(disk) ? disk : []);
|
||||
} catch { /* 后端未就绪时静默 */ }
|
||||
});
|
||||
}, [hosts]);
|
||||
|
||||
const wsRef = useRef<WebSocket | null>(null);
|
||||
const reconnectRef = useRef<ReturnType<typeof setTimeout> | null>(null);
|
||||
|
||||
// Step 1: 加载主机列表
|
||||
const loadHosts = useCallback(async () => {
|
||||
try {
|
||||
const data = await agentApi.getLatest();
|
||||
const list = asList(data);
|
||||
agentApi.getLatest().then((data: any) => {
|
||||
const list = Array.isArray(data) ? data : (data?.data || data?.list || []);
|
||||
setHosts(list);
|
||||
if (list.length > 0 && !selectedHost) {
|
||||
// 优先匹配 URL 参数传入的主机
|
||||
const matched = urlHost ? list.find((h: any) => h.hostname === urlHost) : null;
|
||||
setSelectedHost(matched ? matched.hostname : list[0].hostname);
|
||||
const m = urlHost ? list.find((h: any) => h.hostname === urlHost) : null;
|
||||
setSelectedHost(m?.hostname || list[0]?.hostname || '');
|
||||
}
|
||||
} catch { /* 后端不可用时显示空状态 */ }
|
||||
finally { setCardLoading(false); }
|
||||
}, [selectedHost, urlHost]);
|
||||
const cur = list.find((h: any) => h.hostname === (urlHost || selectedHost));
|
||||
if (cur) {
|
||||
setLatest(cur);
|
||||
setServerInfo(cur);
|
||||
}
|
||||
}).catch(() => {}).finally(() => setLoading(false));
|
||||
}, []);
|
||||
|
||||
useEffect(() => { loadHosts(); }, []);
|
||||
|
||||
// Step 2: 选中主机后加载 K 线
|
||||
// 加载历史数据
|
||||
useEffect(() => {
|
||||
if (!selectedHost) return;
|
||||
setChartLoading(true);
|
||||
|
||||
const now = new Date();
|
||||
const from = new Date(now.getTime() - 60 * 60 * 1000);
|
||||
// JS toISOString() 包含毫秒 (2026-06-18T12:50:00.000Z),Go time.RFC3339 不解析毫秒
|
||||
const toISO = (d: Date) => d.toISOString().replace(/\.\d{3}Z$/, 'Z');
|
||||
|
||||
Promise.all([
|
||||
agentApi.getKline({ hostname: selectedHost, metric: 'cpu', interval: '5m', from: toISO(from), to: toISO(now) }),
|
||||
agentApi.getKline({ hostname: selectedHost, metric: 'mem', interval: '5m', from: toISO(from), to: toISO(now) }),
|
||||
])
|
||||
.then(([cpu, mem]) => {
|
||||
setCpuKlines(asList(cpu));
|
||||
setMemKlines(asList(mem));
|
||||
setLoading(true);
|
||||
agentApi.getHistory(selectedHost, rangeHours)
|
||||
.then((data: any) => {
|
||||
const list = Array.isArray(data) ? data : (data?.data || data?.list || []);
|
||||
setHistory(list);
|
||||
if (list.length > 0) {
|
||||
const fresh = list[list.length - 1];
|
||||
setLatest((prev: any) => ({ ...prev, ...fresh }));
|
||||
}
|
||||
})
|
||||
.catch(() => { setCpuKlines([]); setMemKlines([]); })
|
||||
.finally(() => setChartLoading(false));
|
||||
.catch(() => setHistory([]))
|
||||
.finally(() => setLoading(false));
|
||||
}, [selectedHost, rangeHours]);
|
||||
|
||||
// 从 hosts 列表中同步 selected host 的最新指标
|
||||
const current = hosts.find((h: any) => h.hostname === selectedHost);
|
||||
if (current) setLatest(current);
|
||||
}, [selectedHost, hosts]);
|
||||
// 提取指标数组
|
||||
const metrics = useMemo(() => {
|
||||
const cpu: number[] = [];
|
||||
const mem: number[] = [];
|
||||
const load1: number[] = [];
|
||||
const disk: number[] = [];
|
||||
const tcpEst: number[] = [];
|
||||
const rx: number[] = [];
|
||||
const tx: number[] = [];
|
||||
const ioRead: number[] = [];
|
||||
const ioWrite: number[] = [];
|
||||
const ioReadOps: number[] = [];
|
||||
const ioWriteOps: number[] = [];
|
||||
|
||||
// Step 3: WebSocket 实时推送
|
||||
useEffect(() => {
|
||||
const token = useUserStore.getState().token;
|
||||
if (!token) return;
|
||||
for (const r of history) {
|
||||
cpu.push(r.cpu_usage || 0);
|
||||
mem.push(r.mem_usage || 0);
|
||||
load1.push(r.load1 || 0);
|
||||
disk.push(r.disk_usage || 0);
|
||||
|
||||
const protocol = window.location.protocol === 'https:' ? 'wss:' : 'ws:';
|
||||
const wsUrl = `${protocol}//${window.location.host}/ws/metrics?token=${token}`;
|
||||
const net = parseJSON(r.net_info);
|
||||
tcpEst.push(net.tcp_established || 0);
|
||||
rx.push(net.net_rx_bps || 0);
|
||||
tx.push(net.net_tx_bps || 0);
|
||||
|
||||
let cancelled = false;
|
||||
const connect = () => {
|
||||
if (cancelled) return;
|
||||
if (wsRef.current?.readyState === WebSocket.OPEN) return;
|
||||
const dio = parseJSON(r.disk_io_info);
|
||||
ioRead.push(dio.read_bps || 0);
|
||||
ioWrite.push(dio.write_bps || 0);
|
||||
ioReadOps.push(dio.read_iops || 0);
|
||||
ioWriteOps.push(dio.write_iops || 0);
|
||||
}
|
||||
|
||||
const ws = new WebSocket(wsUrl);
|
||||
wsRef.current = ws;
|
||||
const target = rangeHours <= 1 ? 60 : rangeHours <= 6 ? 72 : rangeHours <= 24 ? 96 : 120;
|
||||
|
||||
ws.onmessage = (event) => {
|
||||
try {
|
||||
const msg = JSON.parse(event.data);
|
||||
if (msg.type === 'metrics_update' && msg.hostname === selectedHost) {
|
||||
setLatest((prev: any) => {
|
||||
if (!prev) return prev;
|
||||
const netInfo = parseJSON(prev.net_info);
|
||||
const diskIO = parseJSON(prev.disk_io_info);
|
||||
return {
|
||||
...prev,
|
||||
cpu_usage: msg.cpu_usage ?? prev.cpu_usage,
|
||||
mem_usage: msg.memory_usage ?? prev.mem_usage,
|
||||
disk_info: prev.disk_info, // 保留原有磁盘信息
|
||||
net_info: JSON.stringify({
|
||||
...netInfo,
|
||||
tcp_established: msg.tcp_established ?? netInfo.tcp_established,
|
||||
tcp_time_wait: msg.tcp_time_wait ?? netInfo.tcp_time_wait,
|
||||
net_rx_bps: msg.net_rx_bps ?? netInfo.net_rx_bps,
|
||||
net_tx_bps: msg.net_tx_bps ?? netInfo.net_tx_bps,
|
||||
}),
|
||||
disk_io_info: JSON.stringify({
|
||||
...diskIO,
|
||||
read_bps: msg.disk_read_bps ?? diskIO.read_bps,
|
||||
write_bps: msg.disk_write_bps ?? diskIO.write_bps,
|
||||
}),
|
||||
};
|
||||
});
|
||||
}
|
||||
} catch { /* WS 消息解析失败静默 */ }
|
||||
};
|
||||
|
||||
ws.onclose = () => {
|
||||
if (!cancelled) reconnectRef.current = setTimeout(connect, 3000);
|
||||
};
|
||||
return {
|
||||
cpu: bucketData(cpu, target),
|
||||
mem: bucketData(mem, target),
|
||||
load1: bucketData(load1, target),
|
||||
disk: bucketData(disk, target),
|
||||
tcpEst: bucketData(tcpEst, target),
|
||||
rx: bucketData(rx.map(v => v / 1024), target), // KB/s
|
||||
tx: bucketData(tx.map(v => v / 1024), target),
|
||||
ioRead: bucketData(ioRead.map(v => v / 1024), target), // KB/s
|
||||
ioWrite: bucketData(ioWrite.map(v => v / 1024), target), // KB/s
|
||||
ioReadOps: bucketData(ioReadOps, target), // count/s
|
||||
ioWriteOps: bucketData(ioWriteOps, target), // count/s
|
||||
};
|
||||
}, [history, rangeHours]);
|
||||
|
||||
connect();
|
||||
return () => {
|
||||
cancelled = true;
|
||||
if (reconnectRef.current) clearTimeout(reconnectRef.current);
|
||||
wsRef.current?.close();
|
||||
};
|
||||
}, [selectedHost]);
|
||||
|
||||
// 解析最新 JSON 字段
|
||||
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);
|
||||
|
||||
// 合并 K 线为图表数据
|
||||
const chartData = cpuKlines.map((k: any, i: number) => ({
|
||||
time: new Date(k.bucket_time).toLocaleTimeString('zh-CN', { hour: '2-digit', minute: '2-digit' }),
|
||||
cpu: k.avg ?? k.close ?? 0,
|
||||
mem: memKlines[i]?.avg ?? memKlines[i]?.close ?? 0,
|
||||
}));
|
||||
const currentVal = (key: string, fallback = '--') => {
|
||||
if (!latest) return fallback;
|
||||
if (key === 'cpu') return latest.cpu_usage != null ? `${latest.cpu_usage.toFixed(1)}%` : fallback;
|
||||
if (key === 'mem') return latest.mem_usage != null ? `${latest.mem_usage.toFixed(1)}%` : fallback;
|
||||
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 === '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;
|
||||
return fallback;
|
||||
};
|
||||
|
||||
if (loading && !history.length) {
|
||||
return <div className="flex items-center justify-center h-64"><Loader2 className="h-8 w-8 animate-spin text-slate-500" /></div>;
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="space-y-6">
|
||||
{/* 主机选择器 */}
|
||||
<div className="flex items-center gap-4 flex-wrap">
|
||||
<label className="text-sm text-[var(--dg-text-muted)] shrink-0">选择主机:</label>
|
||||
<Select value={selectedHost} onValueChange={setSelectedHost}>
|
||||
<SelectTrigger className="w-64 bg-[var(--dg-bg-secondary)] border-[var(--dg-border)]">
|
||||
<SelectValue placeholder={cardLoading ? '加载中...' : '选择主机...'} />
|
||||
</SelectTrigger>
|
||||
<SelectContent className="bg-slate-800 border-slate-700 text-slate-200">
|
||||
{hosts.map((h: any) => (
|
||||
<SelectItem key={h.hostname} value={h.hostname}>
|
||||
<span className="flex items-center gap-2">
|
||||
{h.hostname}
|
||||
<span
|
||||
className={`inline-block w-1.5 h-1.5 rounded-full ${
|
||||
isOnline(h.report_time) ? 'bg-emerald-400' : 'bg-red-400'
|
||||
}`}
|
||||
/>
|
||||
</span>
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
{latest && (
|
||||
<span className="text-xs text-[var(--dg-text-muted)]">
|
||||
最后上报: {timeAgo(latest.report_time)}
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Top 5 排行 */}
|
||||
{(topCPU.length > 0 || topMem.length > 0 || topDisk.length > 0) && (
|
||||
<div className="grid grid-cols-1 md:grid-cols-3 gap-4">
|
||||
<TopRankCard title="🔥 CPU 使用率 Top 5" icon={<Cpu className="h-4 w-4 text-red-400" />} data={topCPU} valueKey="cpu_usage" unit="%" color="red" />
|
||||
<TopRankCard title="💾 内存使用率 Top 5" icon={<Server className="h-4 w-4 text-amber-400" />} data={topMem} valueKey="memory_usage" unit="%" color="amber" />
|
||||
<TopRankCard title="💿 磁盘使用率 Top 5" icon={<HardDrive className="h-4 w-4 text-orange-400" />} data={topDisk} valueKey="disk_usage" unit="%" color="orange" />
|
||||
<div className="space-y-3">
|
||||
{/* 顶栏:主机选择 + 时间范围 */}
|
||||
<div className="flex items-center justify-between flex-wrap gap-2">
|
||||
<div className="flex items-center gap-2">
|
||||
<Server className="h-4 w-4 text-blue-400" />
|
||||
<Select value={selectedHost} onValueChange={setSelectedHost}>
|
||||
<SelectTrigger className="w-52 h-8 text-xs bg-[var(--dg-bg-secondary)] border-[var(--dg-border)]">
|
||||
<SelectValue placeholder="选择主机..." />
|
||||
</SelectTrigger>
|
||||
<SelectContent className="bg-slate-800 border-slate-700 text-slate-200">
|
||||
{hosts.map((h: any) => (
|
||||
<SelectItem key={h.hostname} value={h.hostname}>{h.hostname}</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
{serverInfo && (
|
||||
<span className="text-xs text-[var(--dg-text-muted)] ml-2">
|
||||
{serverInfo.os || ''} | {serverInfo.cpu_cores || '?'} 核 | {serverInfo.mem_total ? `${serverInfo.mem_total.toFixed(0)}GB` : '?'}
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* 概览卡片 */}
|
||||
<div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-4">
|
||||
<MetricCard
|
||||
icon={<Cpu className="h-5 w-5 text-blue-400" />}
|
||||
label="CPU 使用率"
|
||||
value={latest?.cpu_usage != null ? `${latest.cpu_usage.toFixed(1)}%` : '--'}
|
||||
color="blue"
|
||||
/>
|
||||
<MetricCard
|
||||
icon={<Server className="h-5 w-5 text-emerald-400" />}
|
||||
label="内存使用率"
|
||||
value={latest?.mem_usage != null ? `${latest.mem_usage.toFixed(1)}%` : '--'}
|
||||
color="emerald"
|
||||
detail={latest?.mem_total ? `${(latest.mem_used ?? 0).toFixed(1)} / ${latest.mem_total.toFixed(0)} GB` : undefined}
|
||||
/>
|
||||
<MetricCard
|
||||
icon={<Network className="h-5 w-5 text-purple-400" />}
|
||||
label="TCP 连接数"
|
||||
value={fmtNum(netInfo.tcp_established)}
|
||||
color="purple"
|
||||
detail={netInfo.tcp_time_wait != null ? `TIME_WAIT ${netInfo.tcp_time_wait}` : undefined}
|
||||
/>
|
||||
<MetricCard
|
||||
icon={<HardDrive className="h-5 w-5 text-orange-400" />}
|
||||
label="磁盘 IO"
|
||||
value={fmtBps((diskIOInfo.read_bps ?? 0) + (diskIOInfo.write_bps ?? 0))}
|
||||
color="orange"
|
||||
detail={diskIOInfo.read_iops != null ? `IOPS R${Math.round(diskIOInfo.read_iops)}/W${Math.round(diskIOInfo.write_iops ?? 0)}` : undefined}
|
||||
/>
|
||||
{/* 时间范围 */}
|
||||
<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>
|
||||
))}
|
||||
<Badge variant="outline" className="text-[10px] h-6">周期: 15秒</Badge>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* 趋势图 + 网络/磁盘 IO 面板 */}
|
||||
<div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
|
||||
{/* CPU / 内存趋势 */}
|
||||
<Card className="bg-[var(--dg-bg-secondary)] border-[var(--dg-border)]">
|
||||
<CardContent className="p-4">
|
||||
<div className="flex items-center gap-2 mb-4">
|
||||
<Activity className="h-4 w-4 text-[var(--dg-text-muted)]" />
|
||||
<h3 className="text-sm font-medium text-[var(--dg-text-primary)]">
|
||||
CPU / 内存 趋势(5m)
|
||||
</h3>
|
||||
</div>
|
||||
<div className="h-64">
|
||||
{chartLoading ? (
|
||||
<div className="h-full flex items-center justify-center">
|
||||
<Loader2 className="h-5 w-5 animate-spin text-slate-500" />
|
||||
</div>
|
||||
) : chartData.length === 0 ? (
|
||||
<div className="h-full flex items-center justify-center text-sm text-[var(--dg-text-muted)] border border-dashed border-[var(--dg-border)] rounded-lg">
|
||||
{selectedHost ? '暂无 K 线数据 — 请确认 Agent 已上报' : '请先选择主机'}
|
||||
</div>
|
||||
) : (
|
||||
<ResponsiveContainer width="100%" height="100%">
|
||||
<AreaChart data={chartData} margin={{ top: 5, right: 5, bottom: 0, left: -20 }}>
|
||||
<defs>
|
||||
<linearGradient id="hCpu" x1="0" y1="0" x2="0" y2="1">
|
||||
<stop offset="5%" stopColor="#3b82f6" stopOpacity={0.35} />
|
||||
<stop offset="95%" stopColor="#3b82f6" stopOpacity={0} />
|
||||
</linearGradient>
|
||||
<linearGradient id="hMem" x1="0" y1="0" x2="0" y2="1">
|
||||
<stop offset="5%" stopColor="#10b981" stopOpacity={0.35} />
|
||||
<stop offset="95%" stopColor="#10b981" stopOpacity={0} />
|
||||
</linearGradient>
|
||||
</defs>
|
||||
<CartesianGrid strokeDasharray="3 3" stroke="#1e293b" />
|
||||
<XAxis dataKey="time" stroke="#475569" fontSize={11} />
|
||||
<YAxis stroke="#475569" fontSize={11} domain={[0, 100]} />
|
||||
<Tooltip
|
||||
contentStyle={{
|
||||
backgroundColor: '#0f172a',
|
||||
border: '1px solid #1e293b',
|
||||
borderRadius: '6px',
|
||||
color: '#f8fafc',
|
||||
fontSize: '12px',
|
||||
}}
|
||||
/>
|
||||
<Area type="monotone" dataKey="cpu" stroke="#3b82f6" fill="url(#hCpu)" name="CPU %" />
|
||||
<Area type="monotone" dataKey="mem" stroke="#10b981" fill="url(#hMem)" name="内存 %" />
|
||||
</AreaChart>
|
||||
</ResponsiveContainer>
|
||||
)}
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
{/* 分类 Tab */}
|
||||
<Tabs value={activeTab} onValueChange={setActiveTab}>
|
||||
<TabsList className="h-8 bg-[var(--dg-bg-secondary)] border-[var(--dg-border)] gap-0">
|
||||
{[
|
||||
{ id: 'basic', label: '基础监控', icon: <Monitor className="w-3 h-3" />, desc: 'CPU/内存/负载' },
|
||||
{ id: 'disk', label: '磁盘监控', icon: <HardDrive className="w-3 h-3" />, desc: '使用率/IO' },
|
||||
{ id: 'network', label: '网络监控', icon: <Network className="w-3 h-3" />, desc: 'TCP/流量' },
|
||||
{ id: 'system', label: '系统信息', icon: <Info className="w-3 h-3" />, desc: 'OS/内核/运行时间' },
|
||||
].map(tab => (
|
||||
<TabsTrigger key={tab.id} value={tab.id} className="text-[11px] h-7 gap-1 data-[state=active]:bg-[var(--dg-bg-primary)]">
|
||||
{tab.icon}{tab.label}
|
||||
</TabsTrigger>
|
||||
))}
|
||||
</TabsList>
|
||||
|
||||
{/* 网络 / 磁盘 IO 速率面板 */}
|
||||
<Card className="bg-[var(--dg-bg-secondary)] border-[var(--dg-border)]">
|
||||
<CardContent className="p-4">
|
||||
<div className="flex items-center gap-2 mb-4">
|
||||
<Network className="h-4 w-4 text-[var(--dg-text-muted)]" />
|
||||
<h3 className="text-sm font-medium text-[var(--dg-text-primary)]">网络 / 磁盘 IO 实时速率</h3>
|
||||
</div>
|
||||
<div className="space-y-3">
|
||||
{/* 网卡 */}
|
||||
<div className="bg-[var(--dg-bg-primary)] rounded-lg p-3 border border-[var(--dg-border)]">
|
||||
<div className="text-xs text-[var(--dg-text-muted)] mb-2">
|
||||
网卡{netInfo.nic_name ? ` (${netInfo.nic_name})` : ''} — RX / TX
|
||||
</div>
|
||||
<div className="flex items-center gap-6">
|
||||
<RateItem label="↓ 接收" value={fmtBps(netInfo.net_rx_bps)} color="text-blue-400" />
|
||||
<RateItem label="↑ 发送" value={fmtBps(netInfo.net_tx_bps)} color="text-emerald-400" />
|
||||
</div>
|
||||
</div>
|
||||
{/* 磁盘 IO */}
|
||||
<div className="bg-[var(--dg-bg-primary)] rounded-lg p-3 border border-[var(--dg-border)]">
|
||||
<div className="text-xs text-[var(--dg-text-muted)] mb-2">磁盘 IO — 读 / 写</div>
|
||||
<div className="flex items-center gap-6">
|
||||
<RateItem label="读" value={fmtBps(diskIOInfo.read_bps)} color="text-orange-400" />
|
||||
<RateItem label="写" value={fmtBps(diskIOInfo.write_bps)} color="text-purple-400" />
|
||||
</div>
|
||||
</div>
|
||||
{/* CPU Load */}
|
||||
{latest && (
|
||||
<div className="bg-[var(--dg-bg-primary)] rounded-lg p-3 border border-[var(--dg-border)]">
|
||||
<div className="text-xs text-[var(--dg-text-muted)] mb-2">系统负载 (Load Average)</div>
|
||||
<div className="flex items-center gap-6">
|
||||
<span className="text-xs text-slate-500">1m</span>
|
||||
<span className="text-sm font-mono text-slate-300">{latest.load1 ?? '--'}</span>
|
||||
<span className="text-xs text-slate-500">5m</span>
|
||||
<span className="text-sm font-mono text-slate-300">{latest.load5 ?? '--'}</span>
|
||||
<span className="text-xs text-slate-500">15m</span>
|
||||
<span className="text-sm font-mono text-slate-300">{latest.load15 ?? '--'}</span>
|
||||
{/* ═══ 基础监控: CPU / 内存 / 负载 ═══ */}
|
||||
<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]}
|
||||
period={`周期: ${rangeHours <= 1 ? '15' : rangeHours <= 6 ? '1m' : '5m'}秒`}
|
||||
/>
|
||||
<MetricChartCard
|
||||
title="内存使用率(%)" value={currentVal('mem')} icon={<Server className="h-4 w-4 text-emerald-400" />}
|
||||
data={metrics.mem} color="#10b981" unit="%" domain={[0, 100]}
|
||||
period={`周期: ${rangeHours <= 1 ? '15' : rangeHours <= 6 ? '1m' : '5m'}秒`}
|
||||
/>
|
||||
<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']}
|
||||
period={`周期: ${rangeHours <= 1 ? '15' : rangeHours <= 6 ? '1m' : '5m'}秒`}
|
||||
/>
|
||||
</TabsContent>
|
||||
|
||||
{/* ═══ 磁盘监控: 使用率 / BPS / IOPS ═══ */}
|
||||
<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]}
|
||||
period={`周期: ${rangeHours <= 1 ? '15' : rangeHours <= 6 ? '1m' : '5m'}秒`}
|
||||
/>
|
||||
<MetricChartCard
|
||||
title="所有磁盘读取BPS(B/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']}
|
||||
period="平均值"
|
||||
/>
|
||||
<MetricChartCard
|
||||
title="所有磁盘写入BPS(B/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']}
|
||||
period="平均值"
|
||||
/>
|
||||
</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']}
|
||||
period="平均值"
|
||||
/>
|
||||
<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']}
|
||||
period="平均值"
|
||||
/>
|
||||
</div>
|
||||
</TabsContent>
|
||||
|
||||
{/* ═══ 网络监控: TCP连接 / 接收 / 发送 ═══ */}
|
||||
<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']}
|
||||
period={`ESTABLISHED / TIME_WAIT ${netInfo.tcp_time_wait || 0}`}
|
||||
/>
|
||||
<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']}
|
||||
period={netInfo.nic_name ? `网卡: ${netInfo.nic_name}` : '平均值'}
|
||||
/>
|
||||
<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']}
|
||||
period={netInfo.nic_name ? `网卡: ${netInfo.nic_name}` : '平均值'}
|
||||
/>
|
||||
</TabsContent>
|
||||
|
||||
{/* ═══ 系统信息 ═══ */}
|
||||
<TabsContent value="system" className="mt-3 space-y-3">
|
||||
<Card className="bg-[var(--dg-bg-secondary)] border-[var(--dg-border)]">
|
||||
<CardContent className="p-4">
|
||||
<div className="grid grid-cols-2 md:grid-cols-4 gap-x-6 gap-y-3 text-xs">
|
||||
{[
|
||||
['主机名', serverInfo?.hostname || selectedHost],
|
||||
['IP 地址', serverInfo?.ip || '—'],
|
||||
['操作系统', serverInfo?.os || '—'],
|
||||
['内核版本', serverInfo?.kernel || '—'],
|
||||
['CPU 核心数', serverInfo?.cpu_cores || '—'],
|
||||
['总内存', 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` : '—'],
|
||||
['监听端口数', portInfo.length > 0 ? `${portInfo.length}` : '—'],
|
||||
].map(([label, val]) => (
|
||||
<div key={label as string}>
|
||||
<span className="text-[var(--dg-text-muted)]">{label}:</span>
|
||||
<span className="text-[var(--dg-text-primary)] font-mono">{val}</span>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
{/* Load Average */}
|
||||
{latest && (
|
||||
<Card className="bg-[var(--dg-bg-secondary)] border-[var(--dg-border)]">
|
||||
<CardContent className="p-4">
|
||||
<div className="flex items-center gap-2 mb-2">
|
||||
<Activity className="h-4 w-4 text-[var(--dg-text-muted)]" />
|
||||
<h3 className="text-xs font-medium text-[var(--dg-text-primary)]">系统负载 (Load Average)</h3>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
</div>
|
||||
<div className="flex items-center gap-6 text-xs">
|
||||
<div><span className="text-[var(--dg-text-muted)]">1min </span><span className="text-sm font-bold text-slate-200">{latest.load1 ?? '--'}</span></div>
|
||||
<div><span className="text-[var(--dg-text-muted)]">5min </span><span className="text-sm font-bold text-slate-200">{latest.load5 ?? '--'}</span></div>
|
||||
<div><span className="text-[var(--dg-text-muted)]">15min </span><span className="text-sm font-bold text-slate-200">{latest.load15 ?? '--'}</span></div>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
)}
|
||||
|
||||
{/* 磁盘分区详情 */}
|
||||
{latest?.disk_info && (() => {
|
||||
const disk = parseJSON(latest.disk_info);
|
||||
const parts = disk.partitions || [];
|
||||
if (!parts.length) return null;
|
||||
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>
|
||||
<div className="space-y-1.5">
|
||||
{parts.map((p: any, i: number) => (
|
||||
<div key={i} className="flex items-center gap-2 text-xs">
|
||||
<span className="text-[var(--dg-text-muted)] w-24 font-mono truncate">{p.mountpoint || p.path}</span>
|
||||
<div className="flex-1 h-1.5 bg-slate-700 rounded-full overflow-hidden">
|
||||
<div className="h-full rounded-full bg-blue-500" style={{ width: `${Math.min(p.used_percent || 0, 100)}%` }} />
|
||||
</div>
|
||||
<span className="text-[var(--dg-text-primary)] w-20 text-right tabular-nums">{p.used || '?'}/{p.total || '?'}</span>
|
||||
<span className="text-blue-400 w-12 text-right tabular-nums">{p.used_percent || 0}%</span>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</CardContent>
|
||||
</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/LN:</span><span className="text-[var(--dg-text-primary)] font-mono">{netInfo.tcp_established || 0}/{netInfo.tcp_time_wait || 0}/{netInfo.tcp_listen || 0}</span></div>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
)}
|
||||
</TabsContent>
|
||||
</Tabs>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
/** 概览卡片 */
|
||||
function MetricCard({
|
||||
icon,
|
||||
label,
|
||||
value,
|
||||
color,
|
||||
detail,
|
||||
// ═══════ 指标图表卡片 ═══════
|
||||
function MetricChartCard({
|
||||
title, value, icon, data, color, unit, domain, period,
|
||||
}: {
|
||||
icon: React.ReactNode;
|
||||
label: string;
|
||||
value: string;
|
||||
color: string;
|
||||
detail?: string;
|
||||
title: string; value: string; icon: React.ReactNode; data: { time: string; value: number }[];
|
||||
color: string; unit: string; domain: [number, number | 'auto']; period: string;
|
||||
}) {
|
||||
return (
|
||||
<Card className="bg-[var(--dg-bg-secondary)] border-[var(--dg-border)]">
|
||||
<CardContent className="p-4">
|
||||
<div className="flex items-center gap-3">
|
||||
<div className={`w-10 h-10 rounded-lg flex items-center justify-center ${colorMap[color] ?? 'bg-slate-500/10'}`}>
|
||||
<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>
|
||||
<div className="min-w-0 flex-1">
|
||||
<p className="text-xs text-[var(--dg-text-muted)] truncate">{label}</p>
|
||||
<p className="text-xl font-bold text-[var(--dg-text-primary)]">{value}</p>
|
||||
{detail && (
|
||||
<p className="text-xs text-[var(--dg-text-muted)] truncate">{detail}</p>
|
||||
)}
|
||||
</div>
|
||||
<span className="text-[10px] text-[var(--dg-text-muted)]">{period}</span>
|
||||
</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>
|
||||
|
||||
{/* 趋势图 */}
|
||||
<div className="h-36">
|
||||
{data.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>
|
||||
) : (
|
||||
<ResponsiveContainer width="100%" height="100%">
|
||||
<AreaChart data={data} margin={{ top: 2, right: 2, bottom: 0, left: -10 }}>
|
||||
<defs>
|
||||
<linearGradient id={`grad-${title}`} x1="0" y1="0" x2="0" y2="1">
|
||||
<stop offset="5%" stopColor={color} stopOpacity={0.3} />
|
||||
<stop offset="95%" stopColor={color} stopOpacity={0} />
|
||||
</linearGradient>
|
||||
</defs>
|
||||
<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',
|
||||
}}
|
||||
formatter={(v: number) => [`${v.toFixed(2)} ${unit}`, title.replace(/\(.+\)/, '')]}
|
||||
/>
|
||||
<Area type="monotone" dataKey="value" stroke={color} strokeWidth={1.5} fill={`url(#grad-${title})`} />
|
||||
</AreaChart>
|
||||
</ResponsiveContainer>
|
||||
)}
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
);
|
||||
}
|
||||
|
||||
/** 速率标签 */
|
||||
function RateItem({ label, value, color }: { label: string; value: string; color: string }) {
|
||||
return (
|
||||
<div className="flex items-center gap-1.5">
|
||||
<span className="text-xs text-slate-500">{label}</span>
|
||||
<span className={`text-sm font-mono font-medium ${color}`}>{value}</span>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export default HostMonitor;
|
||||
|
||||
/** Top N 排行卡片 */
|
||||
function TopRankCard({
|
||||
title, icon, data, valueKey, unit, color,
|
||||
}: {
|
||||
title: string; icon: React.ReactNode; data: any[]; valueKey: string; unit: string; color: string;
|
||||
}) {
|
||||
const barColors: Record<string, string> = { red: 'bg-red-500', amber: 'bg-amber-500', orange: 'bg-orange-500', emerald: 'bg-emerald-500' };
|
||||
const barColor = barColors[color] || 'bg-red-500';
|
||||
|
||||
return (
|
||||
<Card className="bg-[var(--dg-bg-secondary)] border-[var(--dg-border)]">
|
||||
<CardContent className="p-3">
|
||||
<div className="flex items-center gap-2 mb-2">
|
||||
{icon}
|
||||
<h3 className="text-xs font-medium text-[var(--dg-text-primary)]">{title}</h3>
|
||||
</div>
|
||||
{data.length === 0 ? (
|
||||
<p className="text-xs text-[var(--dg-text-muted)] py-4 text-center">暂无数据</p>
|
||||
) : (
|
||||
<div className="space-y-1.5">
|
||||
{data.map((item: any, i: number) => {
|
||||
const val = Number(item[valueKey] || 0);
|
||||
const barPct = Math.min(val, 100);
|
||||
return (
|
||||
<div key={i} className="flex items-center gap-2 text-xs">
|
||||
<span className="w-4 text-[var(--dg-text-muted)] font-mono text-right">{i + 1}</span>
|
||||
<span className="w-24 truncate text-[var(--dg-text-secondary)]" title={item.hostname}>{item.hostname}</span>
|
||||
<div className="flex-1 h-1.5 rounded-full bg-[var(--dg-bg-tertiary)] overflow-hidden">
|
||||
<div
|
||||
className={`h-full rounded-full ${barColor} transition-all`}
|
||||
style={{ width: `${barPct}%` }}
|
||||
/>
|
||||
</div>
|
||||
<span className="w-12 text-right font-mono text-[var(--dg-text-primary)]">{val.toFixed(1)}{unit}</span>
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
)}
|
||||
</CardContent>
|
||||
</Card>
|
||||
);
|
||||
}
|
||||
Reference in new issue
Block a user