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

@@ -85,7 +85,7 @@ export function PipelineManager() {
const [newCachePaths, setNewCachePaths] = useState('');
// Executor concurrency
const [newMaxExecutors, setNewMaxExecutors] = useState(1);
const [newMaxExecutors, setNewMaxExecutors] = useState(2);
// Reference data
const [repos, setRepos] = useState<any[]>([]);
@@ -288,33 +288,46 @@ export function PipelineManager() {
))}
</div>
{/* ══════════ 全流程可视化横幅 // Logan.Li ══════════ */}
<div className="flex items-center gap-1.5 px-4 py-2.5 rounded-lg bg-[var(--dg-bg-secondary)] border border-[var(--dg-border)]">
<div className="flex items-center gap-1">
<GitBranch className="h-3.5 w-3.5 text-indigo-400" />
<span className="text-[11px] font-semibold text-indigo-400">Git 代码</span>
{/* ══════════ 全流程可视化横幅 — 双路径 ══════════ */}
<div className="flex items-stretch gap-3 px-4 py-3 rounded-lg bg-[var(--dg-bg-secondary)] border border-[var(--dg-border)]">
{/* 路径 1: SSH 传统主机部署 */}
<div className="flex-1 space-y-1.5">
<div className="flex items-center gap-1.5">
<GitBranch className="h-3 w-3 text-indigo-400" />
<span className="text-[10px] font-semibold text-indigo-400">构建</span>
<ArrowRight className="h-2.5 w-2.5 text-[var(--dg-text-secondary)] opacity-30" />
<Rocket className="h-3 w-3 text-red-400" />
<span className="text-[10px] font-semibold text-red-400">部署</span>
<ArrowRight className="h-2.5 w-2.5 text-[var(--dg-text-secondary)] opacity-30" />
<div className="flex items-center gap-1 px-2 py-0.5 rounded bg-blue-400/10 border border-blue-400/20">
<Server className="h-3 w-3 text-blue-400" />
<span className="text-[10px] font-medium text-blue-400">SSH 主机</span>
</div>
</div>
<p className="text-[9px] text-[var(--dg-text-secondary)] opacity-40 pl-1">传统主机 SCP 部署 · 无需镜像仓库</p>
</div>
<ArrowRight className="h-3 w-3 text-[var(--dg-text-secondary)] opacity-30" />
<div className="flex items-center gap-1">
<Box className="h-3.5 w-3.5 text-amber-400" />
<span className="text-[11px] font-semibold text-amber-400">构建</span>
{/* 分隔 */}
<div className="w-px bg-[var(--dg-border)]" />
{/* 路径 2: Kubernetes 容器部署 */}
<div className="flex-1 space-y-1.5">
<div className="flex items-center gap-1.5">
<GitBranch className="h-3 w-3 text-indigo-400" />
<span className="text-[10px] font-semibold text-indigo-400">构建</span>
<ArrowRight className="h-2.5 w-2.5 text-[var(--dg-text-secondary)] opacity-30" />
<Container className="h-3 w-3 text-cyan-400" />
<span className="text-[10px] font-semibold text-cyan-400">镜像仓库</span>
<ArrowRight className="h-2.5 w-2.5 text-[var(--dg-text-secondary)] opacity-30" />
<Rocket className="h-3 w-3 text-red-400" />
<span className="text-[10px] font-semibold text-red-400">部署</span>
<ArrowRight className="h-2.5 w-2.5 text-[var(--dg-text-secondary)] opacity-30" />
<div className="flex items-center gap-1 px-2 py-0.5 rounded bg-emerald-400/10 border border-emerald-400/20">
<Network className="h-3 w-3 text-emerald-400" />
<span className="text-[10px] font-medium text-emerald-400">Kubernetes</span>
</div>
</div>
<p className="text-[9px] text-[var(--dg-text-secondary)] opacity-40 pl-1">容器化部署 · 需镜像仓库推送</p>
</div>
<ArrowRight className="h-3 w-3 text-[var(--dg-text-secondary)] opacity-30" />
<div className="flex items-center gap-1">
<Container className="h-3.5 w-3.5 text-cyan-400" />
<span className="text-[11px] font-semibold text-cyan-400">镜像仓库</span>
</div>
<ArrowRight className="h-3 w-3 text-[var(--dg-text-secondary)] opacity-30" />
<div className="flex items-center gap-1">
<Rocket className="h-3.5 w-3.5 text-red-400" />
<span className="text-[11px] font-semibold text-red-400">部署</span>
</div>
<ArrowRight className="h-3 w-3 text-[var(--dg-text-secondary)] opacity-30" />
<div className="flex items-center gap-1">
<Network className="h-3.5 w-3.5 text-emerald-400" />
<span className="text-[11px] font-semibold text-emerald-400">K8s</span>
</div>
<span className="ml-auto text-[10px] text-[var(--dg-text-secondary)] opacity-40 tracking-wide">全流程可视化</span>
<span className="self-center ml-2 text-[10px] text-[var(--dg-text-secondary)] opacity-30 tracking-wide whitespace-nowrap">全流程可视化</span>
</div>
<div className="flex items-center gap-4">
@@ -401,7 +414,7 @@ export function PipelineManager() {
)}
<div className="flex items-center gap-3 mt-1.5 text-xs text-[var(--dg-text-secondary)] opacity-60">
<span className="flex items-center gap-1"><GitBranch className="h-3 w-3" />{pipeline.deploy_mode === 'tag' ? 'Tag发版' : pipeline.branch || 'main'}</span>
<span className="flex items-center gap-1">{(pipeline.deploy_target || 'ssh') === 'k8s' ? <><Network className="h-3 w-3" />K8s</> : <><Server className="h-3 w-3" />SSH</>}</span>
<span className="flex items-center gap-1">{(pipeline.deploy_target || 'ssh') === 'k8s' ? <><Network className="h-3 w-3" />Kubernetes</> : <><Server className="h-3 w-3" />SSH 主机</>}</span>
{repo && <span className="flex items-center gap-1"><Globe className="h-3 w-3" />{repo.name}</span>}
{registry && <span className="flex items-center gap-1"><Container className="h-3 w-3" />{registry.name}</span>}
{pipeline.last_run_at && <span><Clock className="h-3 w-3 inline mr-0.5" />{new Date(pipeline.last_run_at).toLocaleString('zh-CN')}</span>}
@@ -560,7 +573,7 @@ export function PipelineManager() {
<div className="flex gap-1 bg-[var(--dg-bg-secondary)] rounded-lg p-1 border border-[var(--dg-border)]">
{[
{ key: 'ssh', label: 'SSH 主机', icon: Server },
{ key: 'k8s', label: 'K8s 集群', icon: Network },
{ key: 'k8s', label: 'Kubernetes 集群', icon: Network },
].map(t => {
const active = newDeployTarget === t.key;
return (
@@ -819,7 +832,7 @@ export function PipelineManager() {
</SelectContent>
</Select>
</div>
<p className="text-[10px] text-[var(--dg-text-secondary)] opacity-50 mt-1">设为 1 则按顺序串行执行,超过 1 可并发构建</p>
<p className="text-[10px] text-[var(--dg-text-secondary)] opacity-50 mt-1">设为 1 则按顺序串行执行,默认 2 可并发构建</p>
</div>
</div>
<div className="flex justify-end gap-2 mt-4 pt-4 border-t border-[var(--dg-border)]">
@@ -889,7 +902,7 @@ function PipelineQueuePanel({ pipeline, clusterId: _cid }: { pipeline: any; clus
const running = queue?.running || 0;
const queued = queue?.queued || 0;
const queueIds: number[] = queue?.queue_ids || [];
const max = pipeline.max_executors || 1;
const max = pipeline.max_executors || 2;
const pendingRuns = queue?.pending_runs || [];
if (loading && !queue) return null;
+214 -86
View File
@@ -1,9 +1,9 @@
import { useState, useEffect } from 'react';
import { Wrench, RefreshCw, Loader2, Download, CheckCircle, XCircle, Clock, Settings2 } from 'lucide-react';
import { Wrench, RefreshCw, Loader2, Download, CheckCircle, XCircle, Clock, Settings2, ChevronDown } from 'lucide-react';
import { Button } from '@/components/ui/button';
import { Badge } from '@/components/ui/badge';
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogDescription } from '@/components/ui/dialog';
import { toast } from 'sonner';
import { deployApi } from '@/services/api';
@@ -12,14 +12,17 @@ interface ToolConfig {
category: string; install_method: 'preinstall' | 'lazy' | 'disabled';
binary_name: string; install_path: string; status: string;
installed_version: string; error_msg: string; enabled: boolean;
sort_order: number;
sort_order: number; default_version: string;
}
interface VersionOption {
version: string; label: string;
}
const categoryLabel: Record<string, string> = {
k8s: 'K8s', build: '构建', deploy: '部署', automation: '自动化', other: '其他',
build: '构建', deploy: '部署', automation: '自动化', other: '其他',
};
const categoryColor: Record<string, string> = {
k8s: 'bg-blue-500/20 text-blue-400 border-blue-500/30',
build: 'bg-amber-500/20 text-amber-400 border-amber-500/30',
deploy: 'bg-cyan-500/20 text-cyan-400 border-cyan-500/30',
automation: 'bg-purple-500/20 text-purple-400 border-purple-500/30',
@@ -34,11 +37,21 @@ const methodColor: Record<string, string> = {
disabled: 'bg-slate-500/20 text-slate-400 border-slate-500/30',
};
// Tools that support version selection
const VERSIONED_TOOLS = ['jdk', 'nodejs', 'maven'];
export default function ToolConfigTab() {
const [tools, setTools] = useState<ToolConfig[]>([]);
const [loading, setLoading] = useState(false);
const [installing, setInstalling] = useState<number | null>(null);
// Version dialog state
const [versionDialog, setVersionDialog] = useState<{ tool: ToolConfig; versions: VersionOption[] } | null>(null);
const [selectedVersion, setSelectedVersion] = useState('');
// Download test state
const [testing, setTesting] = useState<number | null>(null);
const fetchTools = async () => {
setLoading(true);
try {
@@ -50,17 +63,32 @@ export default function ToolConfigTab() {
useEffect(() => { fetchTools(); }, []);
const handleInstall = async (tool: ToolConfig) => {
const openVersionDialog = async (tool: ToolConfig) => {
try {
const res: any = await deployApi.getToolVersions(tool.id);
const versions = (res as any)?.versions || [];
if (versions.length === 0) {
// No versions — install directly
handleInstall(tool);
return;
}
setVersionDialog({ tool, versions });
setSelectedVersion(tool.default_version || versions[0]?.version || '');
} catch {
// Fallback: install with default version
handleInstall(tool);
}
};
const handleInstall = async (tool: ToolConfig, version?: string) => {
setInstalling(tool.id);
try {
await deployApi.installTool(tool.id);
toast.success(`${tool.display_name} 安装已触发`);
// Poll for status
const v = version || tool.default_version;
await deployApi.installTool(tool.id, v);
toast.success(`${tool.display_name}${v ? ` (${v})` : ''} 安装已触发`);
setVersionDialog(null);
setTimeout(async () => {
try {
await deployApi.checkTool(tool.id);
fetchTools();
} catch { /* ignore */ }
try { await deployApi.checkTool(tool.id); fetchTools(); } catch { /* ignore */ }
setInstalling(null);
}, 3000);
} catch {
@@ -85,6 +113,26 @@ export default function ToolConfigTab() {
} catch { toast.error('更新失败'); }
};
// Download speed test
const handleTestDownload = async (tool: ToolConfig) => {
setTesting(tool.id);
const start = Date.now();
try {
// Simulate a quick reachability test by fetching the version URL
const res: any = await deployApi.getToolVersions(tool.id);
const elapsed = ((Date.now() - start) / 1000).toFixed(1);
const available = (res as any)?.versions?.length > 0;
if (available) {
toast.success(`${tool.display_name} 镜像可访问 (${elapsed}s)`);
} else {
toast(`${tool.display_name} 无法获取版本列表`, { description: '请检查网络连接' });
}
} catch {
toast.error(`${tool.display_name} 网络不可达`);
}
setTesting(null);
};
return (
<div className="space-y-3">
<div className="flex items-center justify-between">
@@ -117,84 +165,164 @@ export default function ToolConfigTab() {
</tr>
</thead>
<tbody>
{tools.map(tool => (
<tr key={tool.id} className="border-b border-[var(--dg-border)] hover:bg-[var(--dg-bg-tertiary)]/50">
<td className="px-3 py-2">
<div className="font-medium text-[var(--dg-text-primary)]">{tool.display_name}</div>
<div className="text-xs text-[var(--dg-text-secondary)] font-mono">{tool.name}</div>
{tool.installed_version && tool.status === 'installed' && (
<div className="text-xs text-emerald-400 font-mono mt-0.5">v{tool.installed_version}</div>
)}
{tool.error_msg && (
<div className="text-xs text-red-400 mt-0.5 max-w-[200px] truncate" title={tool.error_msg}>{tool.error_msg}</div>
)}
</td>
<td className="px-3 py-2 hidden sm:table-cell">
<Badge className={`text-xs ${categoryColor[tool.category] || categoryColor.other}`}>
{categoryLabel[tool.category] || tool.category}
</Badge>
</td>
<td className="px-3 py-2">
<Select
value={tool.install_method}
onValueChange={(v) => handleMethodChange(tool, v as 'preinstall' | 'lazy' | 'disabled')}
>
<SelectTrigger className="h-7 w-[90px] text-xs">
<SelectValue />
</SelectTrigger>
<SelectContent>
<SelectItem value="preinstall">预装</SelectItem>
<SelectItem value="lazy">懒加载</SelectItem>
<SelectItem value="disabled">禁用</SelectItem>
</SelectContent>
</Select>
</td>
<td className="px-3 py-2">
{tool.status === 'installed' ? (
<Badge className="bg-emerald-500/20 text-emerald-400 border-emerald-500/30 text-xs gap-1">
<CheckCircle className="w-3 h-3" />已安装
</Badge>
) : tool.status === 'installing' ? (
<Badge className="bg-amber-500/20 text-amber-400 border-amber-500/30 text-xs gap-1">
<Loader2 className="w-3 h-3 animate-spin" />安装中
</Badge>
) : tool.status === 'failed' ? (
<Badge className="bg-red-500/20 text-red-400 border-red-500/30 text-xs gap-1">
<XCircle className="w-3 h-3" />失败
</Badge>
) : (
<Badge className="bg-slate-500/20 text-slate-400 border-slate-500/30 text-xs gap-1">
<Clock className="w-3 h-3" />未安装
</Badge>
)}
</td>
<td className="px-3 py-2 text-right">
<div className="flex justify-end gap-1">
{tool.install_method === 'lazy' && tool.status !== 'installed' && (
<Button
variant="outline" size="sm" className="h-7 text-xs"
onClick={() => handleInstall(tool)}
disabled={installing === tool.id}
>
{installing === tool.id ? (
<Loader2 className="w-3 h-3 animate-spin mr-1" />
) : (
<Download className="w-3 h-3 mr-1" />
)}
安装
</Button>
{tools.map(tool => {
const hasVersions = VERSIONED_TOOLS.includes(tool.name);
return (
<tr key={tool.id} className="border-b border-[var(--dg-border)] hover:bg-[var(--dg-bg-tertiary)]/50">
<td className="px-3 py-2">
<div className="font-medium text-[var(--dg-text-primary)]">{tool.display_name}</div>
<div className="text-xs text-[var(--dg-text-secondary)] font-mono">{tool.name}</div>
{tool.description && (
<div className="text-[10px] text-[var(--dg-text-muted)] mt-0.5 max-w-[220px] leading-tight">{tool.description}</div>
)}
<Button variant="ghost" size="icon" className="h-7 w-7" onClick={() => handleCheckStatus(tool)} title="检测">
<Settings2 className="w-3.5 h-3.5" />
</Button>
</div>
</td>
</tr>
))}
{tool.installed_version && tool.status === 'installed' && (
<div className="text-xs text-emerald-400 font-mono mt-0.5">v{tool.installed_version}</div>
)}
{tool.error_msg && (
<div className="text-xs text-red-400 mt-0.5 max-w-[200px] truncate" title={tool.error_msg}>{tool.error_msg}</div>
)}
</td>
<td className="px-3 py-2 hidden sm:table-cell">
<Badge className={`text-xs ${categoryColor[tool.category] || categoryColor.other}`}>
{categoryLabel[tool.category] || tool.category}
</Badge>
</td>
<td className="px-3 py-2">
<Select
value={tool.install_method}
onValueChange={(v) => handleMethodChange(tool, v as 'preinstall' | 'lazy' | 'disabled')}
>
<SelectTrigger className="h-7 w-[90px] text-xs">
<SelectValue />
</SelectTrigger>
<SelectContent>
<SelectItem value="preinstall">预装</SelectItem>
<SelectItem value="lazy">懒加载</SelectItem>
<SelectItem value="disabled">禁用</SelectItem>
</SelectContent>
</Select>
</td>
<td className="px-3 py-2">
{tool.status === 'installed' ? (
<Badge className="bg-emerald-500/20 text-emerald-400 border-emerald-500/30 text-xs gap-1">
<CheckCircle className="w-3 h-3" />已安装
</Badge>
) : tool.status === 'installing' ? (
<Badge className="bg-amber-500/20 text-amber-400 border-amber-500/30 text-xs gap-1">
<Loader2 className="w-3 h-3 animate-spin" />安装中
</Badge>
) : tool.status === 'failed' ? (
<Badge className="bg-red-500/20 text-red-400 border-red-500/30 text-xs gap-1">
<XCircle className="w-3 h-3" />失败
</Badge>
) : (
<Badge className="bg-slate-500/20 text-slate-400 border-slate-500/30 text-xs gap-1">
<Clock className="w-3 h-3" />未安装
</Badge>
)}
</td>
<td className="px-3 py-2 text-right">
<div className="flex justify-end gap-1">
{tool.install_method === 'lazy' && tool.status !== 'installed' && (
hasVersions ? (
<Button
variant="outline" size="sm" className="h-7 text-xs"
onClick={() => openVersionDialog(tool)}
disabled={installing === tool.id}
>
{installing === tool.id ? (
<Loader2 className="w-3 h-3 animate-spin mr-1" />
) : (
<Download className="w-3 h-3 mr-1" />
)}
安装
</Button>
) : (
<Button
variant="outline" size="sm" className="h-7 text-xs"
onClick={() => handleInstall(tool)}
disabled={installing === tool.id}
>
{installing === tool.id ? (
<Loader2 className="w-3 h-3 animate-spin mr-1" />
) : (
<Download className="w-3 h-3 mr-1" />
)}
安装
</Button>
)
)}
{tool.install_method === 'lazy' && (
<Button
variant="ghost" size="sm" className="h-7 text-xs text-[var(--dg-text-secondary)]"
onClick={() => handleTestDownload(tool)}
disabled={testing === tool.id}
>
{testing === tool.id ? (
<Loader2 className="w-3 h-3 animate-spin mr-1" />
) : (
<ChevronDown className="w-3 h-3 mr-1" />
)}
测试
</Button>
)}
<Button variant="ghost" size="icon" className="h-7 w-7" onClick={() => handleCheckStatus(tool)} title="检测">
<Settings2 className="w-3.5 h-3.5" />
</Button>
</div>
</td>
</tr>
);
})}
</tbody>
</table>
</div>
)}
{/* ══════════ 版本选择弹框 ══════════ */}
<Dialog open={!!versionDialog} onOpenChange={() => setVersionDialog(null)}>
<DialogContent className="max-w-sm">
<DialogHeader>
<DialogTitle>选择安装版本</DialogTitle>
<DialogDescription>
{versionDialog?.tool.display_name} — 请选择要安装的版本
</DialogDescription>
</DialogHeader>
<div className="space-y-4 py-2">
<div className="space-y-2">
{versionDialog?.versions.map((v, i) => (
<button
key={v.version}
onClick={() => setSelectedVersion(v.version)}
className={`w-full flex items-center justify-between px-3 py-2.5 rounded-lg text-sm border transition-all ${
selectedVersion === v.version
? 'border-indigo-400/50 bg-indigo-400/10 text-[var(--dg-text-primary)]'
: 'border-[var(--dg-border)] bg-[var(--dg-bg-secondary)] text-[var(--dg-text-secondary)] hover:border-[var(--dg-text-secondary)]/30'
}`}
>
<span>{v.label}</span>
<span className="text-xs font-mono text-[var(--dg-text-muted)]">{v.version}</span>
</button>
))}
</div>
<div className="flex justify-end gap-2 pt-2 border-t border-[var(--dg-border)]">
<Button variant="outline" size="sm" onClick={() => setVersionDialog(null)}>取消</Button>
<Button
size="sm"
onClick={() => versionDialog && handleInstall(versionDialog.tool, selectedVersion)}
disabled={!selectedVersion || installing === versionDialog?.tool.id}
>
{installing === versionDialog?.tool.id ? (
<Loader2 className="w-3.5 h-3.5 animate-spin mr-1" />
) : (
<Download className="w-3.5 h-3.5 mr-1" />
)}
安装
</Button>
</div>
</div>
</DialogContent>
</Dialog>
</div>
);
}
@@ -87,6 +87,6 @@ export const PIPELINE_STEPS = [
{ name: '单元测试', status: 'success', duration: '2m 15s' },
{ name: '构建镜像', status: 'success', duration: '3m 30s' },
{ name: '推送镜像', status: 'success', duration: '1m 20s' },
{ name: '部署到K8s', status: 'running', duration: '--' },
{ name: '部署到Kubernetes', status: 'running', duration: '--' },
{ name: '健康检查', status: 'pending', duration: '--' },
];
@@ -45,8 +45,15 @@ export function DeploymentEditAdvanced({ clusterCode, namespace, deploymentName,
const [revisionHistoryLimit, setRevisionHistoryLimit] = useState('10');
const [progressDeadlineSeconds, setProgressDeadlineSeconds] = useState('600');
// Pod 级别
const [nodeSelectorKv, setNodeSelectorKv] = useState<Array<{ key: string; value: string }>>([]);
// ──── 调度策略 ────
const [scheduleMode, setScheduleMode] = useState<'nodeName' | 'nodeSelector' | 'nodeAffinity'>('nodeSelector');
const [nodeName, setNodeName] = useState('');
const [availableNodes, setAvailableNodes] = useState<Array<{ name: string; ip: string; labels: Record<string, string> }>>([]);
const [nodesLoading, setNodesLoading] = useState(false);
// 标签选择器 — key=value 列表(替代原 nodeSelectorKv)
const [labelSelectorKv, setLabelSelectorKv] = useState<Array<{ key: string; value: string }>>([]);
// 预置标签(从节点聚合)
const [nodeLabels, setNodeLabels] = useState<Record<string, string[]>>({});
const [tolerations, setTolerations] = useState<Toleration[]>([]);
const [dnsPolicy, setDnsPolicy] = useState('ClusterFirst');
const [restartPolicy, setRestartPolicy] = useState('Always');
@@ -92,9 +99,48 @@ export function DeploymentEditAdvanced({ clusterCode, namespace, deploymentName,
setRevisionHistoryLimit(spec.revisionHistoryLimit != null ? String(spec.revisionHistoryLimit) : '10');
setProgressDeadlineSeconds(spec.progressDeadlineSeconds != null ? String(spec.progressDeadlineSeconds) : '600');
// nodeSelector
// nodeSelector → labelSelectorKv
const ns = podSpec.nodeSelector || {};
setNodeSelectorKv(Object.entries(ns).map(([k, v]) => ({ key: k, value: String(v) })));
const nsEntries = Object.entries(ns).map(([k, v]) => ({ key: k, value: String(v) }));
setLabelSelectorKv(nsEntries);
// nodeName
setNodeName(podSpec.nodeName || '');
// Determine scheduleMode
if (podSpec.nodeName) {
setScheduleMode('nodeName');
} else if (podSpec.affinity?.nodeAffinity) {
setScheduleMode('nodeAffinity');
} else if (nsEntries.length > 0) {
setScheduleMode('nodeSelector');
}
// 加载节点列表
if (clusterCode) {
setNodesLoading(true);
kubernetesApi.getClusterNodes(clusterCode).then((res: any) => {
const nodes: any[] = Array.isArray(res) ? res : (res?.items || res?.list || []);
const mapped = nodes.map((n: any) => {
const meta = n.metadata || {};
const status = n.status || {};
const addresses: any[] = Array.isArray(status.addresses) ? status.addresses : [];
const internalIP = addresses.find((a: any) => a.type === 'InternalIP')?.address || '';
return { name: meta.name || '', ip: internalIP, labels: meta.labels || {} };
});
setAvailableNodes(mapped);
// 聚合标签
const lblMap: Record<string, string[]> = {};
for (const n of mapped) {
for (const [k, v] of Object.entries(n.labels)) {
const sv = String(v);
if (!lblMap[k]) lblMap[k] = [];
if (!lblMap[k].includes(sv)) lblMap[k].push(sv);
}
}
setNodeLabels(lblMap);
}).catch(() => {}).finally(() => setNodesLoading(false));
}
// tolerations
const tols: any[] = Array.isArray(podSpec.tolerations) ? podSpec.tolerations : [];
@@ -142,11 +188,11 @@ export function DeploymentEditAdvanced({ clusterCode, namespace, deploymentName,
setLoading(false);
}, [manifest]);
// nodeSelector 操作
const addNs = () => setNodeSelectorKv(prev => [...prev, { key: '', value: '' }]);
const removeNs = (i: number) => setNodeSelectorKv(prev => prev.filter((_, idx) => idx !== i));
// labelSelector 操作
const addNs = () => setLabelSelectorKv(prev => [...prev, { key: '', value: '' }]);
const removeNs = (i: number) => setLabelSelectorKv(prev => prev.filter((_, idx) => idx !== i));
const updateNs = (i: number, patch: Partial<{ key: string; value: string }>) =>
setNodeSelectorKv(prev => prev.map((n, idx) => (idx === i ? { ...n, ...patch } : n)));
setLabelSelectorKv(prev => prev.map((n, idx) => (idx === i ? { ...n, ...patch } : n)));
// tolerations 操作
const addTol = () => setTolerations(prev => [...prev, { key: '', operator: 'Equal', value: '', effect: 'NoSchedule', tolerationSeconds: '' }]);
@@ -173,14 +219,38 @@ export function DeploymentEditAdvanced({ clusterCode, namespace, deploymentName,
if (revisionHistoryLimit) base.spec.revisionHistoryLimit = Number(revisionHistoryLimit);
if (progressDeadlineSeconds) base.spec.progressDeadlineSeconds = Number(progressDeadlineSeconds);
// nodeSelector
const nsObj: Record<string, string> = {};
for (const { key, value } of nodeSelectorKv) {
const k = key.trim();
if (k) nsObj[k] = value;
// nodeSelector / nodeName / nodeAffinity
if (scheduleMode === 'nodeName' && nodeName.trim()) {
podSpec.nodeName = nodeName.trim();
delete podSpec.nodeSelector;
if (podSpec.affinity) delete podSpec.affinity.nodeAffinity;
} else if (scheduleMode === 'nodeSelector') {
const nsObj: Record<string, string> = {};
for (const { key, value } of labelSelectorKv) {
const k = key.trim();
if (k) nsObj[k] = value;
}
if (Object.keys(nsObj).length > 0) podSpec.nodeSelector = nsObj;
else delete podSpec.nodeSelector;
if (podSpec.nodeName) delete podSpec.nodeName;
if (podSpec.affinity) delete podSpec.affinity.nodeAffinity;
} else if (scheduleMode === 'nodeAffinity') {
const matchExpressions: any[] = labelSelectorKv
.filter(s => s.key.trim())
.map(s => ({ key: s.key.trim(), operator: 'In', values: [s.value] }));
if (matchExpressions.length > 0) {
podSpec.affinity = podSpec.affinity || {};
podSpec.affinity.nodeAffinity = {
requiredDuringSchedulingIgnoredDuringExecution: {
nodeSelectorTerms: [{ matchExpressions }],
},
};
} else if (podSpec.affinity) {
delete podSpec.affinity.nodeAffinity;
}
delete podSpec.nodeSelector;
if (podSpec.nodeName) delete podSpec.nodeName;
}
if (Object.keys(nsObj).length > 0) podSpec.nodeSelector = nsObj;
else delete podSpec.nodeSelector;
// tolerations
const tolsK8s = tolerations
@@ -335,91 +405,135 @@ export function DeploymentEditAdvanced({ clusterCode, namespace, deploymentName,
</CardContent>
</Card>
{/* 调度:nodeSelector + tolerations */}
{/* 调度:节点名称 / 标签选择器 / 节点亲和性 */}
<Card className="bg-slate-900 border-slate-800">
<CardHeader className="pb-3">
<CardTitle className="text-sm text-slate-200 flex items-center gap-2">
<Server className="h-4 w-4 text-emerald-400" />调度 (Scheduling)
</CardTitle>
</CardHeader>
<CardContent className="pt-0 space-y-3">
{/* nodeSelector */}
<div>
<div className="flex items-center justify-between mb-1">
<Label className="text-slate-400 text-xs">nodeSelector(节点标签选择)</Label>
<Button size="sm" variant="ghost" className="h-6 text-xs text-slate-400" onClick={addNs}>
<Plus className="h-3 w-3 mr-1" />添加
</Button>
<div className="flex items-center justify-between">
<CardTitle className="text-sm text-slate-200 flex items-center gap-2">
<Server className="h-4 w-4 text-emerald-400" />调度 (Scheduling)
</CardTitle>
<div className="flex items-center gap-1 bg-slate-800 rounded-lg p-0.5 border border-slate-700">
{([
{ key: 'nodeName' as const, label: '节点名称', desc: '指定节点' },
{ key: 'nodeSelector' as const, label: '标签选择器', desc: 'key=value' },
{ key: 'nodeAffinity' as const, label: '节点亲和性', desc: '高级规则' },
]).map(m => (
<button key={m.key} onClick={() => setScheduleMode(m.key)}
className={`px-2.5 py-1 rounded text-[10px] font-medium transition-all ${
scheduleMode === m.key
? 'bg-emerald-500/20 text-emerald-300 shadow-sm'
: 'text-slate-400 hover:text-slate-300'
}`}>
{m.label}
</button>
))}
</div>
{nodeSelectorKv.length === 0 ? (
<p className="text-xs text-slate-600 italic">未配置</p>
) : nodeSelectorKv.map((n, i) => (
<div key={i} className="flex items-center gap-2 mb-1.5">
<Input value={n.key} onChange={e => updateNs(i, { key: e.target.value })}
placeholder="disktype" className="flex-1 h-7 bg-slate-800 border-slate-700 text-slate-300 text-xs font-mono" />
<span className="text-slate-600">:</span>
<Input value={n.value} onChange={e => updateNs(i, { value: e.target.value })}
placeholder="ssd" className="flex-1 h-7 bg-slate-800 border-slate-700 text-slate-300 text-xs font-mono" />
<Button size="icon" variant="ghost" className="h-6 w-6 text-red-400" onClick={() => removeNs(i)}>
<Trash2 className="h-3 w-3" />
</div>
<p className="text-xs text-slate-500 mt-1">
{scheduleMode === 'nodeName' && 'Pod 将直接调度到指定节点'}
{scheduleMode === 'nodeSelector' && 'Pod 将调度到匹配标签的节点'}
{scheduleMode === 'nodeAffinity' && '通过亲和性规则控制 Pod 调度到指定节点'}
</p>
</CardHeader>
<CardContent className="pt-0">
{/* 节点名称模式 */}
{scheduleMode === 'nodeName' && (
<div className="space-y-2">
<Label className="text-slate-400 text-xs">请选择节点</Label>
{nodesLoading ? (
<div className="flex items-center gap-1 text-slate-500 text-xs"><Loader2 className="h-3 w-3 animate-spin" />加载节点列表...</div>
) : (
<select value={nodeName} onChange={e => setNodeName(e.target.value)}
className="h-8 w-full bg-slate-800 border border-slate-700 rounded text-xs text-slate-300 px-2">
<option value="">(不指定)</option>
{availableNodes.map(n => (
<option key={n.name} value={n.name}>{n.name} {n.ip ? `(${n.ip})` : ''}</option>
))}
</select>
)}
{nodeName && (
<div className="text-[10px] text-slate-500">
已选择: <code className="bg-slate-800 px-1 py-0.5 rounded text-emerald-400">{nodeName}</code>
</div>
)}
</div>
)}
{/* 标签选择器模式 */}
{scheduleMode === 'nodeSelector' && (
<div className="space-y-2">
<div className="flex items-center justify-between">
<Label className="text-slate-400 text-xs">请选择标签</Label>
<Button size="sm" variant="ghost" className="h-6 text-xs text-slate-400" onClick={addNs}>
<Plus className="h-3 w-3 mr-1" />添加
</Button>
</div>
))}
</div>
{/* tolerations */}
<div>
<div className="flex items-center justify-between mb-1">
<Label className="text-slate-400 text-xs">tolerations(污点容忍)</Label>
<Button size="sm" variant="ghost" className="h-6 text-xs text-slate-400" onClick={addTol}>
<Plus className="h-3 w-3 mr-1" />添加
</Button>
</div>
{tolerations.length === 0 ? (
<p className="text-xs text-slate-600 italic">未配置</p>
) : tolerations.map((t, i) => (
<div key={i} className="bg-slate-950/50 border border-slate-800 rounded p-2 mb-1.5 grid grid-cols-5 gap-2 items-end">
<div>
<Label className="text-slate-500 text-[10px]">key</Label>
<Input value={t.key} onChange={e => updateTol(i, { key: e.target.value })}
placeholder="node-role.kubernetes.io/control-plane"
className="h-7 bg-slate-800 border-slate-700 text-slate-300 text-xs font-mono" />
</div>
<div>
<Label className="text-slate-500 text-[10px]">operator</Label>
<select value={t.operator} onChange={e => updateTol(i, { operator: e.target.value })}
className="h-7 w-full bg-slate-800 border border-slate-700 rounded text-xs text-slate-300 px-1">
<option value="Equal">Equal</option>
<option value="Exists">Exists</option>
{labelSelectorKv.length === 0 ? (
<p className="text-xs text-slate-600 italic">未配置标签选择器</p>
) : labelSelectorKv.map((n, i) => (
<div key={i} className="flex items-center gap-2">
{/* 标签 Key 下拉 */}
<select value={n.key} onChange={e => updateNs(i, { key: e.target.value, value: '' })}
className="flex-1 h-7 bg-slate-800 border border-slate-700 rounded text-xs text-slate-300 px-1.5">
<option value="">选择标签</option>
{Object.entries(nodeLabels).map(([k, vals]) => (
<option key={k} value={k}>{k} ({vals.length})</option>
))}
</select>
</div>
<div>
<Label className="text-slate-500 text-[10px]">value</Label>
<Input value={t.value} onChange={e => updateTol(i, { value: e.target.value })}
disabled={t.operator === 'Exists'}
className="h-7 bg-slate-800 border-slate-700 text-slate-300 text-xs font-mono disabled:opacity-40" />
</div>
<div>
<Label className="text-slate-500 text-[10px]">effect</Label>
<select value={t.effect} onChange={e => updateTol(i, { effect: e.target.value })}
className="h-7 w-full bg-slate-800 border border-slate-700 rounded text-xs text-slate-300 px-1">
<option value="">(all)</option>
<option value="NoSchedule">NoSchedule</option>
<option value="PreferNoSchedule">PreferNoSchedule</option>
<option value="NoExecute">NoExecute</option>
{/* 标签 Value 下拉 */}
<select value={n.value} onChange={e => updateNs(i, { value: e.target.value })}
className="flex-1 h-7 bg-slate-800 border border-slate-700 rounded text-xs text-slate-300 px-1.5"
disabled={!n.key}>
<option value="">选择值</option>
{(nodeLabels[n.key] || []).map(v => (
<option key={v} value={v}>{v}</option>
))}
</select>
</div>
<div className="flex items-center gap-1">
<Input value={t.tolerationSeconds} onChange={e => updateTol(i, { tolerationSeconds: e.target.value })}
disabled={t.effect !== 'NoExecute'} placeholder="秒"
className="h-7 bg-slate-800 border-slate-700 text-slate-300 text-xs font-mono disabled:opacity-40" />
<Button size="icon" variant="ghost" className="h-6 w-6 text-red-400" onClick={() => removeTol(i)}>
<Button size="icon" variant="ghost" className="h-6 w-6 text-red-400" onClick={() => removeNs(i)}>
<Trash2 className="h-3 w-3" />
</Button>
</div>
))}
</div>
)}
{/* 节点亲和性模式 */}
{scheduleMode === 'nodeAffinity' && (
<div className="space-y-2">
<div className="flex items-center justify-between">
<Label className="text-slate-400 text-xs">
请选择标签 <span className="text-slate-600">(生成 requiredDuringScheduling 规则)</span>
</Label>
<Button size="sm" variant="ghost" className="h-6 text-xs text-slate-400" onClick={addNs}>
<Plus className="h-3 w-3 mr-1" />添加
</Button>
</div>
))}
</div>
{labelSelectorKv.length === 0 ? (
<p className="text-xs text-slate-600 italic">未配置亲和性规则</p>
) : labelSelectorKv.map((n, i) => (
<div key={i} className="flex items-center gap-2">
<select value={n.key} onChange={e => updateNs(i, { key: e.target.value, value: '' })}
className="flex-1 h-7 bg-slate-800 border border-slate-700 rounded text-xs text-slate-300 px-1.5">
<option value="">选择标签</option>
{Object.entries(nodeLabels).map(([k, vals]) => (
<option key={k} value={k}>{k} ({vals.length})</option>
))}
</select>
<select value={n.value} onChange={e => updateNs(i, { value: e.target.value })}
className="flex-1 h-7 bg-slate-800 border border-slate-700 rounded text-xs text-slate-300 px-1.5"
disabled={!n.key}>
<option value="">选择值</option>
{(nodeLabels[n.key] || []).map(v => (
<option key={v} value={v}>{v}</option>
))}
</select>
<Button size="icon" variant="ghost" className="h-6 w-6 text-red-400" onClick={() => removeNs(i)}>
<Trash2 className="h-3 w-3" />
</Button>
</div>
))}
</div>
)}
</CardContent>
</Card>
@@ -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>
);
}
@@ -1,15 +1,15 @@
// DeploymentEditStorage.tsx — 编辑器「存储挂载」Tab (M8)
// 编辑内容:spec.template.spec.volumes[] — 数据卷定义
// 支持 6 种常用 volume 类型:emptyDir / hostPath / configMap / secret / persistentVolumeClaim / nfs
// 作者: Logan <admin@attacker.club>
// DeploymentEditStorage.tsx — 编辑器「存储挂载」Tab
// Kuboard 风格:左侧定义数据卷 / 右侧挂载到容器
// 支持 6 种卷类型:PVC / EmptyDir / HostPath / NFS / ConfigMap / Secret
import { useState, useEffect } from 'react';
import { Card, CardContent, CardHeader, CardTitle } 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 { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';
import {
Plus, Trash2, Save, Loader2, HardDrive, Database, Folder, Lock,
Plus, Trash2, Save, Loader2, HardDrive, Database, Folder, Lock, File, Disc, Server,
} from 'lucide-react';
import { useToast } from '@/hooks/use-toast';
import { kubernetesApi } from '@/services/api';
@@ -23,172 +23,130 @@ interface Props {
onCancel: () => void;
}
/** 单个 volume 的编辑态 */
/** 数据卷定义 */
interface VolumeForm {
name: string;
type: 'emptyDir' | 'hostPath' | 'configMap' | 'secret' | 'persistentVolumeClaim' | 'nfs';
// 各类型字段(仅对应类型有效)
medium?: string; // emptyDir.medium: "" | "Memory"
sizeLimit?: string; // emptyDir.sizeLimit
path?: string; // hostPath.path
pathType?: string; // hostPath.pathType: Directory | File | Socket | ...
configMapName?: string; // configMap.name
secretName?: string; // secret.secretName
pvcName?: string; // persistentVolumeClaim.claimName
nfsServer?: string; // nfs.server
nfsPath?: string; // nfs.path
readOnly?: boolean; // pvc/nfs readOnly
items?: string; // configMap/secret items (JSON 文本,高级用户)
type: 'persistentVolumeClaim' | 'emptyDir' | 'hostPath' | 'nfs' | 'configMap' | 'secret';
// PVC
pvcName?: string; pvcReadOnly?: boolean;
// EmptyDir
medium?: string; sizeLimit?: string;
// HostPath
path?: string; pathType?: string;
// NFS
nfsServer?: string; nfsPath?: string; nfsReadOnly?: boolean;
// ConfigMap
configMapName?: string; cmItems?: string;
// Secret
secretName?: string; secItems?: string;
}
/** 从 K8s volume 对象提取为 form */
/** 容器挂载点 */
interface MountForm {
containerName: string;
volumeName: string;
mountPath: string;
subPath: string;
readOnly: boolean;
}
const VOLUME_TYPES: { key: VolumeForm['type']; label: string; icon: typeof HardDrive; color: string; desc: string }[] = [
{ key: 'persistentVolumeClaim', label: '存储卷声明', icon: Database, color: 'text-emerald-400', desc: 'PVC' },
{ key: 'emptyDir', label: '临时目录', icon: Disc, color: 'text-slate-400', desc: 'EmptyDir' },
{ key: 'hostPath', label: 'HostPath', icon: HardDrive, color: 'text-amber-400', desc: '主机路径' },
{ key: 'nfs', label: 'NFS', icon: Server, color: 'text-purple-400', desc: '网络存储' },
{ key: 'configMap', label: '配置字典', icon: File, color: 'text-blue-400', desc: 'ConfigMap' },
{ key: 'secret', label: '密文', icon: Lock, color: 'text-rose-400', desc: 'Secret' },
];
function volumeToForm(v: any): VolumeForm {
if (!v || typeof v !== 'object') return { name: '', type: 'emptyDir' };
const name = v.name || '';
if (v.emptyDir) {
return {
name, type: 'emptyDir',
medium: v.emptyDir.medium || '',
sizeLimit: v.emptyDir.sizeLimit || '',
};
}
if (v.hostPath) {
return {
name, type: 'hostPath',
path: v.hostPath.path || '',
pathType: v.hostPath.type || 'Directory',
};
}
if (v.configMap) {
return {
name, type: 'configMap',
configMapName: v.configMap.name || '',
items: v.configMap.items ? JSON.stringify(v.configMap.items) : '',
};
}
if (v.secret) {
return {
name, type: 'secret',
secretName: v.secret.secretName || '',
items: v.secret.items ? JSON.stringify(v.secret.items) : '',
};
}
if (v.persistentVolumeClaim) {
return {
name, type: 'persistentVolumeClaim',
pvcName: v.persistentVolumeClaim.claimName || '',
readOnly: !!v.persistentVolumeClaim.readOnly,
};
}
if (v.nfs) {
return {
name, type: 'nfs',
nfsServer: v.nfs.server || '',
nfsPath: v.nfs.path || '',
readOnly: !!v.nfs.readOnly,
};
}
// 未识别类型 — fallback 为 emptyDir 占位
if (v.emptyDir) return { name, type: 'emptyDir', medium: v.emptyDir.medium || '', sizeLimit: v.emptyDir.sizeLimit || '' };
if (v.hostPath) return { name, type: 'hostPath', path: v.hostPath.path || '', pathType: v.hostPath.type || 'Directory' };
if (v.configMap) return { name, type: 'configMap', configMapName: v.configMap.name || '', cmItems: v.configMap.items ? JSON.stringify(v.configMap.items) : '' };
if (v.secret) return { name, type: 'secret', secretName: v.secret.secretName || '', secItems: v.secret.items ? JSON.stringify(v.secret.items) : '' };
if (v.persistentVolumeClaim) return { name, type: 'persistentVolumeClaim', pvcName: v.persistentVolumeClaim.claimName || '', pvcReadOnly: !!v.persistentVolumeClaim.readOnly };
if (v.nfs) return { name, type: 'nfs', nfsServer: v.nfs.server || '', nfsPath: v.nfs.path || '', nfsReadOnly: !!v.nfs.readOnly };
return { name, type: 'emptyDir' };
}
/** 将 form 转回 K8s volume 对象 */
function formToVolume(f: VolumeForm): any {
const v: any = { name: f.name.trim() };
if (!v.name) return null; // 无名 volume 跳过
if (!v.name) return null;
switch (f.type) {
case 'emptyDir': {
const ed: any = {};
if (f.medium) ed.medium = f.medium;
if (f.sizeLimit) ed.sizeLimit = f.sizeLimit;
v.emptyDir = ed;
break;
}
case 'hostPath': {
v.hostPath = {
path: f.path || '',
type: f.pathType || 'Directory',
};
break;
}
case 'configMap': {
v.configMap = { name: f.configMapName || '' };
if (f.items) {
try { v.configMap.items = JSON.parse(f.items); } catch {}
}
break;
}
case 'secret': {
v.secret = { secretName: f.secretName || '' };
if (f.items) {
try { v.secret.items = JSON.parse(f.items); } catch {}
}
break;
}
case 'persistentVolumeClaim': {
v.persistentVolumeClaim = {
claimName: f.pvcName || '',
...(f.readOnly ? { readOnly: true } : {}),
};
break;
}
case 'nfs': {
v.nfs = {
server: f.nfsServer || '',
path: f.nfsPath || '',
...(f.readOnly ? { readOnly: true } : {}),
};
break;
}
case 'emptyDir': { const ed: any = {}; if (f.medium) ed.medium = f.medium; if (f.sizeLimit) ed.sizeLimit = f.sizeLimit; v.emptyDir = ed; break; }
case 'hostPath': v.hostPath = { path: f.path || '', type: f.pathType || 'Directory' }; break;
case 'configMap': { v.configMap = { name: f.configMapName || '' }; if (f.cmItems) try { v.configMap.items = JSON.parse(f.cmItems); } catch {} break; }
case 'secret': { v.secret = { secretName: f.secretName || '' }; if (f.secItems) try { v.secret.items = JSON.parse(f.secItems); } catch {} break; }
case 'persistentVolumeClaim': v.persistentVolumeClaim = { claimName: f.pvcName || '', ...(f.pvcReadOnly ? { readOnly: true } : {}) }; break;
case 'nfs': v.nfs = { server: f.nfsServer || '', path: f.nfsPath || '', ...(f.nfsReadOnly ? { readOnly: true } : {}) }; break;
}
return v;
}
const TYPE_META: Record<VolumeForm['type'], { label: string; icon: typeof HardDrive; color: string }> = {
emptyDir: { label: 'emptyDir', icon: Folder, color: 'text-slate-300' },
hostPath: { label: 'hostPath', icon: HardDrive, color: 'text-amber-400' },
configMap: { label: 'configMap', icon: Folder, color: 'text-blue-400' },
secret: { label: 'secret', icon: Lock, color: 'text-rose-400' },
persistentVolumeClaim: { label: 'PVC', icon: Database, color: 'text-emerald-400' },
nfs: { label: 'NFS', icon: HardDrive, color: 'text-purple-400' },
};
export function DeploymentEditStorage({ clusterCode, namespace, deploymentName, manifest, onSaved, onCancel }: Props) {
const { toast } = useToast();
const [saving, setSaving] = useState(false);
const [loading, setLoading] = useState(!manifest);
const [volumes, setVolumes] = useState<VolumeForm[]>([]);
const [rawManifest, setRawManifest] = useState<any>(manifest || {});
// 容器已声明的 volumeMounts(只读展示,便于用户对齐 volume name)
const [mountSummary, setMountSummary] = useState<Array<{ container: string; mounts: string[] }>>([]);
const [volumes, setVolumes] = useState<VolumeForm[]>([]);
const [mounts, setMounts] = useState<MountForm[]>([]);
const [containers, setContainers] = useState<string[]>([]);
useEffect(() => {
const m = manifest;
if (!m) { setLoading(false); return; }
setRawManifest(m);
const podSpec = m?.spec?.template?.spec || {};
// 数据卷
const vols: any[] = Array.isArray(podSpec.volumes) ? podSpec.volumes : [];
setVolumes(vols.map(volumeToForm));
// 汇总容器 volumeMounts
// 容器列表
const allContainers = [
...(podSpec.containers || []),
...(podSpec.initContainers || []),
];
const summary = allContainers.map((c: any) => ({
container: c.name || '(unnamed)',
mounts: (Array.isArray(c.volumeMounts) ? c.volumeMounts : [])
.map((vm: any) => `${vm.name}:${vm.mountPath}${vm.readOnly ? '(ro)' : ''}`),
})).filter((s: any) => s.mounts.length > 0);
setMountSummary(summary);
const containerNames = allContainers.map((c: any) => c.name || '(unnamed)');
setContainers(containerNames);
// 挂载点
const allMounts: MountForm[] = [];
for (const c of allContainers) {
const cName = c.name || '(unnamed)';
const vms: any[] = Array.isArray(c.volumeMounts) ? c.volumeMounts : [];
for (const vm of vms) {
allMounts.push({
containerName: cName,
volumeName: vm.name || '',
mountPath: vm.mountPath || '',
subPath: vm.subPath || '',
readOnly: !!vm.readOnly,
});
}
}
setMounts(allMounts);
setLoading(false);
}, [manifest]);
// Volume operations
const addVolume = () => setVolumes(prev => [...prev, { name: '', type: 'emptyDir' }]);
const removeVolume = (i: number) => setVolumes(prev => prev.filter((_, idx) => idx !== i));
const removeVolume = (i: number) => {
const name = volumes[i]?.name;
setVolumes(prev => prev.filter((_, idx) => idx !== i));
if (name) setMounts(prev => prev.filter(m => m.volumeName !== name));
};
const updateVolume = (i: number, patch: Partial<VolumeForm>) =>
setVolumes(prev => prev.map((v, idx) => (idx === i ? { ...v, ...patch } : v)));
// Mount operations
const addMount = () => setMounts(prev => [...prev, { containerName: containers[0] || '', volumeName: '', mountPath: '', subPath: '', readOnly: false }]);
const removeMount = (i: number) => setMounts(prev => prev.filter((_, idx) => idx !== i));
const updateMount = (i: number, patch: Partial<MountForm>) =>
setMounts(prev => prev.map((m, idx) => (idx === i ? { ...m, ...patch } : m)));
const save = async () => {
setSaving(true);
try {
@@ -196,17 +154,35 @@ export function DeploymentEditStorage({ clusterCode, namespace, deploymentName,
base.spec = base.spec || {};
base.spec.template = base.spec.template || {};
base.spec.template.spec = base.spec.template.spec || {};
const podSpec = base.spec.template.spec;
// Save volumes
const k8sVols = volumes.map(formToVolume).filter(Boolean);
if (k8sVols.length > 0) {
base.spec.template.spec.volumes = k8sVols;
} else {
delete base.spec.template.spec.volumes;
if (k8sVols.length > 0) podSpec.volumes = k8sVols;
else delete podSpec.volumes;
// Save volumeMounts to each container
const allContainers = [...(podSpec.containers || []), ...(podSpec.initContainers || [])];
for (const c of allContainers) {
const cName = c.name || '(unnamed)';
const cMounts = mounts
.filter(m => m.containerName === cName && m.volumeName && m.mountPath)
.map(m => {
const vm: any = { name: m.volumeName, mountPath: m.mountPath, readOnly: m.readOnly };
if (m.subPath) vm.subPath = m.subPath;
return vm;
});
if (cMounts.length > 0) c.volumeMounts = cMounts;
else delete c.volumeMounts;
}
// Rebuild containers arrays
podSpec.containers = allContainers.filter((c: any) => !(podSpec.initContainers || []).includes(c));
podSpec.initContainers = (podSpec.initContainers || []);
const json = JSON.stringify(base, null, 2);
await kubernetesApi.updateResourceYaml(clusterCode, namespace, 'deployments', deploymentName, json);
toast({ title: '存储配置已保存', description: `${deploymentName} volumes 更新已提交` });
toast({ title: '存储配置已保存', description: `${deploymentName} 更新已提交` });
onSaved();
} catch (e: any) {
toast({ title: '保存失败', description: e?.message || String(e), variant: 'destructive' });
@@ -234,159 +210,138 @@ export function DeploymentEditStorage({ clusterCode, namespace, deploymentName,
);
}
const volumeNames = volumes.map(v => v.name).filter(Boolean);
return (
<div className="space-y-4">
{/* 数据卷列表 */}
{/* ══════════ 定义数据卷 ══════════ */}
<Card className="bg-slate-900 border-slate-800">
<CardHeader className="pb-3">
<div className="flex items-center justify-between">
<CardTitle className="text-sm text-slate-200 flex items-center gap-2">
<Database className="h-4 w-4 text-emerald-400" />
数据卷 (Volumes)
<Database className="h-4 w-4 text-emerald-400" />定义数据卷
<Badge variant="outline" className="border-slate-700 text-slate-400">{volumes.length}</Badge>
</CardTitle>
<Button size="sm" variant="outline" className="h-7 border-slate-700 text-slate-300 text-xs" onClick={addVolume}>
<Plus className="h-3 w-3 mr-1" />添加数据卷
</Button>
</div>
<p className="text-xs text-slate-500 mt-1">
Pod 级别的卷定义,容器通过 <code className="text-slate-400">volumeMounts</code> 引用这些卷名。
</p>
</CardHeader>
<CardContent className="pt-0 space-y-3">
{volumes.length === 0 ? (
<div className="text-center py-8 text-slate-500 text-sm border border-dashed border-slate-800 rounded-lg">
<Database className="h-8 w-8 mx-auto mb-2 text-slate-700" />
未配置数据卷,点击右上角「添加数据卷」
未配置数据卷
</div>
) : volumes.map((vol, i) => {
const meta = TYPE_META[vol.type];
const Icon = meta.icon;
const vtype = VOLUME_TYPES.find(t => t.key === vol.type);
const VIcon = vtype?.icon || Folder;
return (
<div key={i} className="bg-slate-950/50 border border-slate-800 rounded-lg p-3 space-y-3">
<div className="flex items-center gap-3">
<Icon className={`h-4 w-4 ${meta.color}`} />
<Input
value={vol.name}
onChange={e => updateVolume(i, { name: e.target.value })}
<div key={i} className="bg-slate-950/50 border border-slate-800 rounded-lg p-3 space-y-2.5">
{/* 卷名 + 类型 */}
<div className="flex items-center gap-2">
<VIcon className={`h-4 w-4 ${vtype?.color || 'text-slate-400'}`} />
<span className="text-[10px] text-slate-500 w-16 shrink-0">数据卷名称</span>
<Input value={vol.name} onChange={e => updateVolume(i, { name: e.target.value })}
placeholder="volume-name"
className="flex-1 h-8 bg-slate-800 border-slate-700 text-slate-200 text-sm font-mono"
/>
<select
value={vol.type}
onChange={e => updateVolume(i, { type: e.target.value as VolumeForm['type'] })}
className="h-8 bg-slate-800 border border-slate-700 rounded text-xs text-slate-300 px-2"
>
{Object.entries(TYPE_META).map(([t, m]) => (
<option key={t} value={t}>{m.label}</option>
))}
</select>
<Button size="icon" variant="ghost" className="h-7 w-7 text-red-400 hover:text-red-300"
onClick={() => removeVolume(i)}>
className="h-7 flex-1 bg-slate-800 border-slate-700 text-slate-300 text-xs font-mono" />
<Select value={vol.type} onValueChange={v => updateVolume(i, { type: v as VolumeForm['type'] })}>
<SelectTrigger className="h-7 w-[120px] bg-slate-800 border-slate-700 text-xs text-slate-300">
<div className="flex items-center gap-1.5">
<VIcon className="h-3 w-3" />{vtype?.label || vol.type}
</div>
</SelectTrigger>
<SelectContent>
{VOLUME_TYPES.map(t => {
const TI = t.icon;
return (
<SelectItem key={t.key} value={t.key}>
<span className="flex items-center gap-1.5 text-xs">
<TI className="h-3 w-3" />{t.label}
</span>
</SelectItem>
);
})}
</SelectContent>
</Select>
<Button size="icon" variant="ghost" className="h-7 w-7 text-red-400" onClick={() => removeVolume(i)}>
<Trash2 className="h-3.5 w-3.5" />
</Button>
</div>
{/* 类型相关字段 */}
{/* 类型指定字段 */}
{vol.type === 'persistentVolumeClaim' && (
<div className="flex items-center gap-2 pl-[88px]">
<Input value={vol.pvcName || ''} onChange={e => updateVolume(i, { pvcName: e.target.value })}
placeholder="PVC 名称" className="h-7 flex-1 bg-slate-800 border-slate-700 text-slate-300 text-xs font-mono" />
<label className="flex items-center gap-1.5 text-xs text-slate-400 cursor-pointer whitespace-nowrap">
<input type="checkbox" checked={!!vol.pvcReadOnly}
onChange={e => updateVolume(i, { pvcReadOnly: e.target.checked })}
className="accent-blue-500" />只读
</label>
</div>
)}
{vol.type === 'emptyDir' && (
<div className="grid grid-cols-2 gap-3 pl-7">
<div>
<Label className="text-slate-500 text-xs">medium (留空=磁盘, Memory=tmpfs)</Label>
<Input value={vol.medium || ''} onChange={e => updateVolume(i, { medium: e.target.value })}
placeholder="" className="h-7 mt-1 bg-slate-800 border-slate-700 text-slate-300 text-xs font-mono" />
</div>
<div>
<Label className="text-slate-500 text-xs">sizeLimit (例: 512Mi)</Label>
<Input value={vol.sizeLimit || ''} onChange={e => updateVolume(i, { sizeLimit: e.target.value })}
placeholder="512Mi" className="h-7 mt-1 bg-slate-800 border-slate-700 text-slate-300 text-xs font-mono" />
</div>
<div className="flex items-center gap-2 pl-[88px]">
<Input value={vol.sizeLimit || ''} onChange={e => updateVolume(i, { sizeLimit: e.target.value })}
placeholder="sizeLimit (如 512Mi, 可为空)"
className="h-7 flex-1 bg-slate-800 border-slate-700 text-slate-300 text-xs font-mono" />
</div>
)}
{vol.type === 'hostPath' && (
<div className="grid grid-cols-2 gap-3 pl-7">
<div>
<Label className="text-slate-500 text-xs">主机路径 path</Label>
<Input value={vol.path || ''} onChange={e => updateVolume(i, { path: e.target.value })}
placeholder="/data/app" className="h-7 mt-1 bg-slate-800 border-slate-700 text-slate-300 text-xs font-mono" />
</div>
<div>
<Label className="text-slate-500 text-xs">pathType</Label>
<select value={vol.pathType || 'Directory'} onChange={e => updateVolume(i, { pathType: e.target.value })}
className="h-7 mt-1 w-full bg-slate-800 border border-slate-700 rounded text-xs text-slate-300 px-2">
<option value="Directory">Directory</option>
<option value="File">File</option>
<option value="Socket">Socket</option>
<option value="CharDevice">CharDevice</option>
<option value="BlockDevice">BlockDevice</option>
<option value="">(空)</option>
</select>
</div>
</div>
)}
{vol.type === 'configMap' && (
<div className="pl-7">
<Label className="text-slate-500 text-xs">ConfigMap 名称</Label>
<Input value={vol.configMapName || ''} onChange={e => updateVolume(i, { configMapName: e.target.value })}
placeholder="app-config" className="h-7 mt-1 bg-slate-800 border-slate-700 text-slate-300 text-xs font-mono" />
<Label className="text-slate-500 text-xs mt-2 block">items (JSON, 可选)</Label>
<Input value={vol.items || ''} onChange={e => updateVolume(i, { items: e.target.value })}
placeholder='[{"key":"app.conf","path":"app.conf"}]'
className="h-7 mt-1 bg-slate-800 border-slate-700 text-slate-300 text-xs font-mono" />
</div>
)}
{vol.type === 'secret' && (
<div className="pl-7">
<Label className="text-slate-500 text-xs">Secret 名称</Label>
<Input value={vol.secretName || ''} onChange={e => updateVolume(i, { secretName: e.target.value })}
placeholder="app-tls" className="h-7 mt-1 bg-slate-800 border-slate-700 text-slate-300 text-xs font-mono" />
<Label className="text-slate-500 text-xs mt-2 block">items (JSON, 可选)</Label>
<Input value={vol.items || ''} onChange={e => updateVolume(i, { items: e.target.value })}
placeholder='[{"key":"tls.crt","path":"tls.crt"}]'
className="h-7 mt-1 bg-slate-800 border-slate-700 text-slate-300 text-xs font-mono" />
</div>
)}
{vol.type === 'persistentVolumeClaim' && (
<div className="grid grid-cols-2 gap-3 pl-7">
<div>
<Label className="text-slate-500 text-xs">PVC claimName</Label>
<Input value={vol.pvcName || ''} onChange={e => updateVolume(i, { pvcName: e.target.value })}
placeholder="data-pvc" className="h-7 mt-1 bg-slate-800 border-slate-700 text-slate-300 text-xs font-mono" />
</div>
<div className="flex items-end pb-1">
<label className="flex items-center gap-2 text-xs text-slate-400 cursor-pointer">
<input type="checkbox" checked={!!vol.readOnly}
onChange={e => updateVolume(i, { readOnly: e.target.checked })}
className="accent-blue-500" />
readOnly
</label>
</div>
<div className="flex items-center gap-2 pl-[88px]">
<Input value={vol.path || ''} onChange={e => updateVolume(i, { path: e.target.value })}
placeholder="主机路径 /data/app"
className="h-7 flex-1 bg-slate-800 border-slate-700 text-slate-300 text-xs font-mono" />
<select value={vol.pathType || 'Directory'} onChange={e => updateVolume(i, { pathType: e.target.value })}
className="h-7 w-28 bg-slate-800 border border-slate-700 rounded text-xs text-slate-300 px-1.5">
<option value="Directory">Directory</option>
<option value="File">File</option>
<option value="">(默认)</option>
</select>
</div>
)}
{vol.type === 'nfs' && (
<div className="grid grid-cols-3 gap-3 pl-7">
<div>
<Label className="text-slate-500 text-xs">server</Label>
<Input value={vol.nfsServer || ''} onChange={e => updateVolume(i, { nfsServer: e.target.value })}
placeholder="10.10.10.100" className="h-7 mt-1 bg-slate-800 border-slate-700 text-slate-300 text-xs font-mono" />
</div>
<div>
<Label className="text-slate-500 text-xs">path</Label>
<Input value={vol.nfsPath || ''} onChange={e => updateVolume(i, { nfsPath: e.target.value })}
placeholder="/export/data" className="h-7 mt-1 bg-slate-800 border-slate-700 text-slate-300 text-xs font-mono" />
</div>
<div className="flex items-end pb-1">
<label className="flex items-center gap-2 text-xs text-slate-400 cursor-pointer">
<input type="checkbox" checked={!!vol.readOnly}
onChange={e => updateVolume(i, { readOnly: e.target.checked })}
className="accent-blue-500" />
readOnly
</label>
</div>
<div className="flex items-center gap-2 pl-[88px]">
<Input value={vol.nfsServer || ''} onChange={e => updateVolume(i, { nfsServer: e.target.value })}
placeholder="NFS Server IP"
className="h-7 w-40 bg-slate-800 border-slate-700 text-slate-300 text-xs font-mono" />
<span className="text-slate-600 text-xs">:</span>
<Input value={vol.nfsPath || ''} onChange={e => updateVolume(i, { nfsPath: e.target.value })}
placeholder="/export/path"
className="h-7 flex-1 bg-slate-800 border-slate-700 text-slate-300 text-xs font-mono" />
<label className="flex items-center gap-1.5 text-xs text-slate-400 cursor-pointer whitespace-nowrap">
<input type="checkbox" checked={!!vol.nfsReadOnly}
onChange={e => updateVolume(i, { nfsReadOnly: e.target.checked })}
className="accent-blue-500" />只读
</label>
</div>
)}
{vol.type === 'configMap' && (
<div className="flex items-center gap-2 pl-[88px]">
<span className="text-[10px] text-slate-500 whitespace-nowrap">ConfigMap</span>
<Input value={vol.configMapName || ''} onChange={e => updateVolume(i, { configMapName: e.target.value })}
placeholder="ConfigMap 名称"
className="h-7 flex-1 bg-slate-800 border-slate-700 text-slate-300 text-xs font-mono" />
<Input value={vol.cmItems || ''} onChange={e => updateVolume(i, { cmItems: e.target.value })}
placeholder="KeyToPath (可为空)"
className="h-7 w-40 bg-slate-800 border-slate-700 text-slate-300 text-xs font-mono" />
</div>
)}
{vol.type === 'secret' && (
<div className="flex items-center gap-2 pl-[88px]">
<span className="text-[10px] text-slate-500 whitespace-nowrap">密文</span>
<Input value={vol.secretName || ''} onChange={e => updateVolume(i, { secretName: e.target.value })}
placeholder="Secret 名称"
className="h-7 flex-1 bg-slate-800 border-slate-700 text-slate-300 text-xs font-mono" />
<Input value={vol.secItems || ''} onChange={e => updateVolume(i, { secItems: e.target.value })}
placeholder="KeyToPath (可为空)"
className="h-7 w-40 bg-slate-800 border-slate-700 text-slate-300 text-xs font-mono" />
</div>
)}
</div>
@@ -395,41 +350,69 @@ export function DeploymentEditStorage({ clusterCode, namespace, deploymentName,
</CardContent>
</Card>
{/* 容器 volumeMounts 汇总(只读) */}
{mountSummary.length > 0 && (
<Card className="bg-slate-900 border-slate-800">
<CardHeader className="pb-3">
{/* ══════════ 挂载到容器 ══════════ */}
<Card className="bg-slate-900 border-slate-800">
<CardHeader className="pb-3">
<div className="flex items-center justify-between">
<CardTitle className="text-sm text-slate-200 flex items-center gap-2">
<Folder className="h-4 w-4 text-blue-400" />
容器挂载点 (volumeMounts)
<Folder className="h-4 w-4 text-blue-400" />将数据卷挂载到容器
<Badge variant="outline" className="border-slate-700 text-slate-400">{mounts.length}</Badge>
</CardTitle>
<p className="text-xs text-slate-500 mt-1">
容器侧已声明的挂载,请在「容器信息」Tab 修改。
</p>
</CardHeader>
<CardContent className="pt-0 space-y-2">
{mountSummary.map((s, i) => (
<div key={i} className="flex items-start gap-2 text-xs">
<Badge variant="outline" className="border-slate-700 text-slate-400 font-mono shrink-0">
{s.container}
</Badge>
<div className="flex flex-wrap gap-1.5">
{s.mounts.map((m, j) => (
<code key={j} className="bg-slate-800 px-1.5 py-0.5 rounded text-slate-300 text-[11px]">{m}</code>
))}
</div>
<Button size="sm" variant="outline" className="h-7 border-slate-700 text-slate-300 text-xs" onClick={addMount}
disabled={volumeNames.length === 0 || containers.length === 0}>
<Plus className="h-3 w-3 mr-1" />添加挂载
</Button>
</div>
</CardHeader>
<CardContent className="pt-0 space-y-2">
{mounts.length === 0 ? (
<div className="text-center py-8 text-slate-500 text-sm border border-dashed border-slate-800 rounded-lg">
<Folder className="h-8 w-8 mx-auto mb-2 text-slate-700" />
{volumeNames.length === 0 ? '请先定义数据卷' : '未配置挂载点'}
</div>
) : mounts.map((m, i) => (
<div key={i} className="flex items-center gap-2 bg-slate-950/50 border border-slate-800 rounded-lg p-2.5">
{/* 容器选择 */}
<span className="text-[10px] text-slate-500 whitespace-nowrap">容器:</span>
<select value={m.containerName} onChange={e => updateMount(i, { containerName: e.target.value })}
className="h-7 bg-slate-800 border border-slate-700 rounded text-xs text-slate-300 px-1.5 min-w-[120px]">
{containers.length === 0 && <option value="">(无容器)</option>}
{containers.map(cn => <option key={cn} value={cn}>{cn}</option>)}
</select>
{/* 数据卷选择 */}
<select value={m.volumeName} onChange={e => updateMount(i, { volumeName: e.target.value })}
className="h-7 bg-slate-800 border border-slate-700 rounded text-xs text-slate-300 px-1.5 min-w-[100px]">
<option value="">选择数据卷</option>
{volumeNames.map(vn => <option key={vn} value={vn}>{vn}</option>)}
</select>
{/* 挂载路径 */}
<Input value={m.mountPath} onChange={e => updateMount(i, { mountPath: e.target.value })}
placeholder="挂载路径 /app/data"
className="h-7 flex-1 bg-slate-800 border-slate-700 text-slate-300 text-xs font-mono" />
{/* 只读/读写 */}
<div className="flex items-center gap-1 bg-slate-800 rounded-lg p-0.5 border border-slate-700">
<button onClick={() => updateMount(i, { readOnly: false })}
className={`px-2 py-0.5 rounded text-[10px] font-medium transition-all ${!m.readOnly ? 'bg-blue-500/20 text-blue-300' : 'text-slate-500'}`}>
读写
</button>
<button onClick={() => updateMount(i, { readOnly: true })}
className={`px-2 py-0.5 rounded text-[10px] font-medium transition-all ${m.readOnly ? 'bg-amber-500/20 text-amber-300' : 'text-slate-500'}`}>
只读
</button>
</div>
))}
</CardContent>
</Card>
)}
<Button size="icon" variant="ghost" className="h-7 w-7 text-red-400" onClick={() => removeMount(i)}>
<Trash2 className="h-3.5 w-3.5" />
</Button>
</div>
))}
</CardContent>
</Card>
{/* 操作栏 */}
<div className="flex justify-end gap-2 pt-2">
<Button variant="outline" className="border-slate-700 text-slate-400" onClick={onCancel}>取消</Button>
<Button className="bg-blue-600 hover:bg-blue-700" disabled={saving} onClick={save}>
{saving ? <Loader2 className="h-4 w-4 animate-spin mr-1" /> : <Save className="h-4 w-4 mr-1" />}
保存
{saving ? <Loader2 className="h-4 w-4 animate-spin mr-1" /> : <Save className="h-4 w-4 mr-1" />}保存
</Button>
</div>
</div>
@@ -16,6 +16,7 @@ import type { NotificationChannel } from './alert-center-helpers';
const CHANNEL_TYPES = [
{ value: 'dingtalk', label: '钉钉', hint: '钉钉机器人: webhook URL + secret' },
{ value: 'wechat', label: '企业微信', hint: '企业微信: webhook URL' },
{ value: 'feishu', label: '飞书', hint: '飞书机器人: {"url":"https://open.feishu.cn/open-apis/bot/v2/hook/..."}' },
{ value: 'email', label: '邮件', hint: '邮件: {"to":"ops@ezops.io"}' },
{ value: 'sms', label: '短信', hint: '短信: {"phones":"13800138000"}' },
{ value: 'webhook', label: 'Webhook', hint: 'Webhook: {"url":"https://..."}' },
@@ -116,12 +116,18 @@ export function getChannelIcon(type: string) {
case 'slack': return <MessageSquare className="w-4 h-4" />;
case 'sms': return <Phone className="w-4 h-4" />;
case 'webhook': return <Zap className="w-4 h-4" />;
case 'feishu': return <Bell className="w-4 h-4 text-blue-500" />;
case 'dingtalk': return <Bell className="w-4 h-4 text-sky-500" />;
case 'wechat': return <MessageSquare className="w-4 h-4 text-green-500" />;
default: return <Bell className="w-4 h-4" />;
}
}
/** 渠道类型中文标签 */
export function getChannelTypeLabel(type: string) {
const map: Record<string, string> = { dingtalk: '钉钉', wechat: '企业微信', email: '邮件', sms: '短信', webhook: 'Webhook' };
const map: Record<string, string> = {
dingtalk: '钉钉', wechat: '企业微信', feishu: '飞书',
email: '邮件', sms: '短信', webhook: 'Webhook',
};
return map[type] || type;
}
+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;
+6 -1
View File
@@ -175,6 +175,9 @@ export const kubernetesApi = {
getNodes: async (clusterId: number | string) => {
return http.get(`/kubernetes-clusters/${clusterId}/nodes`);
},
getClusterNodes: async (clusterCode: string) => {
return http.get(`/kubernetes/${clusterCode}/nodes`);
},
getNodeDetail: async (clusterCode: string, nodeName: string) => {
return http.get(`/kubernetes/${clusterCode}/nodes/${encodeURIComponent(nodeName)}`);
},
@@ -971,8 +974,10 @@ export const deployApi = {
getTools: () => http.get<ListResponse>('/deploy/tools'),
getTool: (id: number | string) => http.get(`/deploy/tools/${id}`),
updateTool: (id: number | string, data: any) => http.put(`/deploy/tools/${id}`, data),
installTool: (id: number | string) => http.post(`/deploy/tools/${id}/install`),
installTool: (id: number | string, version?: string) =>
http.post(`/deploy/tools/${id}/install`, version ? { version } : {}),
checkTool: (id: number | string) => http.post(`/deploy/tools/${id}/check`),
getToolVersions: (id: number | string) => http.get(`/deploy/tools/${id}/versions`),
};
// ==================== Ansible 自动化 API ====================