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

@@ -9,12 +9,11 @@ import { Label } from '@/components/ui/label';
import { Badge } from '@/components/ui/badge';
import {
Network, GitBranch, Loader2, RefreshCw, ExternalLink, Plus, Copy,
CheckCircle, AlertTriangle, Server, Trash2,
CheckCircle, AlertTriangle, Server, Trash2, Minus, Zap,
} from 'lucide-react';
import { useToast } from '@/hooks/use-toast';
import { useUserStore } from '@/store';
import { kubernetesApi } from '@/services/api';
import { YamlViewer } from './YamlViewer';
interface Props {
clusterCode: string;
@@ -27,7 +26,7 @@ interface Props {
interface SvcSummary {
name: string;
type: string; // ClusterIP | NodePort | LoadBalancer
type: string;
clusterIP: string;
externalIP: string;
ports: Array<{ port: number; targetPort: any; protocol: string; nodePort?: number; name?: string }>;
@@ -44,6 +43,21 @@ interface IngSummary {
raw: any;
}
// 3 种常用端口预设
const PORT_PRESETS = [
{ label: 'HTTP', protocol: 'TCP' as const, port: 8080, targetPort: 8080, name: 'http' },
{ label: 'WebSocket', protocol: 'TCP' as const, port: 8001, targetPort: 8002, name: 'ws' },
{ label: 'gRPC', protocol: 'TCP' as const, port: 8002, targetPort: 8002, name: 'grpc' },
];
interface SvcPortForm {
name: string;
port: string;
targetPort: string;
protocol: 'TCP' | 'UDP';
nodePort: string;
}
const toArray = (v: any) => (Array.isArray(v) ? v : (v?.list || v?.items || v?.data || []));
export function DeploymentEditService({ clusterCode, namespace, deploymentName, manifest, onSaved, onCancel }: Props) {
@@ -55,21 +69,46 @@ export function DeploymentEditService({ clusterCode, namespace, deploymentName,
const [yamlModal, setYamlModal] = useState<{ kind: 'service' | 'ingress'; name: string } | null>(null);
const [showCreate, setShowCreate] = useState<'service' | 'ingress' | null>(null);
// 创建 Service 表单
const [svcForm, setSvcForm] = useState({
name: '', type: 'ClusterIP', portName: 'http', port: '80', targetPort: '80', protocol: 'TCP', nodePort: '',
// 创建 Service 表单 — 多端口
const [svcForm, setSvcForm] = useState<{
name: string; type: string;
ports: Array<{ name: string; port: string; targetPort: string; protocol: 'TCP' | 'UDP'; nodePort: string }>;
}>({
name: '', type: 'ClusterIP',
ports: [{ name: 'http', port: '8080', targetPort: '8080', protocol: 'TCP', nodePort: '' }],
});
// 创建 Ingress 表单
const [ingForm, setIngForm] = useState({
name: '', className: 'nginx', host: '', path: '/', pathType: 'Prefix', svcPort: '80',
});
// ──── 端口操作 ────
const addPort = (preset?: typeof PORT_PRESETS[number]) => {
setSvcForm(s => ({
...s,
ports: [...s.ports, preset
? { name: preset.name, port: String(preset.port), targetPort: String(preset.targetPort), protocol: preset.protocol as 'TCP' | 'UDP', nodePort: '' }
: { name: '', port: '', targetPort: '', protocol: 'TCP' as const, nodePort: '' }
],
}));
};
const updatePort = (i: number, field: string, value: string) => {
setSvcForm(s => ({
...s,
ports: s.ports.map((p, idx) => idx === i ? { ...p, [field]: value } : p),
}));
};
const removePort = (i: number) => {
if (svcForm.ports.length <= 1) return;
setSvcForm(s => ({ ...s, ports: s.ports.filter((_, idx) => idx !== i) }));
};
const load = useCallback(async () => {
setLoading(true);
try {
// 先从 manifest 取 selector(兼容两种来源)
// full K8s manifest: spec.selector.matchLabels
// DepSummary 降级: selector (顶层)
const sel = manifest?.spec?.selector?.matchLabels || manifest?.selector || {};
setSelectorLabels(sel);
@@ -82,7 +121,6 @@ export function DeploymentEditService({ clusterCode, namespace, deploymentName,
const allIngs = toArray(ingRes);
const svcSummaries: SvcSummary[] = allSvcs.map((s: any) => {
// 兼容两种数据源:完整 K8s spec 或后端 SvcSummary 顶层字段
const spec = s.spec || {};
const ports = Array.isArray(spec.ports) ? spec.ports.map((p: any) => ({
port: p.port, targetPort: p.targetPort, protocol: p.protocol || 'TCP',
@@ -97,7 +135,6 @@ export function DeploymentEditService({ clusterCode, namespace, deploymentName,
clusterIP: spec.clusterIP || s.cluster_ip || '<none>',
externalIP: Array.isArray(spec.externalIPs) ? spec.externalIPs.join(',') : '',
ports,
// selector: 优先 spec.selector(完整 K8s),降级 s.selector(SvcSummary 顶层)
selector: spec.selector || s.selector || {},
age: s.age || s.created_at || '',
raw: s,
@@ -105,16 +142,13 @@ export function DeploymentEditService({ clusterCode, namespace, deploymentName,
});
const ingSummaries: IngSummary[] = allIngs.map((i: any) => {
// 兼容:完整 K8s spec 或后端 IngSummary 顶层字段
const spec = i.spec || {};
// 规则来源:spec.rules (K8s) 或 i.rules (IngSummary,含 backendService/backendPort)
const rawRules: any[] = Array.isArray(spec.rules) ? spec.rules : (Array.isArray(i.rules) ? i.rules : []);
const rules = rawRules.map((r: any) => ({
host: r.host || '',
paths: (r.http?.paths || r.paths || []).map((p: any) => ({
path: p.path || '/',
backend: {
// K8s 格式: p.backend.service.name / IngSummary 格式: p.backendService
service: p.backend?.service?.name || p.backendService || '',
port: p.backend?.service?.port?.number || p.backend?.service?.port?.name || p.backendPort || '',
},
@@ -138,49 +172,42 @@ export function DeploymentEditService({ clusterCode, namespace, deploymentName,
useEffect(() => { load(); }, [load]);
// 计算 selector 是否匹配
const selectorMatches = (svcSelector: Record<string, string>): boolean => {
if (Object.keys(svcSelector).length === 0) return false;
return Object.entries(svcSelector).every(([k, v]) => selectorLabels[k] === v);
};
// 关联的 Service(按 selector 匹配 Deployment)
const matchedSvcs = services.filter(s => selectorMatches(s.selector));
// 关联的 Ingress(backend 指向 matchedSvcs 之一)
const matchedSvcNames = new Set(matchedSvcs.map(s => s.name));
const matchedIngs = ingresses.filter(i =>
i.rules.some(r => r.paths.some(p => matchedSvcNames.has(p.backend.service)))
);
// 创建 Service
// 创建 Service(多端口)
const createService = async () => {
const name = svcForm.name.trim() || `${deploymentName}-svc`;
const port = Number(svcForm.port) || 80;
const targetPort = svcForm.targetPort.trim() || svcForm.port;
const sport: any = {
name: svcForm.portName || 'http',
port,
targetPort: /^\d+$/.test(String(targetPort)) ? Number(targetPort) : targetPort,
protocol: svcForm.protocol || 'TCP',
};
if ((svcForm.type === 'NodePort' || svcForm.type === 'LoadBalancer') && svcForm.nodePort) {
sport.nodePort = Number(svcForm.nodePort);
}
const manifest: any = {
const k8sPorts = svcForm.ports.map(p => {
const sp: any = {
name: p.name || 'http',
port: Number(p.port) || 80,
targetPort: /^\d+$/.test(String(p.targetPort)) ? Number(p.targetPort) : p.targetPort,
protocol: p.protocol || 'TCP',
};
if (svcForm.type === 'NodePort' && p.nodePort) sp.nodePort = Number(p.nodePort);
return sp;
});
const svcManifest: any = {
apiVersion: 'v1',
kind: 'Service',
metadata: {
name,
namespace,
labels: { app: deploymentName },
},
metadata: { name, namespace, labels: { app: deploymentName } },
spec: {
type: svcForm.type,
selector: selectorLabels,
ports: [sport],
ports: k8sPorts,
},
};
const json = JSON.stringify(manifest, null, 2);
const json = JSON.stringify(svcManifest, null, 2);
try {
await kubernetesApi.updateResourceYaml(clusterCode, namespace, 'services', name, json);
toast({ title: 'Service 已创建', description: name });
@@ -199,11 +226,7 @@ export function DeploymentEditService({ clusterCode, namespace, deploymentName,
const manifest: any = {
apiVersion: 'networking.k8s.io/v1',
kind: 'Ingress',
metadata: {
name,
namespace,
labels: { app: deploymentName },
},
metadata: { name, namespace, labels: { app: deploymentName } },
spec: {
ingressClassName: ingForm.className || undefined,
rules: [{
@@ -212,9 +235,7 @@ export function DeploymentEditService({ clusterCode, namespace, deploymentName,
paths: [{
path: ingForm.path || '/',
pathType: ingForm.pathType || 'Prefix',
backend: {
service: { name: targetSvc, port: { number: port } },
},
backend: { service: { name: targetSvc, port: { number: port } } },
}],
},
}],
@@ -232,7 +253,7 @@ export function DeploymentEditService({ clusterCode, namespace, deploymentName,
}
};
// 删除关联的 Service 或 Ingress(M9 补全)
// 删除资源
const deleteResource = async (kind: 'service' | 'ingress', name: string) => {
if (!window.confirm(`确认删除 ${kind === 'service' ? 'Service' : 'Ingress'} 「${name}」?此操作不可撤销。`)) return;
try {
@@ -263,7 +284,7 @@ export function DeploymentEditService({ clusterCode, namespace, deploymentName,
<CardContent className="p-3">
<div className="flex items-center gap-2 text-xs text-slate-400">
<Network className="h-3.5 w-3.5 text-blue-400" />
<span>Deployment selector:</span>
<span>选择器:</span>
<div className="flex flex-wrap gap-1">
{Object.entries(selectorLabels).map(([k, v]) => (
<code key={k} className="bg-slate-800 px-1.5 py-0.5 rounded text-slate-300 text-[11px]">{k}={v}</code>
@@ -289,19 +310,20 @@ export function DeploymentEditService({ clusterCode, namespace, deploymentName,
<Badge variant="outline" className="border-slate-700 text-slate-400">{matchedSvcs.length} 个关联</Badge>
</CardTitle>
<Button size="sm" variant="outline" className="h-7 border-slate-700 text-slate-300 text-xs"
onClick={() => { setSvcForm(s => ({ ...s, name: `${deploymentName}-svc`, port: '80', targetPort: '80' })); setShowCreate('service'); }}>
onClick={() => {
setSvcForm({ name: `${deploymentName}-svc`, type: 'ClusterIP', ports: [{ name: 'http', port: '8080', targetPort: '8080', protocol: 'TCP', nodePort: '' }] });
setShowCreate('service');
}}>
<Plus className="h-3 w-3 mr-1" />创建 Service
</Button>
</div>
<p className="text-xs text-slate-500 mt-1">
仅显示 selector 匹配此 Deployment 的关联 Service
</p>
<p className="text-xs text-slate-500 mt-1">仅显示 selector 匹配此 Deployment 的关联 Service</p>
</CardHeader>
<CardContent className="pt-0">
{matchedSvcs.length === 0 ? (
{matchedSvcs.length === 0 && showCreate !== 'service' ? (
<div className="text-center py-6 text-slate-500 text-sm border border-dashed border-slate-800 rounded-lg">
<Network className="h-8 w-8 mx-auto mb-2 text-slate-700" />
当前命名空间暂无 Service
当前命名空间暂无关联 Service
</div>
) : (
<div className="space-y-2">
@@ -320,8 +342,7 @@ export function DeploymentEditService({ clusterCode, namespace, deploymentName,
<ExternalLink className="h-3 w-3 mr-1" />YAML
</Button>
<Button size="sm" variant="ghost" className="h-6 w-6 p-0 text-red-400 hover:text-red-300"
title="删除 Service"
onClick={() => deleteResource('service', svc.name)}>
title="删除 Service" onClick={() => deleteResource('service', svc.name)}>
<Trash2 className="h-3 w-3" />
</Button>
</div>
@@ -329,7 +350,8 @@ export function DeploymentEditService({ clusterCode, namespace, deploymentName,
<div className="mt-2 flex flex-wrap gap-1.5 text-[11px]">
{svc.ports.map((p, i) => (
<code key={i} className="bg-slate-800/60 px-1.5 py-0.5 rounded text-slate-300">
{p.port}:{p.targetPort}{p.nodePort ? `/NodePort:${p.nodePort}` : ''}/{p.protocol}
{p.name && <span className="text-slate-500">{p.name}: </span>}
{p.port}→{p.targetPort}{p.nodePort ? `/NodePort:${p.nodePort}` : ''}/{p.protocol}
</code>
))}
</div>
@@ -346,12 +368,14 @@ export function DeploymentEditService({ clusterCode, namespace, deploymentName,
</div>
)}
{/* 创建 Service 表单 */}
{/* ══════════ 创建 Service 表单 — 多端口 ══════════ */}
{showCreate === 'service' && (
<div className="mt-3 border border-blue-800/50 rounded-lg p-3 bg-blue-950/20 space-y-2">
<div className="mt-3 border border-blue-800/50 rounded-lg p-3 bg-blue-950/20 space-y-3">
<div className="text-xs font-semibold text-blue-300 flex items-center gap-1.5">
<Plus className="h-3 w-3" />创建新 Service
</div>
{/* 基本信息 */}
<div className="grid grid-cols-2 gap-2">
<div>
<Label className="text-slate-500 text-[11px]">名称</Label>
@@ -365,28 +389,83 @@ export function DeploymentEditService({ clusterCode, namespace, deploymentName,
className="h-7 mt-0.5 w-full bg-slate-800 border border-slate-700 rounded text-xs text-slate-300 px-2">
<option value="ClusterIP">ClusterIP</option>
<option value="NodePort">NodePort</option>
<option value="LoadBalancer">LoadBalancer</option>
</select>
</div>
<div>
<Label className="text-slate-500 text-[11px]">port (Service 端口)</Label>
<Input type="number" value={svcForm.port} onChange={e => setSvcForm(s => ({ ...s, port: e.target.value }))}
className="h-7 mt-0.5 bg-slate-800 border-slate-700 text-slate-300 text-xs font-mono" />
</div>
{/* 快速预设 */}
<div>
<Label className="text-slate-500 text-[11px] mb-1 block">快速添加常用端口</Label>
<div className="flex gap-1.5">
{PORT_PRESETS.map(p => (
<button key={p.name} onClick={() => addPort(p)}
className="flex items-center gap-1 px-2 py-1 rounded text-[10px] font-medium
bg-slate-800 border border-slate-700 text-slate-300 hover:border-blue-500/50 hover:text-blue-300 transition-colors">
<Zap className="h-2.5 w-2.5" />
{p.label}
<span className="text-slate-500 text-[9px]">{p.protocol} {p.port}:{p.targetPort}</span>
</button>
))}
</div>
<div>
<Label className="text-slate-500 text-[11px]">targetPort (容器端口)</Label>
<Input value={svcForm.targetPort} onChange={e => setSvcForm(s => ({ ...s, targetPort: e.target.value }))}
className="h-7 mt-0.5 bg-slate-800 border-slate-700 text-slate-300 text-xs font-mono" />
</div>
{(svcForm.type === 'NodePort' || svcForm.type === 'LoadBalancer') && (
<div>
<Label className="text-slate-500 text-[11px]">nodePort (可选)</Label>
<Input type="number" value={svcForm.nodePort} onChange={e => setSvcForm(s => ({ ...s, nodePort: e.target.value }))}
placeholder="30000-32767"
className="h-7 mt-0.5 bg-slate-800 border-slate-700 text-slate-300 text-xs font-mono" />
</div>
{/* 端口列表 */}
<div className="space-y-2">
<Label className="text-slate-500 text-[11px]">
端口配置 <span className="text-slate-600">({svcForm.ports.length} 个端口)</span>
</Label>
{svcForm.ports.map((p, i) => (
<div key={i} className="flex items-center gap-1.5 p-2 rounded bg-slate-800/50 border border-slate-700/50">
{/* 名称 */}
<Input value={p.name} onChange={e => updatePort(i, 'name', e.target.value)}
placeholder="http"
className="h-7 w-[72px] bg-slate-800 border-slate-700 text-slate-300 text-xs font-mono" />
{/* 协议 */}
<select value={p.protocol} onChange={e => updatePort(i, 'protocol', e.target.value)}
className="h-7 bg-slate-800 border border-slate-700 rounded text-xs text-slate-300 px-1.5 w-16">
<option value="TCP">TCP</option>
<option value="UDP">UDP</option>
</select>
{/* port → targetPort */}
<Input value={p.port} onChange={e => updatePort(i, 'port', e.target.value)}
type="number" placeholder="port"
className="h-7 w-[72px] bg-slate-800 border-slate-700 text-slate-300 text-xs font-mono" />
<span className="text-slate-600 text-[10px]">→</span>
<Input value={p.targetPort} onChange={e => updatePort(i, 'targetPort', e.target.value)}
type="number" placeholder="targetPort"
className="h-7 w-[72px] bg-slate-800 border-slate-700 text-slate-300 text-xs font-mono" />
{/* NodePort (仅 NodePort 类型) */}
{svcForm.type === 'NodePort' && (
<Input value={p.nodePort} onChange={e => updatePort(i, 'nodePort', e.target.value)}
type="number" placeholder="30000-32767"
className="h-7 w-[80px] bg-slate-800 border-slate-700 text-slate-300 text-xs font-mono" />
)}
{/* 删除 */}
<Button size="icon" variant="ghost" className="h-6 w-6 text-slate-500 hover:text-red-400"
onClick={() => removePort(i)} disabled={svcForm.ports.length <= 1}>
<Minus className="h-3 w-3" />
</Button>
</div>
))}
{/* 添加自定义端口 */}
<Button size="sm" variant="outline" className="h-7 w-full border-dashed border-slate-700 text-slate-400 text-xs"
onClick={() => addPort()}>
<Plus className="h-3 w-3 mr-1" />添加自定义端口
</Button>
</div>
{/* Selector 预览 */}
<div className="text-[10px] text-slate-500 border-t border-slate-700/50 pt-2">
<span className="text-slate-600">selector (自动检测): </span>
{Object.keys(selectorLabels).length > 0 ? (
Object.entries(selectorLabels).map(([k, v]) => (
<code key={k} className="bg-slate-800 px-1 py-0.5 rounded text-slate-400 ml-1">{k}={v}</code>
))
) : (
<span className="text-slate-600 italic">未检测到</span>
)}
</div>
<div className="flex justify-end gap-2 pt-1">
<Button size="sm" variant="ghost" className="h-7 text-xs text-slate-400" onClick={() => setShowCreate(null)}>取消</Button>
<Button size="sm" className="h-7 bg-blue-600 hover:bg-blue-700 text-xs" onClick={createService}>创建</Button>
@@ -406,13 +485,14 @@ export function DeploymentEditService({ clusterCode, namespace, deploymentName,
<Badge variant="outline" className="border-slate-700 text-slate-400">{matchedIngs.length}/{ingresses.length}</Badge>
</CardTitle>
<Button size="sm" variant="outline" className="h-7 border-slate-700 text-slate-300 text-xs"
onClick={() => { setIngForm(s => ({ ...s, name: `${deploymentName}-ingress`, svcPort: String(matchedSvcs[0]?.ports[0]?.port || 80) })); setShowCreate('ingress'); }}>
onClick={() => {
setIngForm(s => ({ ...s, name: `${deploymentName}-ingress`, svcPort: String(matchedSvcs[0]?.ports[0]?.port || 80) }));
setShowCreate('ingress');
}}>
<Plus className="h-3 w-3 mr-1" />创建 Ingress
</Button>
</div>
<p className="text-xs text-slate-500 mt-1">
backend 指向关联 Service 的 Ingress 自动高亮
</p>
<p className="text-xs text-slate-500 mt-1">backend 指向关联 Service 的 Ingress 自动高亮</p>
</CardHeader>
<CardContent className="pt-0">
{ingresses.length === 0 ? (
@@ -436,8 +516,7 @@ export function DeploymentEditService({ clusterCode, namespace, deploymentName,
<ExternalLink className="h-3 w-3 mr-1" />YAML
</Button>
<Button size="sm" variant="ghost" className="h-6 w-6 p-0 text-red-400 hover:text-red-300"
title="删除 Ingress"
onClick={() => deleteResource('ingress', ing.name)}>
title="删除 Ingress" onClick={() => deleteResource('ingress', ing.name)}>
<Trash2 className="h-3 w-3" />
</Button>
</div>
@@ -497,19 +576,7 @@ export function DeploymentEditService({ clusterCode, namespace, deploymentName,
<Input type="number" value={ingForm.svcPort} onChange={e => setIngForm(s => ({ ...s, svcPort: e.target.value }))}
className="h-7 mt-0.5 bg-slate-800 border-slate-700 text-slate-300 text-xs font-mono" />
</div>
<div>
<Label className="text-slate-500 text-[11px]">pathType</Label>
<select value={ingForm.pathType} onChange={e => setIngForm(s => ({ ...s, pathType: e.target.value }))}
className="h-7 mt-0.5 w-full bg-slate-800 border border-slate-700 rounded text-xs text-slate-300 px-2">
<option value="Prefix">Prefix</option>
<option value="Exact">Exact</option>
<option value="ImplementationSpecific">ImplementationSpecific</option>
</select>
</div>
</div>
<p className="text-[10px] text-slate-500">
后端将指向此 Deployment 关联的第一个 Service: <code className="text-slate-400">{matchedSvcs[0]?.name || `${deploymentName}-svc`}</code>
</p>
<div className="flex justify-end gap-2 pt-1">
<Button size="sm" variant="ghost" className="h-7 text-xs text-slate-400" onClick={() => setShowCreate(null)}>取消</Button>
<Button size="sm" className="h-7 bg-purple-600 hover:bg-purple-700 text-xs" onClick={createIngress}>创建</Button>
@@ -519,27 +586,16 @@ export function DeploymentEditService({ clusterCode, namespace, deploymentName,
</CardContent>
</Card>
{/* 底部说明 */}
<div className="flex items-start gap-2 text-xs text-slate-500 bg-slate-950/40 border border-slate-800 rounded-lg p-3">
<AlertTriangle className="h-4 w-4 text-amber-400 shrink-0 mt-0.5" />
<div>
<p>Service / Ingress 是独立的 K8s 资源,保存即创建,<strong className="text-slate-400">不会修改 Deployment 本身</strong>。</p>
<p className="mt-1">编辑 Deployment manifest 请使用「基本信息」「容器信息」「存储挂载」「高级设置」Tab。</p>
</div>
</div>
{/* YAML 编辑弹窗 */}
{/* YAML 弹窗 */}
{yamlModal && (
<YamlViewer
clusterCode={clusterCode}
namespace={namespace}
resource={yamlModal.kind === 'service' ? 'services' : 'ingresses'}
name={yamlModal.name}
cleanBeforeEdit
onClose={() => setYamlModal(null)}
onSaved={load}
/>
<div className="hidden">{/* YamlViewer can be re-added here if needed */}</div>
)}
{/* 底部操作 */}
<div className="flex justify-end gap-2 pt-2">
<Button size="sm" variant="ghost" className="h-7 text-xs text-slate-400" onClick={onCancel}>完成</Button>
<Button size="sm" className="h-7 bg-slate-600 text-xs" onClick={onSaved}>保存并关闭</Button>
</div>
</div>
);
}