- 后端 GetMetrics 修复 strftime 字符串无法扫入 time.Time 导致 timestamp 为零值的 bug (改为 string 类型 + time.ParseInLocation 手动解析) - 前端 Dashboard.tsx 新增 getMetrics(24) 调用,获取真实按小时聚合的 Agent 数据 - DashboardCharts.tsx 新增 buildMetricsFromReal() 将 MetricData[] 转换为图表数据 - ResourceUsageCard 优先使用真实时间序列,无数据时回退到平均值生成
379 lines
14 KiB
TypeScript
379 lines
14 KiB
TypeScript
import { Card, CardContent, CardHeader, CardTitle, CardDescription } from '@/components/ui/card';
|
|
import { Badge } from '@/components/ui/badge';
|
|
import {
|
|
AreaChart,
|
|
Area,
|
|
XAxis,
|
|
YAxis,
|
|
CartesianGrid,
|
|
Tooltip,
|
|
ResponsiveContainer,
|
|
PieChart,
|
|
Pie,
|
|
Cell,
|
|
BarChart,
|
|
Bar,
|
|
} from 'recharts';
|
|
import { Cpu, HardDrive, Activity, MemoryStick, Database } from 'lucide-react';
|
|
|
|
// 云平台颜色映射
|
|
const CLOUD_COLORS: Record<string, string> = {
|
|
'阿里云': '#ff6a00',
|
|
aliyun: '#ff6a00',
|
|
AWS: '#ff9900',
|
|
aws: '#ff9900',
|
|
'腾讯云': '#006eff',
|
|
tencent: '#006eff',
|
|
'华为云': '#ff0000',
|
|
huawei: '#ff0000',
|
|
Azure: '#0078d4',
|
|
azure: '#0078d4',
|
|
};
|
|
const FALLBACK_CLOUD_COLORS = ['#ff6a00', '#ff9900', '#006eff', '#ff0000', '#0078d4', '#10b981', '#a855f7', '#ec4899'];
|
|
|
|
// 计算月度环比变化(基于 month_trend 最后两个月)
|
|
export function computeMonthChange(monthTrend: any[]): {
|
|
pct: number;
|
|
label: string;
|
|
direction: 'up' | 'down' | 'neutral';
|
|
} {
|
|
if (!monthTrend || monthTrend.length < 2) {
|
|
return { pct: 0, label: '暂无数据', direction: 'neutral' };
|
|
}
|
|
const cur = Number(monthTrend[monthTrend.length - 1].cost ?? 0);
|
|
const prev = Number(monthTrend[monthTrend.length - 2].cost ?? 0);
|
|
if (prev === 0) {
|
|
return { pct: 0, label: cur > 0 ? '新增费用' : '持平', direction: 'neutral' };
|
|
}
|
|
const pct = ((cur - prev) / prev) * 100;
|
|
const direction = pct > 0.05 ? 'up' : pct < -0.05 ? 'down' : 'neutral';
|
|
const label = `${pct > 0 ? '+' : ''}${pct.toFixed(1)}% 较上月`;
|
|
return { pct, label, direction };
|
|
}
|
|
|
|
// 根据平均值生成24小时趋势数据(无实时指标时使用)
|
|
function generateMetricsData(avgCpu: number, avgMemory: number, avgDisk: number, points = 24) {
|
|
const data = [];
|
|
for (let i = points - 1; i >= 0; i--) {
|
|
const d = new Date(Date.now() - i * 60 * 60 * 1000);
|
|
data.push({
|
|
time: `${d.getHours().toString().padStart(2, '0')}:00`,
|
|
cpu: Number(Math.max(0, avgCpu + (Math.random() - 0.5) * 15).toFixed(1)),
|
|
memory: Number(Math.max(0, avgMemory + (Math.random() - 0.5) * 10).toFixed(1)),
|
|
disk: Number(Math.max(0, avgDisk + (Math.random() - 0.5) * 5).toFixed(1)),
|
|
});
|
|
}
|
|
return data;
|
|
}
|
|
|
|
// 成本费用卡片
|
|
export function CostOverviewCard({ costStats }: { costStats: any }) {
|
|
const cloudCosts: any[] = costStats?.cloud_costs ?? [];
|
|
const monthTrend: any[] = costStats?.month_trend ?? [];
|
|
|
|
const costData = cloudCosts.map((c, i) => ({
|
|
name: c.cloud,
|
|
value: c.cost,
|
|
color: CLOUD_COLORS[c.cloud] || FALLBACK_CLOUD_COLORS[i % FALLBACK_CLOUD_COLORS.length],
|
|
}));
|
|
const monthlyData = monthTrend.map((m) => ({ month: m.month, cost: m.cost }));
|
|
const totalCost =
|
|
costStats?.total_cost ?? costData.reduce((sum, item) => sum + item.value, 0);
|
|
const costChange = computeMonthChange(monthTrend);
|
|
|
|
return (
|
|
<Card className="bg-slate-900 border-slate-800">
|
|
<CardHeader className="pb-2">
|
|
<div className="flex items-center justify-between">
|
|
<div>
|
|
<CardTitle className="text-slate-100">云成本概览</CardTitle>
|
|
<CardDescription className="text-slate-500">本月各云平台费用支出</CardDescription>
|
|
</div>
|
|
<div className="text-right">
|
|
<p className="text-2xl font-bold text-slate-100">¥{Number(totalCost).toLocaleString()}</p>
|
|
<p className={`text-xs ${
|
|
costChange.direction === 'up'
|
|
? 'text-emerald-400'
|
|
: costChange.direction === 'down'
|
|
? 'text-red-400'
|
|
: 'text-slate-500'
|
|
}`}>
|
|
{costChange.label}
|
|
</p>
|
|
</div>
|
|
</div>
|
|
</CardHeader>
|
|
<CardContent>
|
|
<div className="grid grid-cols-2 gap-4">
|
|
<div>
|
|
<p className="text-sm text-slate-400 mb-2">费用分布</p>
|
|
<div className="h-[180px]">
|
|
<ResponsiveContainer width="100%" height="100%">
|
|
<PieChart>
|
|
<Pie
|
|
data={costData}
|
|
cx="50%"
|
|
cy="50%"
|
|
innerRadius={40}
|
|
outerRadius={70}
|
|
paddingAngle={2}
|
|
dataKey="value"
|
|
>
|
|
{costData.map((entry, index) => (
|
|
<Cell key={`cell-${index}`} fill={entry.color} />
|
|
))}
|
|
</Pie>
|
|
<Tooltip
|
|
contentStyle={{
|
|
backgroundColor: '#0f172a',
|
|
border: '1px solid #1e293b',
|
|
borderRadius: '6px',
|
|
color: '#f8fafc',
|
|
}}
|
|
formatter={(value: number) => `¥${value.toLocaleString()}`}
|
|
/>
|
|
</PieChart>
|
|
</ResponsiveContainer>
|
|
</div>
|
|
</div>
|
|
<div>
|
|
<p className="text-sm text-slate-400 mb-2">月度趋势</p>
|
|
<div className="h-[180px]">
|
|
<ResponsiveContainer width="100%" height="100%">
|
|
<BarChart data={monthlyData} margin={{ top: 5, right: 5, left: 0, bottom: 5 }}>
|
|
<CartesianGrid strokeDasharray="3 3" stroke="#1e293b" />
|
|
<XAxis dataKey="month" stroke="#475569" fontSize={10} tickLine={false} axisLine={false} />
|
|
<YAxis stroke="#475569" fontSize={10} tickLine={false} axisLine={false} />
|
|
<Tooltip
|
|
contentStyle={{
|
|
backgroundColor: '#0f172a',
|
|
border: '1px solid #1e293b',
|
|
borderRadius: '6px',
|
|
color: '#f8fafc',
|
|
}}
|
|
formatter={(value: number) => `¥${value.toLocaleString()}`}
|
|
/>
|
|
<Bar dataKey="cost" fill="#3b82f6" radius={[4, 4, 0, 0]} />
|
|
</BarChart>
|
|
</ResponsiveContainer>
|
|
</div>
|
|
</div>
|
|
</div>
|
|
<div className="mt-4 space-y-2">
|
|
{costData.map((item) => (
|
|
<div key={item.name} className="flex items-center justify-between">
|
|
<div className="flex items-center gap-2">
|
|
<div className="w-3 h-3 rounded-full" style={{ backgroundColor: item.color }} />
|
|
<span className="text-sm text-slate-300">{item.name}</span>
|
|
</div>
|
|
<span className="text-sm font-medium text-slate-100">¥{Number(item.value).toLocaleString()}</span>
|
|
</div>
|
|
))}
|
|
</div>
|
|
</CardContent>
|
|
</Card>
|
|
);
|
|
}
|
|
|
|
// Top5 资源使用卡片
|
|
export function TopResourceUsageCard({ topUsage }: { topUsage: any }) {
|
|
const topCpuServers = (topUsage?.cpu ?? []).slice(0, 5);
|
|
const topMemoryServers = (topUsage?.memory ?? []).slice(0, 5);
|
|
const topDiskServers = (topUsage?.disk ?? []).slice(0, 5);
|
|
|
|
const renderList = (
|
|
items: any[],
|
|
color: string,
|
|
BarColor: string,
|
|
icon: React.ReactNode,
|
|
label: string
|
|
) => (
|
|
<div>
|
|
<div className="flex items-center gap-2 mb-3">
|
|
{icon}
|
|
<span className="text-sm font-medium text-slate-300">{label}</span>
|
|
</div>
|
|
<div className="space-y-2">
|
|
{items.map((item, index) => {
|
|
const usage = Number(item.usage ?? 0);
|
|
return (
|
|
<div key={item.id ?? index} className="flex items-center gap-2">
|
|
<span className="text-xs text-slate-500 w-4">{index + 1}</span>
|
|
<div className="flex-1 min-w-0">
|
|
<p className="text-xs text-slate-300 truncate">{item.hostname}</p>
|
|
<div className="flex items-center gap-2">
|
|
<div className="flex-1 h-1.5 bg-slate-700 rounded-full overflow-hidden">
|
|
<div
|
|
className={`h-full rounded-full ${
|
|
usage > 80 ? 'bg-red-400' : usage > 60 ? 'bg-amber-400' : BarColor
|
|
}`}
|
|
style={{ width: `${usage}%` }}
|
|
/>
|
|
</div>
|
|
<span className={`text-xs ${
|
|
usage > 80 ? 'text-red-400' : usage > 60 ? 'text-amber-400' : 'text-slate-400'
|
|
}`}>
|
|
{usage.toFixed(1)}%
|
|
</span>
|
|
</div>
|
|
</div>
|
|
</div>
|
|
);
|
|
})}
|
|
</div>
|
|
</div>
|
|
);
|
|
|
|
return (
|
|
<Card className="bg-slate-900 border-slate-800">
|
|
<CardHeader className="pb-2">
|
|
<div className="flex items-center justify-between">
|
|
<div>
|
|
<CardTitle className="text-slate-100">Top5 资源使用</CardTitle>
|
|
<CardDescription className="text-slate-500">CPU、内存、磁盘使用率最高</CardDescription>
|
|
</div>
|
|
</div>
|
|
</CardHeader>
|
|
<CardContent>
|
|
<div className="grid grid-cols-3 gap-4">
|
|
{/* CPU Top5 */}
|
|
{renderList(topCpuServers, 'blue', 'bg-blue-400', <Cpu className="h-4 w-4 text-blue-400" />, 'CPU')}
|
|
{/* Memory Top5 */}
|
|
{renderList(topMemoryServers, 'emerald', 'bg-emerald-400', <MemoryStick className="h-4 w-4 text-emerald-400" />, '内存')}
|
|
{/* Disk Top5 */}
|
|
{renderList(topDiskServers, 'purple', 'bg-purple-400', <Database className="h-4 w-4 text-purple-400" />, '磁盘')}
|
|
</div>
|
|
</CardContent>
|
|
</Card>
|
|
);
|
|
}
|
|
|
|
// 将后端 MetricData[] 时间序列转换为图表所需格式 { time, cpu, memory } // Logan.Li
|
|
function buildMetricsFromReal(metrics: any[], avgDisk: number): { time: string; cpu: number; memory: number; disk: number }[] {
|
|
if (!metrics || metrics.length === 0) return [];
|
|
// 按 timestamp 分组:同一时刻有 cpu + memory 两条记录
|
|
const buckets: Record<string, { cpu?: number; memory?: number }> = {};
|
|
for (const m of metrics) {
|
|
const ts = m.timestamp;
|
|
if (!ts) continue;
|
|
// 提取 HH:MM 格式作为 X 轴标签
|
|
const d = new Date(ts);
|
|
const label = `${d.getHours().toString().padStart(2, '0')}:00`;
|
|
if (!buckets[label]) buckets[label] = {};
|
|
if (m.name === 'cpu') buckets[label].cpu = Number(m.value) || 0;
|
|
if (m.name === 'memory') buckets[label].memory = Number(m.value) || 0;
|
|
}
|
|
return Object.entries(buckets)
|
|
.sort((a, b) => a[0].localeCompare(b[0]))
|
|
.map(([time, v]) => ({
|
|
time,
|
|
cpu: Number((v.cpu ?? 0).toFixed(1)),
|
|
memory: Number((v.memory ?? 0).toFixed(1)),
|
|
disk: Number(avgDisk.toFixed(1)), // 磁盘无历史序列,用平均值
|
|
}));
|
|
}
|
|
|
|
// 资源使用率趋势卡片
|
|
export function ResourceUsageCard({
|
|
avgCpu,
|
|
avgMemory,
|
|
avgDisk,
|
|
metrics,
|
|
}: {
|
|
avgCpu: number;
|
|
avgMemory: number;
|
|
avgDisk: number;
|
|
metrics?: any[];
|
|
}) {
|
|
// 优先使用真实 Agent 指标时间序列;无数据时回退到平均值生成(带随机波动) // Logan.Li
|
|
const realData = buildMetricsFromReal(metrics ?? [], avgDisk);
|
|
const data = realData.length > 0 ? realData : generateMetricsData(avgCpu, avgMemory, avgDisk, 24);
|
|
|
|
return (
|
|
<Card className="bg-slate-900 border-slate-800">
|
|
<CardHeader className="pb-2">
|
|
<div className="flex items-center justify-between">
|
|
<div>
|
|
<CardTitle className="text-slate-100">资源使用率趋势</CardTitle>
|
|
<CardDescription className="text-slate-500">过去24小时系统资源使用情况</CardDescription>
|
|
</div>
|
|
<div className="flex items-center gap-2">
|
|
<Badge variant="outline" className="border-blue-500/30 text-blue-400 bg-blue-500/10">
|
|
<Cpu className="h-3 w-3 mr-1" />
|
|
CPU
|
|
</Badge>
|
|
<Badge variant="outline" className="border-emerald-500/30 text-emerald-400 bg-emerald-500/10">
|
|
<Activity className="h-3 w-3 mr-1" />
|
|
内存
|
|
</Badge>
|
|
<Badge variant="outline" className="border-purple-500/30 text-purple-400 bg-purple-500/10">
|
|
<HardDrive className="h-3 w-3 mr-1" />
|
|
磁盘
|
|
</Badge>
|
|
</div>
|
|
</div>
|
|
</CardHeader>
|
|
<CardContent>
|
|
<div className="h-[280px]">
|
|
<ResponsiveContainer width="100%" height="100%">
|
|
<AreaChart data={data} margin={{ top: 10, right: 10, left: 0, bottom: 0 }}>
|
|
<defs>
|
|
<linearGradient id="colorCpu" x1="0" y1="0" x2="0" y2="1">
|
|
<stop offset="5%" stopColor="#3b82f6" stopOpacity={0.3} />
|
|
<stop offset="95%" stopColor="#3b82f6" stopOpacity={0} />
|
|
</linearGradient>
|
|
<linearGradient id="colorMemory" x1="0" y1="0" x2="0" y2="1">
|
|
<stop offset="5%" stopColor="#10b981" stopOpacity={0.3} />
|
|
<stop offset="95%" stopColor="#10b981" stopOpacity={0} />
|
|
</linearGradient>
|
|
<linearGradient id="colorDisk" x1="0" y1="0" x2="0" y2="1">
|
|
<stop offset="5%" stopColor="#a855f7" stopOpacity={0.3} />
|
|
<stop offset="95%" stopColor="#a855f7" stopOpacity={0} />
|
|
</linearGradient>
|
|
</defs>
|
|
<CartesianGrid strokeDasharray="3 3" stroke="#1e293b" />
|
|
<XAxis dataKey="time" stroke="#475569" fontSize={12} tickLine={false} axisLine={false} />
|
|
<YAxis stroke="#475569" fontSize={12} tickLine={false} axisLine={false} unit="%" />
|
|
<Tooltip
|
|
contentStyle={{
|
|
backgroundColor: '#0f172a',
|
|
border: '1px solid #1e293b',
|
|
borderRadius: '6px',
|
|
color: '#f8fafc',
|
|
}}
|
|
/>
|
|
<Area
|
|
type="monotone"
|
|
dataKey="cpu"
|
|
stroke="#3b82f6"
|
|
fillOpacity={1}
|
|
fill="url(#colorCpu)"
|
|
strokeWidth={2}
|
|
name="CPU"
|
|
/>
|
|
<Area
|
|
type="monotone"
|
|
dataKey="memory"
|
|
stroke="#10b981"
|
|
fillOpacity={1}
|
|
fill="url(#colorMemory)"
|
|
strokeWidth={2}
|
|
name="内存"
|
|
/>
|
|
<Area
|
|
type="monotone"
|
|
dataKey="disk"
|
|
stroke="#a855f7"
|
|
fillOpacity={1}
|
|
fill="url(#colorDisk)"
|
|
strokeWidth={2}
|
|
name="磁盘"
|
|
/>
|
|
</AreaChart>
|
|
</ResponsiveContainer>
|
|
</div>
|
|
</CardContent>
|
|
</Card>
|
|
);
|
|
}
|