543 lines
23 KiB
TypeScript
543 lines
23 KiB
TypeScript
import { useState, useEffect, useCallback } from 'react';
|
|
import { toast } from 'sonner';
|
|
import { useConfirm } from '@/components/ui/confirm-dialog';
|
|
import { agentApi } from '@/services/api';
|
|
import { Card, CardContent } from '@/components/ui/card';
|
|
import { Button } from '@/components/ui/button';
|
|
import { Input } from '@/components/ui/input';
|
|
import { Label } from '@/components/ui/label';
|
|
import { Badge } from '@/components/ui/badge';
|
|
import { Switch } from '@/components/ui/switch';
|
|
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs';
|
|
import {
|
|
Dialog,
|
|
DialogContent,
|
|
DialogDescription,
|
|
DialogFooter,
|
|
DialogHeader,
|
|
DialogTitle,
|
|
} from '@/components/ui/dialog';
|
|
import {
|
|
Select,
|
|
SelectContent,
|
|
SelectItem,
|
|
SelectTrigger,
|
|
SelectValue,
|
|
} from '@/components/ui/select';
|
|
import {
|
|
AlertTriangle,
|
|
CheckCircle,
|
|
Plus,
|
|
Pencil,
|
|
Trash2,
|
|
Loader2,
|
|
RefreshCw,
|
|
Bell,
|
|
Cpu,
|
|
MemoryStick,
|
|
HardDrive,
|
|
WifiOff,
|
|
Network,
|
|
Clock,
|
|
} from 'lucide-react';
|
|
|
|
// ============ 常量 ============
|
|
|
|
const METRIC_OPTIONS = [
|
|
{ value: 'cpu', label: 'CPU', icon: Cpu },
|
|
{ value: 'mem', label: '内存', icon: MemoryStick },
|
|
{ value: 'disk', label: '磁盘', icon: HardDrive },
|
|
{ value: 'offline', label: '主机离线', icon: WifiOff },
|
|
{ value: 'port_down', label: '端口不通', icon: Network },
|
|
];
|
|
|
|
const OPERATOR_OPTIONS = [
|
|
{ value: '>', label: '> 大于' },
|
|
{ value: '<', label: '< 小于' },
|
|
{ value: '>=', label: '≥ 大于等于' },
|
|
{ value: '<=', label: '≤ 小于等于' },
|
|
{ value: '==', label: '= 等于' },
|
|
];
|
|
|
|
const SEVERITY_OPTIONS = [
|
|
{ value: 'critical', label: '严重', color: 'bg-red-500/15 text-red-400 border-red-500/30' },
|
|
{ value: 'warning', label: '警告', color: 'bg-amber-500/15 text-amber-400 border-amber-500/30' },
|
|
{ value: 'info', label: '提示', color: 'bg-blue-500/15 text-blue-400 border-blue-500/30' },
|
|
];
|
|
|
|
function getMetricLabel(metric: string) {
|
|
return METRIC_OPTIONS.find((m) => m.value === metric)?.label || metric;
|
|
}
|
|
|
|
function asList(data: any): any[] {
|
|
if (!data) return [];
|
|
if (Array.isArray(data)) return data;
|
|
if (Array.isArray(data.list)) return data.list;
|
|
if (Array.isArray(data.items)) return data.items;
|
|
if (Array.isArray(data.data)) return data.data;
|
|
return [];
|
|
}
|
|
|
|
// ============ 主组件 ============
|
|
|
|
export function AgentAlerts() {
|
|
const confirm = useConfirm();
|
|
const [activeTab, setActiveTab] = useState('events');
|
|
const [alerts, setAlerts] = useState<any[]>([]);
|
|
const [rules, setRules] = useState<any[]>([]);
|
|
const [loading, setLoading] = useState(true);
|
|
const [resolvedView, setResolvedView] = useState(false);
|
|
|
|
// 规则编辑
|
|
const [ruleOpen, setRuleOpen] = useState(false);
|
|
const [editingRule, setEditingRule] = useState<any>(null);
|
|
const [ruleSaving, setRuleSaving] = useState(false);
|
|
const [ruleForm, setRuleForm] = useState({
|
|
name: '',
|
|
metric: 'cpu',
|
|
operator: '>',
|
|
threshold: '90',
|
|
port: '',
|
|
severity: 'warning',
|
|
enabled: true,
|
|
duration: '60',
|
|
});
|
|
|
|
const loadData = useCallback(async () => {
|
|
setLoading(true);
|
|
try {
|
|
const [alertsRes, rulesRes] = await Promise.all([
|
|
agentApi.listAlerts({ resolved: String(resolvedView) }),
|
|
agentApi.listRules(),
|
|
]);
|
|
setAlerts(asList(alertsRes));
|
|
setRules(asList(rulesRes));
|
|
} catch (err) {
|
|
console.error(err);
|
|
toast.error('加载告警数据失败');
|
|
} finally {
|
|
setLoading(false);
|
|
}
|
|
}, [resolvedView]);
|
|
|
|
useEffect(() => {
|
|
loadData();
|
|
}, [loadData]);
|
|
|
|
// ============ 告警事件 ============
|
|
const handleResolve = async (id: number) => {
|
|
const ok = await confirm({ title: '恢复告警', description: '确定将此告警标记为已恢复?', confirmText: '恢复' });
|
|
if (!ok) return;
|
|
try {
|
|
await agentApi.resolveAlert(id);
|
|
toast.success('告警已恢复');
|
|
loadData();
|
|
} catch (err: any) {
|
|
toast.error(err?.message || '操作失败');
|
|
}
|
|
};
|
|
|
|
// ============ 规则 CRUD ============
|
|
const resetRuleForm = () => {
|
|
setRuleForm({ name: '', metric: 'cpu', operator: '>', threshold: '90', port: '', severity: 'warning', enabled: true, duration: '60' });
|
|
setEditingRule(null);
|
|
};
|
|
|
|
const openCreateRule = () => {
|
|
resetRuleForm();
|
|
setRuleOpen(true);
|
|
};
|
|
|
|
const openEditRule = (rule: any) => {
|
|
setEditingRule(rule);
|
|
setRuleForm({
|
|
name: rule.name || '',
|
|
metric: rule.metric || 'cpu',
|
|
operator: rule.operator || '>',
|
|
threshold: String(rule.threshold ?? '90'),
|
|
port: rule.port ? String(rule.port) : '',
|
|
severity: rule.severity || 'warning',
|
|
enabled: rule.enabled !== false,
|
|
duration: rule.duration ? String(rule.duration) : '60',
|
|
});
|
|
setRuleOpen(true);
|
|
};
|
|
|
|
const handleSaveRule = async () => {
|
|
if (!ruleForm.name.trim()) {
|
|
toast.error('请输入规则名称');
|
|
return;
|
|
}
|
|
setRuleSaving(true);
|
|
try {
|
|
const payload: any = {
|
|
name: ruleForm.name.trim(),
|
|
metric: ruleForm.metric,
|
|
operator: ruleForm.operator,
|
|
threshold: Number(ruleForm.threshold) || 0,
|
|
severity: ruleForm.severity,
|
|
enabled: ruleForm.enabled,
|
|
duration: Number(ruleForm.duration) || 0,
|
|
};
|
|
if (ruleForm.metric === 'port_down' && ruleForm.port) {
|
|
payload.port = Number(ruleForm.port);
|
|
}
|
|
if (editingRule) {
|
|
await agentApi.updateRule(editingRule.id, payload);
|
|
toast.success('规则已更新');
|
|
} else {
|
|
await agentApi.createRule(payload);
|
|
toast.success('规则已创建');
|
|
}
|
|
setRuleOpen(false);
|
|
resetRuleForm();
|
|
loadData();
|
|
} catch (err: any) {
|
|
toast.error(err?.message || '保存失败');
|
|
} finally {
|
|
setRuleSaving(false);
|
|
}
|
|
};
|
|
|
|
const handleDeleteRule = async (id: number) => {
|
|
const ok = await confirm({ title: '删除规则', description: '确定删除此告警规则?', confirmText: '删除', variant: 'destructive' });
|
|
if (!ok) return;
|
|
try {
|
|
await agentApi.deleteRule(id);
|
|
toast.success('规则已删除');
|
|
loadData();
|
|
} catch (err: any) {
|
|
toast.error(err?.message || '删除失败');
|
|
}
|
|
};
|
|
|
|
const handleToggleRule = async (rule: any) => {
|
|
try {
|
|
await agentApi.updateRule(rule.id, { ...rule, enabled: !rule.enabled });
|
|
loadData();
|
|
} catch (err: any) {
|
|
toast.error(err?.message || '操作失败');
|
|
}
|
|
};
|
|
|
|
const severityBadge = (sev: string) => {
|
|
const opt = SEVERITY_OPTIONS.find((s) => s.value === sev) || SEVERITY_OPTIONS[1];
|
|
return (
|
|
<Badge className={opt.color}>
|
|
<AlertTriangle className="h-3 w-3 mr-1" />
|
|
{opt.label}
|
|
</Badge>
|
|
);
|
|
};
|
|
|
|
return (
|
|
<div className="space-y-4">
|
|
{/* 页头 */}
|
|
<div className="flex items-center justify-between">
|
|
<div>
|
|
<h2 className="text-xl font-semibold text-slate-100">Agent 告警</h2>
|
|
<p className="text-sm text-slate-400 mt-0.5">基于 Agent 上报指标的告警规则与事件</p>
|
|
</div>
|
|
<Button variant="outline" size="sm" onClick={loadData} disabled={loading} className="bg-slate-800 border-slate-700 text-slate-300 hover:bg-slate-700">
|
|
<RefreshCw className={`h-4 w-4 mr-1.5 ${loading ? 'animate-spin' : ''}`} />
|
|
刷新
|
|
</Button>
|
|
</div>
|
|
|
|
<Tabs value={activeTab} onValueChange={setActiveTab} className="w-full">
|
|
<TabsList className="bg-slate-800 border border-slate-700">
|
|
<TabsTrigger value="events" className="data-[state=active]:bg-slate-700">告警事件</TabsTrigger>
|
|
<TabsTrigger value="rules" className="data-[state=active]:bg-slate-700">告警规则</TabsTrigger>
|
|
</TabsList>
|
|
|
|
{/* ========== 告警事件 ========== */}
|
|
<TabsContent value="events" className="mt-4 space-y-3">
|
|
<div className="flex items-center gap-2">
|
|
<Button
|
|
size="sm"
|
|
variant={resolvedView ? 'outline' : 'default'}
|
|
onClick={() => setResolvedView(false)}
|
|
className={!resolvedView ? 'bg-blue-600 hover:bg-blue-700 text-white' : 'bg-slate-800 border-slate-700 text-slate-300'}
|
|
>
|
|
未恢复
|
|
</Button>
|
|
<Button
|
|
size="sm"
|
|
variant={resolvedView ? 'default' : 'outline'}
|
|
onClick={() => setResolvedView(true)}
|
|
className={resolvedView ? 'bg-blue-600 hover:bg-blue-700 text-white' : 'bg-slate-800 border-slate-700 text-slate-300'}
|
|
>
|
|
已恢复
|
|
</Button>
|
|
</div>
|
|
|
|
{loading ? (
|
|
<Card className="bg-slate-900 border-slate-800">
|
|
<CardContent className="flex items-center justify-center py-16">
|
|
<Loader2 className="h-5 w-5 animate-spin text-slate-500" />
|
|
<span className="ml-2 text-slate-400">加载中...</span>
|
|
</CardContent>
|
|
</Card>
|
|
) : alerts.length === 0 ? (
|
|
<Card className="bg-slate-900 border-slate-800">
|
|
<CardContent className="flex flex-col items-center justify-center py-16">
|
|
<CheckCircle className="h-10 w-10 text-emerald-500 mb-3" />
|
|
<p className="text-slate-400">{resolvedView ? '暂无已恢复的告警' : '当前无活动告警,一切正常'}</p>
|
|
</CardContent>
|
|
</Card>
|
|
) : (
|
|
<div className="space-y-2">
|
|
{alerts.map((alert) => (
|
|
<Card key={alert.id} className="bg-slate-900 border-slate-800 py-4">
|
|
<CardContent>
|
|
<div className="flex items-start justify-between gap-3">
|
|
<div className="flex items-start gap-3 min-w-0 flex-1">
|
|
<div className="w-9 h-9 rounded-lg bg-slate-800 flex items-center justify-center shrink-0">
|
|
<AlertTriangle className={`h-4 w-4 ${(alert.severity || 'warning') === 'critical' ? 'text-red-400' : (alert.severity || 'warning') === 'warning' ? 'text-amber-400' : 'text-blue-400'}`} />
|
|
</div>
|
|
<div className="min-w-0">
|
|
<div className="flex items-center gap-2 flex-wrap">
|
|
{severityBadge(alert.severity)}
|
|
<span className="font-medium text-slate-100">{alert.rule_name || alert.name || alert.title || '告警'}</span>
|
|
</div>
|
|
<p className="text-sm text-slate-400 mt-1">{alert.message || alert.description || '触发告警阈值'}</p>
|
|
<div className="flex items-center gap-4 mt-2 text-xs text-slate-500 flex-wrap">
|
|
<span className="inline-flex items-center gap-1">
|
|
<Cpu className="h-3 w-3" />
|
|
{alert.hostname || '--'}
|
|
</span>
|
|
<span className="inline-flex items-center gap-1">
|
|
<span className="text-slate-400">指标:</span> {getMetricLabel(alert.metric)}
|
|
</span>
|
|
{alert.value != null && (
|
|
<span className="inline-flex items-center gap-1">
|
|
<span className="text-slate-400">当前值:</span> {alert.value}
|
|
</span>
|
|
)}
|
|
<span className="inline-flex items-center gap-1">
|
|
<Clock className="h-3 w-3" />
|
|
{alert.created_at || alert.triggered_at ? new Date(alert.created_at || alert.triggered_at).toLocaleString() : '--'}
|
|
</span>
|
|
</div>
|
|
</div>
|
|
</div>
|
|
{!resolvedView && (
|
|
<Button
|
|
size="sm"
|
|
variant="outline"
|
|
onClick={() => handleResolve(alert.id)}
|
|
className="shrink-0 h-8 bg-slate-800 border-slate-700 text-emerald-400 hover:bg-emerald-500/10 hover:text-emerald-400"
|
|
>
|
|
<CheckCircle className="h-3.5 w-3.5 mr-1" />
|
|
恢复
|
|
</Button>
|
|
)}
|
|
</div>
|
|
</CardContent>
|
|
</Card>
|
|
))}
|
|
</div>
|
|
)}
|
|
</TabsContent>
|
|
|
|
{/* ========== 告警规则 ========== */}
|
|
<TabsContent value="rules" className="mt-4 space-y-3">
|
|
<div className="flex justify-end">
|
|
<Button size="sm" onClick={openCreateRule} className="bg-blue-600 hover:bg-blue-700 text-white">
|
|
<Plus className="h-4 w-4 mr-1.5" />
|
|
新建规则
|
|
</Button>
|
|
</div>
|
|
|
|
{loading ? (
|
|
<Card className="bg-slate-900 border-slate-800">
|
|
<CardContent className="flex items-center justify-center py-16">
|
|
<Loader2 className="h-5 w-5 animate-spin text-slate-500" />
|
|
<span className="ml-2 text-slate-400">加载中...</span>
|
|
</CardContent>
|
|
</Card>
|
|
) : rules.length === 0 ? (
|
|
<Card className="bg-slate-900 border-slate-800">
|
|
<CardContent className="flex flex-col items-center justify-center py-16">
|
|
<Bell className="h-10 w-10 text-slate-600 mb-3" />
|
|
<p className="text-slate-400">暂无告警规则</p>
|
|
<Button size="sm" onClick={openCreateRule} className="mt-4 bg-blue-600 hover:bg-blue-700 text-white">
|
|
<Plus className="h-4 w-4 mr-1.5" />
|
|
创建第一条规则
|
|
</Button>
|
|
</CardContent>
|
|
</Card>
|
|
) : (
|
|
<div className="space-y-2">
|
|
{rules.map((rule) => {
|
|
const MetricIcon = METRIC_OPTIONS.find((m) => m.value === rule.metric)?.icon || Cpu;
|
|
return (
|
|
<Card key={rule.id} className={`bg-slate-900 ${rule.enabled === false ? 'border-slate-800 opacity-60' : 'border-slate-800'} py-4`}>
|
|
<CardContent>
|
|
<div className="flex items-center justify-between gap-3">
|
|
<div className="flex items-center gap-3 min-w-0 flex-1">
|
|
<div className="w-9 h-9 rounded-lg bg-slate-800 flex items-center justify-center shrink-0">
|
|
<MetricIcon className="h-4 w-4 text-blue-400" />
|
|
</div>
|
|
<div className="min-w-0">
|
|
<div className="flex items-center gap-2 flex-wrap">
|
|
<span className="font-medium text-slate-100">{rule.name}</span>
|
|
{severityBadge(rule.severity)}
|
|
{rule.enabled === false && (
|
|
<Badge className="bg-slate-700 text-slate-400 border border-slate-600">已禁用</Badge>
|
|
)}
|
|
</div>
|
|
<div className="flex items-center gap-3 mt-1.5 text-xs text-slate-500 flex-wrap">
|
|
<span>{getMetricLabel(rule.metric)}</span>
|
|
{rule.metric !== 'offline' && (
|
|
<span className="text-slate-400">
|
|
{rule.operator} {rule.threshold}{rule.metric === 'port_down' ? '' : '%'}
|
|
</span>
|
|
)}
|
|
{rule.metric === 'port_down' && rule.port ? (
|
|
<span className="text-slate-400">端口 {rule.port}</span>
|
|
) : null}
|
|
{rule.duration ? <span className="text-slate-400">持续 {rule.duration}s</span> : null}
|
|
</div>
|
|
</div>
|
|
</div>
|
|
|
|
<div className="flex items-center gap-2 shrink-0">
|
|
<Switch checked={rule.enabled !== false} onCheckedChange={() => handleToggleRule(rule)} />
|
|
<Button size="icon" variant="ghost" className="h-8 w-8 text-slate-400 hover:text-slate-100 hover:bg-slate-800" onClick={() => openEditRule(rule)}>
|
|
<Pencil className="h-4 w-4" />
|
|
</Button>
|
|
<Button size="icon" variant="ghost" className="h-8 w-8 text-slate-400 hover:text-red-400 hover:bg-slate-800" onClick={() => handleDeleteRule(rule.id)}>
|
|
<Trash2 className="h-4 w-4" />
|
|
</Button>
|
|
</div>
|
|
</div>
|
|
</CardContent>
|
|
</Card>
|
|
);
|
|
})}
|
|
</div>
|
|
)}
|
|
</TabsContent>
|
|
</Tabs>
|
|
|
|
{/* ========== 规则编辑弹窗 ========== */}
|
|
<Dialog open={ruleOpen} onOpenChange={(v) => { if (!v) setRuleOpen(false); }}>
|
|
<DialogContent className="max-w-md bg-slate-900 border-slate-800 text-slate-100">
|
|
<DialogHeader>
|
|
<DialogTitle className="text-slate-100">{editingRule ? '编辑规则' : '新建规则'}</DialogTitle>
|
|
<DialogDescription className="text-slate-400">配置 Agent 指标告警规则</DialogDescription>
|
|
</DialogHeader>
|
|
|
|
<div className="space-y-3">
|
|
<div className="space-y-1.5">
|
|
<Label className="text-slate-300 text-xs">规则名称</Label>
|
|
<Input
|
|
value={ruleForm.name}
|
|
onChange={(e) => setRuleForm({ ...ruleForm, name: e.target.value })}
|
|
placeholder="例如:CPU 使用率告警"
|
|
className="h-9 bg-slate-800 border-slate-700 text-slate-200"
|
|
/>
|
|
</div>
|
|
|
|
<div className="grid grid-cols-2 gap-3">
|
|
<div className="space-y-1.5">
|
|
<Label className="text-slate-300 text-xs">监控指标</Label>
|
|
<Select value={ruleForm.metric} onValueChange={(v) => setRuleForm({ ...ruleForm, metric: v })}>
|
|
<SelectTrigger className="h-9 bg-slate-800 border-slate-700 text-slate-200">
|
|
<SelectValue />
|
|
</SelectTrigger>
|
|
<SelectContent className="bg-slate-800 border-slate-700 text-slate-200">
|
|
{METRIC_OPTIONS.map((m) => (
|
|
<SelectItem key={m.value} value={m.value}>{m.label}</SelectItem>
|
|
))}
|
|
</SelectContent>
|
|
</Select>
|
|
</div>
|
|
<div className="space-y-1.5">
|
|
<Label className="text-slate-300 text-xs">严重程度</Label>
|
|
<Select value={ruleForm.severity} onValueChange={(v) => setRuleForm({ ...ruleForm, severity: v })}>
|
|
<SelectTrigger className="h-9 bg-slate-800 border-slate-700 text-slate-200">
|
|
<SelectValue />
|
|
</SelectTrigger>
|
|
<SelectContent className="bg-slate-800 border-slate-700 text-slate-200">
|
|
{SEVERITY_OPTIONS.map((s) => (
|
|
<SelectItem key={s.value} value={s.value}>{s.label}</SelectItem>
|
|
))}
|
|
</SelectContent>
|
|
</Select>
|
|
</div>
|
|
</div>
|
|
|
|
{ruleForm.metric !== 'offline' && (
|
|
<div className="grid grid-cols-2 gap-3">
|
|
<div className="space-y-1.5">
|
|
<Label className="text-slate-300 text-xs">比较运算符</Label>
|
|
<Select value={ruleForm.operator} onValueChange={(v) => setRuleForm({ ...ruleForm, operator: v })}>
|
|
<SelectTrigger className="h-9 bg-slate-800 border-slate-700 text-slate-200">
|
|
<SelectValue />
|
|
</SelectTrigger>
|
|
<SelectContent className="bg-slate-800 border-slate-700 text-slate-200">
|
|
{OPERATOR_OPTIONS.map((o) => (
|
|
<SelectItem key={o.value} value={o.value}>{o.label}</SelectItem>
|
|
))}
|
|
</SelectContent>
|
|
</Select>
|
|
</div>
|
|
<div className="space-y-1.5">
|
|
<Label className="text-slate-300 text-xs">阈值 {ruleForm.metric !== 'port_down' ? '(%)' : ''}</Label>
|
|
<Input
|
|
type="number"
|
|
value={ruleForm.threshold}
|
|
onChange={(e) => setRuleForm({ ...ruleForm, threshold: e.target.value })}
|
|
className="h-9 bg-slate-800 border-slate-700 text-slate-200"
|
|
/>
|
|
</div>
|
|
</div>
|
|
)}
|
|
|
|
{ruleForm.metric === 'port_down' && (
|
|
<div className="space-y-1.5">
|
|
<Label className="text-slate-300 text-xs">监控端口</Label>
|
|
<Input
|
|
type="number"
|
|
value={ruleForm.port}
|
|
onChange={(e) => setRuleForm({ ...ruleForm, port: e.target.value })}
|
|
placeholder="例如:8080"
|
|
className="h-9 bg-slate-800 border-slate-700 text-slate-200"
|
|
/>
|
|
</div>
|
|
)}
|
|
|
|
<div className="space-y-1.5">
|
|
<Label className="text-slate-300 text-xs">持续时间(秒)</Label>
|
|
<Input
|
|
type="number"
|
|
value={ruleForm.duration}
|
|
onChange={(e) => setRuleForm({ ...ruleForm, duration: e.target.value })}
|
|
placeholder="指标持续超限多久后告警"
|
|
className="h-9 bg-slate-800 border-slate-700 text-slate-200"
|
|
/>
|
|
</div>
|
|
|
|
<div className="flex items-center justify-between">
|
|
<Label className="text-slate-300 text-xs">启用规则</Label>
|
|
<Switch checked={ruleForm.enabled} onCheckedChange={(v) => setRuleForm({ ...ruleForm, enabled: v })} />
|
|
</div>
|
|
</div>
|
|
|
|
<DialogFooter className="gap-2">
|
|
<Button variant="outline" onClick={() => setRuleOpen(false)} className="border-slate-700 text-slate-300">取消</Button>
|
|
<Button onClick={handleSaveRule} disabled={ruleSaving} className="bg-blue-600 hover:bg-blue-700 text-white">
|
|
{ruleSaving ? <Loader2 className="h-4 w-4 mr-1.5 animate-spin" /> : null}
|
|
{editingRule ? '保存' : '创建'}
|
|
</Button>
|
|
</DialogFooter>
|
|
</DialogContent>
|
|
</Dialog>
|
|
</div>
|
|
);
|
|
}
|
|
|
|
export default AgentAlerts;
|