feat(i18n): 剩余模块全量国际化 — 51% 覆盖率 (231 文件接入 t())

批量转换 163 个文件,3204 处中文替换为 t() 调用:
- Monitor: 日志中心/告警中心/数据源/大屏/站点拨测/SNMP/中间件 全部转换
- Kubernetes: ResourceVisualEditor/NamespaceResourcePage/拓扑/事件 全部转换
- Deploy: 流水线/发布/凭证/RBAC 全部转换
- Server/Cloud/Agent/Task/Layout/UI: 全部转换
- 翻译词典扩展至 6474 行 (22 namespaces, 5000+ keys)
- tsc 编译零错误
This commit is contained in:
attacker committed 2026-07-03 01:51:57 +08:00
1 parent 78c27037e3
commit ecec73989b
166 files changed
+6925 -2800

No files matched your search

@@ -13,8 +13,10 @@ import { kubernetesApi } from '@/api';
import { PageShell } from '@/components/layout/PageShell';
import { ContentPanel } from '@/components/layout/ContentPanel';
import type { JsonData } from '@/types/common';
import { useTranslation } from 'react-i18next';
export default function CapacityPage() {
const { t } = useTranslation();
const { clusterCode } = useParams<{ clusterCode: string }>();
const navigate = useNavigate();
const [loading, setLoading] = useState(false);
@@ -76,8 +78,8 @@ export default function CapacityPage() {
return (
<PageShell
variant="list"
title="资源容量分析"
subtitle={clusterName ? `${clusterName} · Deployment 资源请求与限制` : 'Deployment 资源请求与限制'}
title=t('kubernetes.capacitypage.s4e67a9')
subtitle={clusterName ? t('kubernetes.capacitypage.sd54408', { clusterName: clusterName }) : t('kubernetes.capacitypage.s6a1128')}
icon={<BarChart3 className="h-5 w-5" />}
actions={(
<>
@@ -88,9 +90,9 @@ export default function CapacityPage() {
</SelectContent>
</Select>
<Select value={selectedNs} onValueChange={setSelectedNs}>
<SelectTrigger className="w-32 h-9 dg-input"><SelectValue placeholder="所有命名空间" /></SelectTrigger>
<SelectTrigger className="w-32 h-9 dg-input"><SelectValue placeholder=t('kubernetes.capacitypage.s58173b') /></SelectTrigger>
<SelectContent>
<SelectItem value="all">所有命名空间</SelectItem>
<SelectItem value="all">{t('kubernetes.capacitypage.s58173b')}</SelectItem>
{namespaces.map(n => <SelectItem key={n} value={n}>{n}</SelectItem>)}
</SelectContent>
</Select>
@@ -109,9 +111,9 @@ export default function CapacityPage() {
<Table>
<TableHeader><TableRow className="border-[var(--dg-border)] hover:bg-transparent">
<TableHead className="dg-text-secondary">Deployment</TableHead>
<TableHead className="dg-text-secondary">命名空间</TableHead>
<TableHead className="dg-text-secondary">副本</TableHead>
<TableHead className="dg-text-secondary">容器</TableHead>
<TableHead className="dg-text-secondary">{t('k8s.column.namespace')}</TableHead>
<TableHead className="dg-text-secondary">{t('kubernetes.capacitypage.s0428b3')}</TableHead>
<TableHead className="dg-text-secondary">{t('k8s.pods.containers')}</TableHead>
<TableHead className="dg-text-secondary"><Cpu className="h-3 w-3 inline mr-1" />CPU Req</TableHead>
<TableHead className="dg-text-secondary"><Cpu className="h-3 w-3 inline mr-1" />CPU Lim</TableHead>
<TableHead className="dg-text-secondary"><HardDrive className="h-3 w-3 inline mr-1" />Mem Req</TableHead>
@@ -26,10 +26,12 @@ import {
import { kubernetesApi } from '@/api';
import type { JsonData } from '@/types/common';
import { useTranslation } from 'react-i18next';
const CHART_COLORS = ['#3B82F6', '#207060', '#F59E0B', '#EF4444', '#8B5CF6', '#EC4899', '#14B8A6', '#F97316'];
export default function ClusterComparePage() {
const { t } = useTranslation();
const navigate = useNavigate();
const [loading, setLoading] = useState(false);
const [data, setData] = useState<JsonData>(null);
@@ -42,7 +44,7 @@ export default function ClusterComparePage() {
const res: JsonData = await kubernetesApi.getMultiClusterComparison();
setData(res || null);
} catch (e) {
setError(e?.message || '加载失败');
setError(e?.message || t('common.loadFailed'));
setData(null);
} finally {
setLoading(false);
@@ -66,16 +68,16 @@ export default function ClusterComparePage() {
const usageBarData = clusters.map((c: JsonData) => ({
name: c.code || c.name,
'CPU %': Number((c.cpu_usage || 0).toFixed(1)),
'内存 %': Number((c.memory_usage || 0).toFixed(1)),
t('kubernetes.clustercomparepage.sbe9d77'): Number((c.memory_usage || 0).toFixed(1)),
}));
const radarData = clusters.length > 0 ? [
{ metric: '节点数', ...Object.fromEntries(clusters.map((c: JsonData) => [c.code || c.name, c.node_count || 0])) },
{ metric: 'Pod数', ...Object.fromEntries(clusters.map((c: JsonData) => [c.code || c.name, Math.min(c.pod_count || 0, 100)])) },
{ metric: '部署数', ...Object.fromEntries(clusters.map((c: JsonData) => [c.code || c.name, c.deployment_count || 0])) },
{ metric: 'CPU使用', ...Object.fromEntries(clusters.map((c: JsonData) => [c.code || c.name, Number((c.cpu_usage || 0).toFixed(1))])) },
{ metric: '内存使用', ...Object.fromEntries(clusters.map((c: JsonData) => [c.code || c.name, Number((c.memory_usage || 0).toFixed(1))])) },
{ metric: 'CPU核数', ...Object.fromEntries(clusters.map((c: JsonData) => [c.code || c.name, c.total_cpu_cores || 0])) },
{ metric: t('kubernetes.cluster.nodeCount'), ...Object.fromEntries(clusters.map((c: JsonData) => [c.code || c.name, c.node_count || 0])) },
{ metric: t('kubernetes.clustercomparepage.s5fe4af'), ...Object.fromEntries(clusters.map((c: JsonData) => [c.code || c.name, Math.min(c.pod_count || 0, 100)])) },
{ metric: t('kubernetes.clustercomparepage.s7d207a'), ...Object.fromEntries(clusters.map((c: JsonData) => [c.code || c.name, c.deployment_count || 0])) },
{ metric: t('kubernetes.clustercomparepage.s020267'), ...Object.fromEntries(clusters.map((c: JsonData) => [c.code || c.name, Number((c.cpu_usage || 0).toFixed(1))])) },
{ metric: t('kubernetes.clustercomparepage.s5d9ce3'), ...Object.fromEntries(clusters.map((c: JsonData) => [c.code || c.name, Number((c.memory_usage || 0).toFixed(1))])) },
{ metric: t('kubernetes.clustercomparepage.sbdb608'), ...Object.fromEntries(clusters.map((c: JsonData) => [c.code || c.name, c.total_cpu_cores || 0])) },
] : [];
const nodeRolePie = clusters.flatMap((c: JsonData) => [
@@ -97,7 +99,7 @@ export default function ClusterComparePage() {
// 格式化同步时间
const fmtTime = (t: string | null | undefined) => {
if (!t) return '从未同步';
if (!t) return t('kubernetes.clustercomparepage.s910982');
try {
const d = new Date(t);
return d.toLocaleString('zh-CN', { hour12: false });
@@ -111,8 +113,8 @@ export default function ClusterComparePage() {
<div className="flex items-center gap-3">
<Layers className="h-5 w-5 dg-text-blue" />
<div>
<h1 className="text-lg font-semibold">多集群资源对比看板</h1>
<p className="text-xs dg-text-muted">跨集群资源用量、节点分布、健康状态对比</p>
<h1 className="text-lg font-semibold">{t('kubernetes.clustercomparepage.s5a25a6')}</h1>
<p className="text-xs dg-text-muted">{t('kubernetes.clustercomparepage.s9807a2')}</p>
</div>
</div>
<div className="flex items-center gap-2">
@@ -139,8 +141,8 @@ export default function ClusterComparePage() {
{/* 概览卡片 */}
<StatStrip
items={[
{ label: '集群', value: totals.cluster_count || 0, color: 'blue' },
{ label: '节点', value: totals.node_count || 0, color: 'emerald' },
{ label: t('kubernetes.clustercomparepage.s85fe50'), value: totals.cluster_count || 0, color: 'blue' },
{ label: t('k8s.tab.nodes'), value: totals.node_count || 0, color: 'emerald' },
{ label: 'Pod', value: totals.pod_count || 0, color: 'purple' },
{ label: 'Deploy', value: totals.deployment_count || 0, color: 'amber' },
{ label: 'Service', value: totals.service_count || 0, color: 'cyan' },
@@ -151,7 +153,7 @@ export default function ClusterComparePage() {
<Card className="bg-[var(--dg-bg-secondary)]/60 border-[var(--dg-border)]">
<CardContent className="py-12 text-center">
<Cloud className="h-12 w-12 dg-text-muted mx-auto mb-3" />
<p className="dg-text-muted">暂无集群数据,请先添加 Kubernetes 集群并同步</p>
<p className="dg-text-muted">{t('kubernetes.clustercomparepage.s4f921c')}</p>
<Link to="/kubernetes" className="inline-block mt-3">
<Button variant="outline" size="sm" className="border-[var(--dg-border)]">
去添加集群 <ChevronRight className="h-3.5 w-3.5 ml-1" />
@@ -169,7 +171,7 @@ export default function ClusterComparePage() {
<CardContent className="p-5">
<div className="flex items-center gap-2 mb-4">
<Layers className="h-4 w-4 dg-text-blue" />
<h3 className="text-sm font-semibold">资源数量对比</h3>
<h3 className="text-sm font-semibold">{t('kubernetes.clustercomparepage.se37201')}</h3>
</div>
<ResponsiveContainer width="100%" height={280}>
<BarChart data={resourceBarData} margin={{ top: 5, right: 10, left: -15, bottom: 5 }}>
@@ -178,7 +180,7 @@ export default function ClusterComparePage() {
<YAxis tick={{ fill: '#94a3b8', fontSize: 11 }} />
<Tooltip contentStyle={{ background: '#0f172a', border: '1px solid #334155', borderRadius: 8, fontSize: 12 }} />
<Legend wrapperStyle={{ fontSize: 11 }} />
<Bar dataKey="节点" fill={CHART_COLORS[1]} radius={[3, 3, 0, 0]} />
<Bar dataKey=t('k8s.tab.nodes') fill={CHART_COLORS[1]} radius={[3, 3, 0, 0]} />
<Bar dataKey="Pod" fill={CHART_COLORS[0]} radius={[3, 3, 0, 0]} />
<Bar dataKey="Deployment" fill={CHART_COLORS[2]} radius={[3, 3, 0, 0]} />
<Bar dataKey="Service" fill={CHART_COLORS[5]} radius={[3, 3, 0, 0]} />
@@ -191,7 +193,7 @@ export default function ClusterComparePage() {
<CardContent className="p-5">
<div className="flex items-center gap-2 mb-4">
<Activity className="h-4 w-4 dg-text-green" />
<h3 className="text-sm font-semibold">CPU / 内存使用率对比</h3>
<h3 className="text-sm font-semibold">{t('kubernetes.clustercomparepage.s8af9cf')}</h3>
</div>
<ResponsiveContainer width="100%" height={280}>
<BarChart data={usageBarData} margin={{ top: 5, right: 10, left: -15, bottom: 5 }}>
@@ -201,7 +203,7 @@ export default function ClusterComparePage() {
<Tooltip contentStyle={{ background: '#0f172a', border: '1px solid #334155', borderRadius: 8, fontSize: 12 }} />
<Legend wrapperStyle={{ fontSize: 11 }} />
<Bar dataKey="CPU %" fill={CHART_COLORS[0]} radius={[3, 3, 0, 0]} />
<Bar dataKey="内存 %" fill={CHART_COLORS[1]} radius={[3, 3, 0, 0]} />
<Bar dataKey=t('kubernetes.clustercomparepage.sbe9d77') fill={CHART_COLORS[1]} radius={[3, 3, 0, 0]} />
</BarChart>
</ResponsiveContainer>
</CardContent>
@@ -215,7 +217,7 @@ export default function ClusterComparePage() {
<CardContent className="p-5">
<div className="flex items-center gap-2 mb-4">
<TrendingUp className="h-4 w-4 dg-text-purple" />
<h3 className="text-sm font-semibold">资源雷达对比</h3>
<h3 className="text-sm font-semibold">{t('kubernetes.clustercomparepage.sc7d7a7')}</h3>
</div>
<ResponsiveContainer width="100%" height={320}>
<RadarChart data={radarData}>
@@ -242,7 +244,7 @@ export default function ClusterComparePage() {
<CardContent className="p-5">
<div className="flex items-center gap-2 mb-4">
<Server className="h-4 w-4 dg-text-yellow" />
<h3 className="text-sm font-semibold">节点角色分布</h3>
<h3 className="text-sm font-semibold">{t('kubernetes.clustercomparepage.sefdd7a')}</h3>
</div>
{nodeRolePie.length > 0 ? (
<ResponsiveContainer width="100%" height={320}>
@@ -260,7 +262,7 @@ export default function ClusterComparePage() {
</PieChart>
</ResponsiveContainer>
) : (
<div className="h-[320px] flex items-center justify-center dg-text-muted text-sm">无节点角色数据</div>
<div className="h-[320px] flex items-center justify-center dg-text-muted text-sm">{t('kubernetes.clustercomparepage.s394f38')}</div>
)}
</CardContent>
</Card>
@@ -272,25 +274,25 @@ export default function ClusterComparePage() {
<CardContent className="p-5">
<div className="flex items-center gap-2 mb-4">
<HardDrive className="h-4 w-4 dg-text-cyan" />
<h3 className="text-sm font-semibold">详细对比</h3>
<span className="text-xs dg-text-muted ml-2">点击行可进入集群概览</span>
<h3 className="text-sm font-semibold">{t('kubernetes.clustercomparepage.s3e920c')}</h3>
<span className="text-xs dg-text-muted ml-2">{t('kubernetes.clustercomparepage.sbcb4f0')}</span>
</div>
<div className="overflow-x-auto">
<Table>
<TableHeader>
<TableRow className="border-[var(--dg-border)] hover:bg-transparent">
<TableHead className="dg-text-secondary">集群</TableHead>
<TableHead className="dg-text-secondary">状态</TableHead>
<TableHead className="dg-text-secondary text-right">节点</TableHead>
<TableHead className="dg-text-secondary">{t('kubernetes.clustercomparepage.s85fe50')}</TableHead>
<TableHead className="dg-text-secondary">{t('common.status')}</TableHead>
<TableHead className="dg-text-secondary text-right">{t('k8s.tab.nodes')}</TableHead>
<TableHead className="dg-text-secondary text-right">Pod</TableHead>
<TableHead className="dg-text-secondary text-right">Deployment</TableHead>
<TableHead className="dg-text-secondary text-right">Service</TableHead>
<TableHead className="dg-text-secondary text-right">CPU 核数</TableHead>
<TableHead className="dg-text-secondary text-right">内存</TableHead>
<TableHead className="dg-text-secondary text-right">CPU 使用率</TableHead>
<TableHead className="dg-text-secondary text-right">内存使用率</TableHead>
<TableHead className="dg-text-secondary">角色</TableHead>
<TableHead className="dg-text-secondary">同步时间</TableHead>
<TableHead className="dg-text-secondary text-right">{t('kubernetes.clustercomparepage.s2e32ab')}</TableHead>
<TableHead className="dg-text-secondary text-right">{t('k8s.pods.memory')}</TableHead>
<TableHead className="dg-text-secondary text-right">{t('monitor.hostCpu')}</TableHead>
<TableHead className="dg-text-secondary text-right">{t('monitor.hostMemory')}</TableHead>
<TableHead className="dg-text-secondary">{t('pipeline.role')}</TableHead>
<TableHead className="dg-text-secondary">{t('cloud.syncTime')}</TableHead>
</TableRow>
</TableHeader>
<TableBody>
@@ -305,7 +307,7 @@ export default function ClusterComparePage() {
</TableCell>
<TableCell>
<Badge variant="outline" className={`text-xs ${statusColorMap[c.status] || statusColorMap.error}`}>
{c.status === 'healthy' ? '✓ 健康' : c.status === 'warning' ? '⚠ 警告' : '✗ 异常'}
{c.status === 'healthy' ? t('kubernetes.clustercomparepage.s33108c') : c.status === 'warning' ? t('kubernetes.clustercomparepage.s5ddbdd') : t('kubernetes.clustercomparepage.sc94103')}
</Badge>
</TableCell>
<TableCell className="text-right font-mono text-[var(--dg-text-secondary)]">{c.node_count}</TableCell>
@@ -25,6 +25,7 @@ import { PageShell } from '@/components/layout/PageShell';
import { ContentPanel } from '@/components/layout/ContentPanel';
import { StatStrip } from '@/components/ui/stat-strip';
import type { JsonData } from '@/types/common';
import { useTranslation } from 'react-i18next';
const NAMESPACE_ICON: Record<string, React.ComponentType<Record<string, unknown>>> = {
'kube-system': Server,
@@ -34,6 +35,7 @@ const NAMESPACE_ICON: Record<string, React.ComponentType<Record<string, unknown>
};
export default function ClusterOverviewPage() {
const { t } = useTranslation();
const { clusterCode } = useParams<{ clusterCode: string }>();
const navigate = useNavigate();
const { toast } = useToast();
@@ -53,7 +55,7 @@ export default function ClusterOverviewPage() {
const current = list.find((c: JsonData) => (c.code || String(c.id)) === clusterCode);
setClusterInfo(current || null);
if (!current && list.length > 0 && clusterCode) {
toast({ title: '集群未找到', description: `找不到集群 ${clusterCode}`, variant: 'destructive' });
toast({ title: t('kubernetes.clusteroverviewpage.s9ff765'), description: t('kubernetes.clusteroverviewpage.s59f69c', { clusterCode: clusterCode }), variant: 'destructive' });
}
} catch { setClusters([]); }
}, [clusterCode]);
@@ -83,15 +85,15 @@ export default function ClusterOverviewPage() {
return (
<PageShell
variant="default"
title={clusterCode || '集群概览'}
subtitle={clusterInfo?.version ? `集群概览 · Kubernetes ${clusterInfo.version}` : '集群概览'}
title={clusterCode || t('kubernetes.clusteroverviewpage.s066c0a')}
subtitle={clusterInfo?.version ? t('kubernetes.clusteroverviewpage.s966b2d', { clusterInfo.version: clusterInfo.version }) : t('kubernetes.clusteroverviewpage.s066c0a')}
icon={<Server className="h-5 w-5" />}
metrics={!loading ? (
<StatStrip
items={[
{ label: '节点', value: nodes.length, color: 'blue' },
{ label: '命名空间', value: namespaces.length, color: 'green' },
{ label: '版本', value: clusterInfo?.version || '-', color: 'muted' },
{ label: t('k8s.tab.nodes'), value: nodes.length, color: 'blue' },
{ label: t('k8s.column.namespace'), value: namespaces.length, color: 'green' },
{ label: t('common.version'), value: clusterInfo?.version || '-', color: 'muted' },
]}
/>
) : undefined}
@@ -111,21 +113,21 @@ export default function ClusterOverviewPage() {
<Table>
<TableHeader>
<TableRow className="border-[var(--dg-border)] hover:bg-transparent">
<TableHead className="text-[var(--dg-text-secondary)]">名称</TableHead>
<TableHead className="text-[var(--dg-text-secondary)]">角色</TableHead>
<TableHead className="text-[var(--dg-text-secondary)]">状态</TableHead>
<TableHead className="text-[var(--dg-text-secondary)]">{t('common.name')}</TableHead>
<TableHead className="text-[var(--dg-text-secondary)]">{t('pipeline.role')}</TableHead>
<TableHead className="text-[var(--dg-text-secondary)]">{t('common.status')}</TableHead>
<TableHead className="text-[var(--dg-text-secondary)]">IP</TableHead>
<TableHead className="text-[var(--dg-text-secondary)]">OS</TableHead>
<TableHead className="text-[var(--dg-text-secondary)]">Kubelet</TableHead>
<TableHead className="text-[var(--dg-text-secondary)]">CPU</TableHead>
<TableHead className="text-[var(--dg-text-secondary)]">内存</TableHead>
<TableHead className="text-[var(--dg-text-secondary)]">{t('k8s.pods.memory')}</TableHead>
</TableRow>
</TableHeader>
<TableBody>
{loading ? (
<TableRow><TableCell colSpan={8} className="text-center text-[var(--dg-text-muted)] py-12"><Loader2 className="h-5 w-5 animate-spin mx-auto mb-2" />加载中...</TableCell></TableRow>
<TableRow><TableCell colSpan={8} className="text-center text-[var(--dg-text-muted)] py-12"><Loader2 className="h-5 w-5 animate-spin mx-auto mb-2" />{t('common.loading')}</TableCell></TableRow>
) : nodes.length === 0 ? (
<TableRow><TableCell colSpan={8} className="text-center text-[var(--dg-text-muted)] py-12"><Cpu className="h-8 w-8 mx-auto mb-2 opacity-50" />暂无节点</TableCell></TableRow>
<TableRow><TableCell colSpan={8} className="text-center text-[var(--dg-text-muted)] py-12"><Cpu className="h-8 w-8 mx-auto mb-2 opacity-50" />{t('k8s.topology.noNodes')}</TableCell></TableRow>
) : (
nodes.map((n: JsonData) => {
const cpuCores = n.cpu || 0;
@@ -16,8 +16,10 @@ import { DeploymentHpaTab } from './deployment-detail/DeploymentHpaTab';
import { DeploymentPodModals } from './deployment-detail/DeploymentPodModals';
import { YamlViewer } from './YamlViewer';
import type { JsonData } from '@/types/common';
import { useTranslation } from 'react-i18next';
export function DeploymentDetail({ clusterCode, namespace, deploymentName, onBack }: DeploymentDetailProps) {
const { t } = useTranslation();
const { toast } = useToast();
const confirm = useConfirm();
const [deployment, setDeployment] = useState<JsonData>(null);
@@ -60,7 +62,7 @@ export function DeploymentDetail({ clusterCode, namespace, deploymentName, onBac
setPods(allPods.filter((p: JsonData) => p.namespace === namespace && p.name.startsWith(deploymentName)));
setHpas(allHpas.filter((h: JsonData) => h.target_name === deploymentName && h.namespace === namespace));
} catch (e) {
console.error('加载详情失败:', e);
console.error(t('kubernetes.deploymentdetail.sb46ea9'), e);
} finally {
setLoading(false);
}
@@ -74,10 +76,10 @@ export function DeploymentDetail({ clusterCode, namespace, deploymentName, onBac
setActionLoading('scale');
try {
await kubernetesApi.scaleDeployment(clusterCode, namespace, deploymentName, newReplicas);
toast({ title: '扩缩容成功', description: `副本数已设置为 ${newReplicas}` });
toast({ title: t('kubernetes.deploymentdetail.s0b3ea1'), description: t('kubernetes.deploymentdetail.sacbcbd', { newReplicas: newReplicas }) });
loadData();
} catch (e) {
toast({ title: '操作失败', description: e?.message || String(e), variant: 'destructive' });
toast({ title: t('common.operationFailed'), description: e?.message || String(e), variant: 'destructive' });
} finally { setActionLoading(''); }
};
@@ -85,9 +87,9 @@ export function DeploymentDetail({ clusterCode, namespace, deploymentName, onBac
setActionLoading('restart');
try {
await kubernetesApi.restartDeployment(clusterCode, namespace, deploymentName);
toast({ title: '重启指令已下发', description: 'Deployment 正在滚动重启' });
toast({ title: t('kubernetes.deploymentdetail.s68a700'), description: t('kubernetes.deploymentdetail.sd18761') });
} catch (e) {
toast({ title: '重启失败', description: e?.message || String(e), variant: 'destructive' });
toast({ title: t('kubernetes.deployment.restartFailed'), description: e?.message || String(e), variant: 'destructive' });
} finally { setActionLoading(''); }
};
@@ -96,28 +98,28 @@ export function DeploymentDetail({ clusterCode, namespace, deploymentName, onBac
setActionLoading('image');
try {
await kubernetesApi.updateDeploymentImage(clusterCode, namespace, deploymentName, newImage);
toast({ title: '镜像更新成功', description: `正在滚动更新为 ${newImage}` });
toast({ title: t('kubernetes.deploymentdetail.s6df3c3'), description: t('kubernetes.deploymentdetail.sa982c3', { newImage: newImage }) });
setShowImageUpdate(false);
loadData();
} catch (e) {
toast({ title: '更新失败', description: e?.message || String(e), variant: 'destructive' });
toast({ title: t('alert.updateFailed'), description: e?.message || String(e), variant: 'destructive' });
} finally { setActionLoading(''); }
};
const handleHpaToggle = async (hpa: JsonData) => {
const ok = await confirm({
title: '删除 HPA',
description: `确定删除 HPA "${hpa.name}"?`,
confirmText: '删除',
title: t('kubernetes.hpa.deleteHpa'),
description: t('kubernetes.deploymentdetail.s209f7e', { hpa.name: hpa.name }),
confirmText: t('common.delete'),
variant: 'destructive',
});
if (!ok) return;
try {
await kubernetesApi.deleteHPA(clusterCode, namespace, hpa.name);
toast({ title: 'HPA 已删除' });
toast({ title: t('kubernetes.deploymentdetail.s0f958f') });
loadData();
} catch (e) {
toast({ title: '删除失败', description: e?.message || String(e), variant: 'destructive' });
toast({ title: t('common.deleteFailed'), description: e?.message || String(e), variant: 'destructive' });
}
};
@@ -126,7 +128,7 @@ export function DeploymentDetail({ clusterCode, namespace, deploymentName, onBac
<Card className="dg-card">
<CardContent className="p-12 text-center">
<Loader2 className="h-6 w-6 animate-spin mx-auto dg-text-muted" />
<p className="dg-text-muted mt-3">加载中...</p>
<p className="dg-text-muted mt-3">{t('common.loading')}</p>
</CardContent>
</Card>
);
@@ -138,7 +140,7 @@ export function DeploymentDetail({ clusterCode, namespace, deploymentName, onBac
<CardContent className="p-12 text-center">
<XCircle className="h-8 w-8 mx-auto dg-text-red" />
<p className="dg-text-secondary mt-3">未找到 Deployment: {deploymentName}</p>
<Button variant="outline" className="mt-4" onClick={onBack}>返回</Button>
<Button variant="outline" className="mt-4" onClick={onBack}>{t('common.back')}</Button>
</CardContent>
</Card>
);
@@ -15,6 +15,7 @@ import { saveDeploymentManifest } from './deployment-manifest-save';
import { SchedulingSection, type ScheduleMode } from './deployment-edit-advanced/SchedulingSection';
import { DnsHostSection } from './deployment-edit-advanced/DnsHostSection';
import type { JsonData } from '@/types/common';
import { useTranslation } from 'react-i18next';
interface Props {
clusterCode: string;
@@ -34,6 +35,7 @@ interface Toleration {
}
export function DeploymentEditAdvanced({ clusterCode, namespace, deploymentName, manifest, onSaved, onCancel }: Props) {
const { t } = useTranslation();
const { toast } = useToast();
const [saving, setSaving] = useState(false);
const [loading, setLoading] = useState(!manifest);
@@ -311,10 +313,10 @@ export function DeploymentEditAdvanced({ clusterCode, namespace, deploymentName,
else delete podSpec.dnsConfig;
await saveDeploymentManifest(clusterCode, namespace, deploymentName, base);
toast({ title: '高级设置已保存', description: `${deploymentName} 更新已提交` });
toast({ title: t('kubernetes.deploymenteditadvanced.s9762d0'), description: t('kubernetes.deploymenteditadvanced.s1952a7', { deploymentName: deploymentName }) });
onSaved(base);
} catch (e) {
toast({ title: '保存失败', description: e?.message || String(e), variant: 'destructive' });
toast({ title: t('common.saveFailed'), description: e?.message || String(e), variant: 'destructive' });
} finally { setSaving(false); }
};
@@ -323,7 +325,7 @@ export function DeploymentEditAdvanced({ clusterCode, namespace, deploymentName,
<Card className="dg-card">
<CardContent className="p-12 text-center">
<Loader2 className="h-6 w-6 animate-spin mx-auto dg-text-muted" />
<p className="dg-text-muted mt-3 text-sm">加载中...</p>
<p className="dg-text-muted mt-3 text-sm">{t('common.loading')}</p>
</CardContent>
</Card>
);
@@ -364,12 +366,12 @@ export function DeploymentEditAdvanced({ clusterCode, namespace, deploymentName,
{strategyType === 'RollingUpdate' && (
<div className="grid grid-cols-2 gap-3">
<div>
<Label className="dg-text-muted text-xs">maxSurge(整数或百分比,超出期望副本数)</Label>
<Label className="dg-text-muted text-xs">{t('kubernetes.deploymenteditadvanced.s282929')}</Label>
<Input value={maxSurge} onChange={e => setMaxSurge(e.target.value)}
placeholder="25%" className="h-8 mt-1 dg-input text-sm font-mono" />
</div>
<div>
<Label className="dg-text-muted text-xs">maxUnavailable(整数或百分比,不可用上限)</Label>
<Label className="dg-text-muted text-xs">{t('kubernetes.deploymenteditadvanced.s7754b7')}</Label>
<Input value={maxUnavailable} onChange={e => setMaxUnavailable(e.target.value)}
placeholder="25%" className="h-8 mt-1 dg-input text-sm font-mono" />
</div>
@@ -387,12 +389,12 @@ export function DeploymentEditAdvanced({ clusterCode, namespace, deploymentName,
</CardHeader>
<CardContent className="pt-0 grid grid-cols-2 gap-3">
<div>
<Label className="dg-text-muted text-xs">revisionHistoryLimit(保留 RS 历史)</Label>
<Label className="dg-text-muted text-xs">{t('kubernetes.deploymenteditadvanced.s0d8e53')}</Label>
<Input type="number" value={revisionHistoryLimit} onChange={e => setRevisionHistoryLimit(e.target.value)}
className="h-8 mt-1 dg-input text-sm font-mono" />
</div>
<div>
<Label className="dg-text-muted text-xs">progressDeadlineSeconds(升级超时秒数)</Label>
<Label className="dg-text-muted text-xs">{t('kubernetes.deploymenteditadvanced.scd3a9b')}</Label>
<Input type="number" value={progressDeadlineSeconds} onChange={e => setProgressDeadlineSeconds(e.target.value)}
className="h-8 mt-1 dg-input text-sm font-mono" />
</div>
@@ -403,7 +405,7 @@ export function DeploymentEditAdvanced({ clusterCode, namespace, deploymentName,
<Card className="dg-card">
<CardHeader className="pb-3">
<div className="flex items-center justify-between">
<CardTitle className="text-sm text-[var(--dg-text-primary)]">容忍 (Tolerations)</CardTitle>
<CardTitle className="text-sm text-[var(--dg-text-primary)]">{t('kubernetes.deploymenteditadvanced.s13a831')}</CardTitle>
<Button size="sm" variant="outline" className="h-7 border-[var(--dg-border)] text-[var(--dg-text-secondary)] text-xs"
onClick={() => setTolerations(prev => [...prev, { key: '', operator: 'Equal', value: '', effect: 'NoSchedule', tolerationSeconds: '' }])}>
<Plus className="h-3 w-3 mr-1" />添加
@@ -411,7 +413,7 @@ export function DeploymentEditAdvanced({ clusterCode, namespace, deploymentName,
</div>
</CardHeader>
<CardContent className="pt-0 space-y-2">
{tolerations.length === 0 && <p className="text-xs dg-text-muted">未配置容忍</p>}
{tolerations.length === 0 && <p className="text-xs dg-text-muted">{t('kubernetes.deploymenteditadvanced.s8bc06b')}</p>}
{tolerations.map((t, i) => (
<div key={i} className="grid grid-cols-[1fr_80px_1fr_100px_80px_auto] gap-2 items-center">
<Input value={t.key} placeholder="key" onChange={e => setTolerations(prev => prev.map((x, idx) => idx === i ? { ...x, key: e.target.value } : x))}
@@ -426,12 +428,12 @@ export function DeploymentEditAdvanced({ clusterCode, namespace, deploymentName,
className="h-7 dg-input text-xs font-mono" />
<select value={t.effect} onChange={e => setTolerations(prev => prev.map((x, idx) => idx === i ? { ...x, effect: e.target.value } : x))}
className="h-7 bg-[var(--dg-bg-tertiary)] border border-[var(--dg-border)] rounded text-xs text-[var(--dg-text-secondary)] px-1">
<option value="">任意</option>
<option value="">{t('kubernetes.deploymenteditadvanced.s2a6eb2')}</option>
<option value="NoSchedule">NoSchedule</option>
<option value="PreferNoSchedule">PreferNoSchedule</option>
<option value="NoExecute">NoExecute</option>
</select>
<Input value={t.tolerationSeconds} placeholder="秒" disabled={t.effect !== 'NoExecute'}
<Input value={t.tolerationSeconds} placeholder=t('common.second') disabled={t.effect !== 'NoExecute'}
onChange={e => setTolerations(prev => prev.map((x, idx) => idx === i ? { ...x, tolerationSeconds: e.target.value } : x))}
className="h-7 dg-input text-xs font-mono" />
<Button variant="ghost" size="icon" className="h-7 w-7 dg-text-red" onClick={() => setTolerations(prev => prev.filter((_, idx) => idx !== i))}>
@@ -578,7 +580,7 @@ export function DeploymentEditAdvanced({ clusterCode, namespace, deploymentName,
{/* 操作栏 */}
<div className="flex justify-end gap-2 pt-2">
<Button variant="outline" className="border-[var(--dg-border)] dg-text-secondary" onClick={onCancel}>取消</Button>
<Button variant="outline" className="border-[var(--dg-border)] dg-text-secondary" onClick={onCancel}>{t('common.cancel')}</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" />}
保存
@@ -10,6 +10,7 @@ import { Badge } from '@/components/ui/badge';
import { Plus, Trash2, Save, Loader2, Tags, FileText, Hash, Lock } from 'lucide-react';
import { useToast } from '@/hooks/use-toast';
import { saveDeploymentManifest } from './deployment-manifest-save';
import { useTranslation } from 'react-i18next';
interface DeploymentEditBasicProps {
clusterCode: string;
@@ -38,6 +39,7 @@ function kvToObj(arr: Array<{ key: string; value: string }>): Record<string, str
}
export function DeploymentEditBasic({ clusterCode, namespace, deploymentName, manifest, onSaved, onCancel, isCreate = false }: DeploymentEditBasicProps) {
const { t } = useTranslation();
const { toast } = useToast();
const [saving, setSaving] = useState(false);
const [loading, setLoading] = useState(!manifest);
@@ -93,7 +95,7 @@ export function DeploymentEditBasic({ clusterCode, namespace, deploymentName, ma
const merged = { ...kvToObj(prev), ...sel };
return Object.entries(merged).map(([key, value]) => ({ key, value }));
});
toast({ title: '已同步', description: 'Selector 标签已合并到 Pod 模板标签' });
toast({ title: t('kubernetes.deploymenteditbasic.s8bf97a'), description: t('kubernetes.deploymenteditbasic.s841d0d') });
};
const save = async () => {
@@ -106,7 +108,7 @@ export function DeploymentEditBasic({ clusterCode, namespace, deploymentName, ma
base.metadata = base.metadata || {};
if (isCreate) {
const trimmed = resName.trim();
if (!trimmed) throw new Error('名称不能为空');
if (!trimmed) throw new Error(t('kubernetes.deploymenteditbasic.sdf09ff'));
base.metadata.name = trimmed;
base.metadata.namespace = namespace;
}
@@ -127,10 +129,10 @@ export function DeploymentEditBasic({ clusterCode, namespace, deploymentName, ma
delete base.spec.template.metadata.labels;
}
const savedName = await saveDeploymentManifest(clusterCode, namespace, deploymentName, base);
toast({ title: isCreate ? '创建成功' : '基本信息已保存', description: isCreate ? `${savedName} 已创建` : `${savedName} 更新已提交` });
toast({ title: isCreate ? t('monitor.dashboard.custom.toastCreateSuccess') : t('kubernetes.deploymenteditbasic.sa59c4d'), description: isCreate ? t('kubernetes.deploymenteditbasic.s220fce', { savedName: savedName }) : t('kubernetes.deploymenteditbasic.s253b77', { savedName: savedName }) });
onSaved(base);
} catch (e) {
toast({ title: '保存失败', description: e?.message || String(e), variant: 'destructive' });
toast({ title: t('common.saveFailed'), description: e?.message || String(e), variant: 'destructive' });
} finally { setSaving(false); }
};
@@ -139,7 +141,7 @@ export function DeploymentEditBasic({ clusterCode, namespace, deploymentName, ma
<Card className="dg-card">
<CardContent className="p-12 text-center">
<Loader2 className="h-6 w-6 animate-spin mx-auto dg-text-muted" />
<p className="dg-text-muted mt-3 text-sm">加载中...</p>
<p className="dg-text-muted mt-3 text-sm">{t('common.loading')}</p>
</CardContent>
</Card>
);
@@ -174,7 +176,7 @@ export function DeploymentEditBasic({ clusterCode, namespace, deploymentName, ma
onChange={e => setReplicas(Math.max(0, Number(e.target.value) || 0))}
className="w-32 dg-input"
/>
<span className="text-xs dg-text-muted">期望运行的 Pod 实例数量</span>
<span className="text-xs dg-text-muted">{t('kubernetes.deploymenteditbasic.s6e47fc')}</span>
</div>
</CardContent>
</Card>
@@ -184,12 +186,12 @@ export function DeploymentEditBasic({ clusterCode, namespace, deploymentName, ma
<CardHeader className="pb-3">
<CardTitle className="text-sm text-[var(--dg-text-primary)] flex items-center gap-2">
<Lock className="h-4 w-4 dg-text-muted" />
{isCreate ? '基本标识' : '基本标识(只读)'}
{isCreate ? t('kubernetes.deploymenteditbasic.sc8de32') : t('kubernetes.deploymenteditbasic.sc4d9eb')}
</CardTitle>
</CardHeader>
<CardContent className="pt-0 grid grid-cols-2 gap-4">
<div>
<Label className="dg-text-secondary text-xs">名称 (name)</Label>
<Label className="dg-text-secondary text-xs">{t('kubernetes.deploymenteditbasic.sab7247')}</Label>
<Input
value={isCreate ? resName : deploymentName}
readOnly={!isCreate}
@@ -198,7 +200,7 @@ export function DeploymentEditBasic({ clusterCode, namespace, deploymentName, ma
/>
</div>
<div>
<Label className="dg-text-secondary text-xs">命名空间 (namespace)</Label>
<Label className="dg-text-secondary text-xs">{t('kubernetes.deploymenteditbasic.s00e648')}</Label>
<Input value={namespace} readOnly
className="mt-1 bg-[var(--dg-bg-primary)] border-[var(--dg-border)] dg-text-muted font-mono text-sm cursor-not-allowed" />
</div>
@@ -220,7 +222,7 @@ export function DeploymentEditBasic({ clusterCode, namespace, deploymentName, ma
</div>
</CardHeader>
<CardContent className="pt-0 space-y-1.5">
{labels.length === 0 && <p className="text-[11px] dg-text-muted">无标签</p>}
{labels.length === 0 && <p className="text-[11px] dg-text-muted">{t('kubernetes.deploymenteditbasic.s3f9afc')}</p>}
{labels.map((l, i) => (
<div key={i} className="grid grid-cols-[1fr_1.4fr_auto] gap-2">
<Input value={l.key} placeholder="app"
@@ -243,7 +245,7 @@ export function DeploymentEditBasic({ clusterCode, namespace, deploymentName, ma
<CardTitle className="text-sm text-[var(--dg-text-primary)] flex items-center gap-2">
<Tags className="h-4 w-4 dg-text-yellow" />
选择器 (Selector)
<Badge variant="outline" className="border-amber-700/50 text-amber-500 text-[10px]">⚠️ 需与模板标签一致</Badge>
<Badge variant="outline" className="border-amber-700/50 text-amber-500 text-[10px]">{t('kubernetes.deploymenteditbasic.s36e4c3')}</Badge>
</CardTitle>
<Button size="sm" variant="outline" className="h-7 border-[var(--dg-border)] text-[var(--dg-text-secondary)] text-xs" onClick={addSelector}>
<Plus className="h-3 w-3 mr-1" />新增
@@ -251,8 +253,8 @@ export function DeploymentEditBasic({ clusterCode, namespace, deploymentName, ma
</div>
</CardHeader>
<CardContent className="pt-0 space-y-1.5">
<p className="text-[11px] text-amber-500/70 mb-1">Selector 决定哪些 Pod 归属此 Deployment。修改时必须确保与 Pod Template Labels 匹配,否则 Deployment 将无法管理 Pod。</p>
{selectorLabels.length === 0 && <p className="text-[11px] dg-text-muted">无选择器</p>}
<p className="text-[11px] text-amber-500/70 mb-1">{t('kubernetes.deploymenteditbasic.sc29c88')}</p>
{selectorLabels.length === 0 && <p className="text-[11px] dg-text-muted">{t('kubernetes.service.noSelector')}</p>}
{selectorLabels.map((s, i) => (
<div key={i} className="grid grid-cols-[1fr_1.4fr_auto] gap-2">
<Input value={s.key} placeholder="app"
@@ -287,8 +289,8 @@ export function DeploymentEditBasic({ clusterCode, namespace, deploymentName, ma
</div>
</CardHeader>
<CardContent className="pt-0 space-y-1.5">
<p className="text-[11px] dg-text-muted mb-1">Pod 模板标签必须包含 Selector 全部键值,否则 Deployment 无法管理 Pod</p>
{templateLabels.length === 0 && <p className="text-[11px] dg-text-muted">无模板标签</p>}
<p className="text-[11px] dg-text-muted mb-1">{t('kubernetes.deploymenteditbasic.s9faa25')}</p>
{templateLabels.length === 0 && <p className="text-[11px] dg-text-muted">{t('kubernetes.deploymenteditbasic.se9c9f6')}</p>}
{templateLabels.map((l, i) => (
<div key={i} className="grid grid-cols-[1fr_1.4fr_auto] gap-2">
<Input value={l.key} placeholder="app"
@@ -319,7 +321,7 @@ export function DeploymentEditBasic({ clusterCode, namespace, deploymentName, ma
</div>
</CardHeader>
<CardContent className="pt-0 space-y-1.5">
{annotations.length === 0 && <p className="text-[11px] dg-text-muted">无注解</p>}
{annotations.length === 0 && <p className="text-[11px] dg-text-muted">{t('kubernetes.deploymenteditbasic.sbe1e7c')}</p>}
{annotations.map((a, i) => (
<div key={i} className="grid grid-cols-[1fr_1.4fr_auto] gap-2">
<Input value={a.key} placeholder="deployment.kubernetes.io/revision"
@@ -341,7 +343,7 @@ export function DeploymentEditBasic({ clusterCode, namespace, deploymentName, ma
保存将通过 <code className="dg-text-secondary">PUT application/yaml</code> 提交(自动剥离 status/managedFields 等只读字段)
</p>
<div className="flex gap-2">
<Button variant="outline" className="border-[var(--dg-border)] dg-text-secondary" onClick={onCancel}>取消</Button>
<Button variant="outline" className="border-[var(--dg-border)] dg-text-secondary" onClick={onCancel}>{t('common.cancel')}</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" />}
保存
@@ -26,8 +26,10 @@ import {
} from './deployment-edit/container-utils';
import type { ContainerForm, DeploymentEditContainersProps } from './deployment-edit/types';
import type { JsonData } from '@/types/common';
import { useTranslation } from 'react-i18next';
export function DeploymentEditContainers({ clusterCode, namespace, deploymentName, manifest, onSaved, onCancel }: DeploymentEditContainersProps) {
const { t } = useTranslation();
const { toast } = useToast();
const [saving, setSaving] = useState(false);
const [loading, setLoading] = useState(!manifest);
@@ -81,11 +83,11 @@ export function DeploymentEditContainers({ clusterCode, namespace, deploymentNam
// validate
for (const c of [...initContainers, ...containers]) {
if (!c.name.trim()) {
toast({ title: '保存失败', description: '容器名称不能为空', variant: 'destructive' });
toast({ title: t('common.saveFailed'), description: t('kubernetes.deploymenteditcontainers.s14b12c'), variant: 'destructive' });
return;
}
if (!c.image.trim()) {
toast({ title: '保存失败', description: `容器 ${c.name} 的镜像不能为空`, variant: 'destructive' });
toast({ title: t('common.saveFailed'), description: t('kubernetes.deploymenteditcontainers.sb01a6a', { c.name: c.name }), variant: 'destructive' });
return;
}
}
@@ -101,10 +103,10 @@ export function DeploymentEditContainers({ clusterCode, namespace, deploymentNam
? imagePullSecrets.filter(s => s.trim()).map((s: string) => ({ name: s }))
: undefined;
await saveDeploymentManifest(clusterCode, namespace, deploymentName, base);
toast({ title: '容器配置已保存', description: `${deploymentName} 更新已提交` });
toast({ title: t('kubernetes.deploymenteditcontainers.sdf22b9'), description: t('kubernetes.deploymenteditcontainers.s1952a7', { deploymentName: deploymentName }) });
onSaved(base);
} catch (e) {
toast({ title: '保存失败', description: e?.message || String(e), variant: 'destructive' });
toast({ title: t('common.saveFailed'), description: e?.message || String(e), variant: 'destructive' });
} finally { setSaving(false); }
};
@@ -113,7 +115,7 @@ export function DeploymentEditContainers({ clusterCode, namespace, deploymentNam
<Card className="dg-card">
<CardContent className="p-12 text-center">
<Loader2 className="h-6 w-6 animate-spin mx-auto dg-text-muted" />
<p className="dg-text-muted mt-3 text-sm">加载中...</p>
<p className="dg-text-muted mt-3 text-sm">{t('common.loading')}</p>
</CardContent>
</Card>
);
@@ -136,7 +138,7 @@ export function DeploymentEditContainers({ clusterCode, namespace, deploymentNam
<CardTitle className="text-sm text-[var(--dg-text-primary)] flex items-center gap-2">
<KeyRound className="h-4 w-4 dg-text-yellow" />
镜像拉取凭证 (imagePullSecrets)
<Badge variant="outline" className="border-[var(--dg-border)] dg-text-muted text-[10px]">Pod 级别</Badge>
<Badge variant="outline" className="border-[var(--dg-border)] dg-text-muted text-[10px]">{t('kubernetes.deploymenteditcontainers.s2f29fb')}</Badge>
</CardTitle>
</CardHeader>
<CardContent className="pt-0 space-y-2">
@@ -148,10 +150,10 @@ export function DeploymentEditContainers({ clusterCode, namespace, deploymentNam
className="dg-text-red hover:dg-text-red ml-1"><Trash2 className="h-3 w-3" /></button>
</div>
))}
{imagePullSecrets.length === 0 && <span className="text-[11px] dg-text-muted">无</span>}
{imagePullSecrets.length === 0 && <span className="text-[11px] dg-text-muted">{t('common.none')}</span>}
</div>
<div className="flex gap-2">
<Input placeholder="输入 Secret 名称后回车" className="dg-input text-xs h-8"
<Input placeholder=t('kubernetes.deploymenteditcontainers.s960f6a') className="dg-input text-xs h-8"
onKeyDown={(e) => {
if (e.key === 'Enter') {
const val = (e.target as HTMLInputElement).value.trim();
@@ -168,8 +170,8 @@ export function DeploymentEditContainers({ clusterCode, namespace, deploymentNam
{/* 初始化容器 */}
<ContainerGroupSection
title="初始化容器"
description="在主容器启动前按顺序执行的容器,用于初始化环境"
title=t('kubernetes.pod.initContainer')
description=t('kubernetes.deploymenteditcontainers.s883e09')
icon={<Play className="h-4 w-4 dg-text-purple" />}
containers={initContainers}
accentColor="purple"
@@ -180,8 +182,8 @@ export function DeploymentEditContainers({ clusterCode, namespace, deploymentNam
{/* 工作容器 */}
<ContainerGroupSection
title="工作容器"
description="Deployment 运行的主容器,定义应用进程及其运行时配置"
title=t('kubernetes.deploymenteditcontainers.sc61b83')
description=t('kubernetes.deploymenteditcontainers.s43eebd')
icon={<Container className="h-4 w-4 dg-text-blue" />}
containers={containers}
accentColor="blue"
@@ -198,7 +200,7 @@ export function DeploymentEditContainers({ clusterCode, namespace, deploymentNam
<span className="text-[var(--dg-text-secondary)] font-semibold ml-1">{containers.length}</span> 个工作容器
</div>
<div className="flex gap-2">
<Button variant="outline" className="border-[var(--dg-border)] dg-text-secondary" onClick={onCancel}>取消</Button>
<Button variant="outline" className="border-[var(--dg-border)] dg-text-secondary" onClick={onCancel}>{t('common.cancel')}</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" />}
保存
@@ -28,6 +28,7 @@ import { useConfirm } from '@/components/ui/confirm-dialog';
import { kubernetesApi } from '@/api';
import { dumpManifest } from './k8s-manifest-utils';
import { ResourceVisualEditor } from './ResourceVisualEditor';
import { useTranslation } from 'react-i18next';
interface Props {
clusterCode: string;
@@ -75,6 +76,7 @@ interface _SvcPortForm {
const toArray = ( v: any) => (Array.isArray(v) ? v : (v?.list || v?.items || v?.data || []));
export function DeploymentEditService({ clusterCode, namespace, deploymentName, manifest, onCancel }: Props) {
const { t } = useTranslation();
const { toast } = useToast();
const confirm = useConfirm();
const [loading, setLoading] = useState(true);
@@ -225,11 +227,11 @@ export function DeploymentEditService({ clusterCode, namespace, deploymentName,
try {
const yaml = await dumpManifest(svcManifest);
await kubernetesApi.applyYAML(clusterCode, yaml);
toast({ title: 'Service 已创建', description: name });
toast({ title: t('kubernetes.deploymenteditservice.sabd7e0'), description: name });
setShowCreate(null);
load();
} catch (e) {
toast({ title: '创建失败', description: e?.message || String(e), variant: 'destructive' });
toast({ title: t('monitor.quickSetupFailed'), description: e?.message || String(e), variant: 'destructive' });
}
};
@@ -260,30 +262,30 @@ export function DeploymentEditService({ clusterCode, namespace, deploymentName,
try {
const yaml = await dumpManifest(manifest);
await kubernetesApi.applyYAML(clusterCode, yaml);
toast({ title: 'Ingress 已创建', description: name });
toast({ title: t('kubernetes.deploymenteditservice.se356fb'), description: name });
setShowCreate(null);
load();
} catch (e) {
toast({ title: '创建失败', description: e?.message || String(e), variant: 'destructive' });
toast({ title: t('monitor.quickSetupFailed'), description: e?.message || String(e), variant: 'destructive' });
}
};
// 删除资源
const deleteResource = async (kind: 'service' | 'ingress', name: string) => {
const ok = await confirm({
title: '删除资源',
description: `确认删除 ${kind === 'service' ? 'Service' : 'Ingress'} 「${name}」?此操作不可撤销。`,
confirmText: '删除',
title: t('kubernetes.deploymenteditservice.s8a2a35'),
description: t('kubernetes.deploymenteditservice.s4742c2', { kind === 'service' ? 'Service' : 'Ingress': kind === 'service' ? 'Service' : 'Ingress', name: name }),
confirmText: t('common.delete'),
variant: 'destructive',
});
if (!ok) return;
try {
const resource = kind === 'service' ? 'services' : 'ingresses';
await kubernetesApi.deleteResourceYaml(clusterCode, namespace, resource, name);
toast({ title: '已删除', description: `${kind === 'service' ? 'Service' : 'Ingress'} ${name} 已删除` });
toast({ title: t('alert.deleted'), description: t('kubernetes.deploymenteditservice.s857e9a', { kind === 'service' ? 'Service' : 'Ingress': kind === 'service' ? 'Service' : 'Ingress', name: name }) });
load();
} catch (e) {
toast({ title: '删除失败', description: e?.message || String(e), variant: 'destructive' });
toast({ title: t('common.deleteFailed'), description: e?.message || String(e), variant: 'destructive' });
}
};
@@ -292,7 +294,7 @@ export function DeploymentEditService({ clusterCode, namespace, deploymentName,
<Card className="dg-card">
<CardContent className="p-12 text-center">
<Loader2 className="h-6 w-6 animate-spin mx-auto dg-text-muted" />
<p className="dg-text-muted mt-3 text-sm">加载中...</p>
<p className="dg-text-muted mt-3 text-sm">{t('common.loading')}</p>
</CardContent>
</Card>
);
@@ -305,13 +307,13 @@ export function DeploymentEditService({ clusterCode, namespace, deploymentName,
<CardContent className="p-3">
<div className="flex items-center gap-2 text-xs dg-text-secondary">
<Network className="h-3.5 w-3.5 dg-text-blue" />
<span>选择器:</span>
<span>{t('kubernetes.deploymenteditservice.sb8eef7')}</span>
<div className="flex flex-wrap gap-1">
{Object.entries(selectorLabels).map(([k, v]) => (
<code key={k} className="bg-[var(--dg-bg-tertiary)] px-1.5 py-0.5 rounded text-[var(--dg-text-secondary)] text-[11px]">{k}={v}</code>
))}
{Object.keys(selectorLabels).length === 0 && (
<span className="dg-text-muted italic">(无 selector)</span>
<span className="dg-text-muted italic">{t('kubernetes.deploymenteditservice.s33360b')}</span>
)}
</div>
<Button size="sm" variant="ghost" className="h-6 ml-auto text-xs dg-text-secondary" onClick={load}>
@@ -338,7 +340,7 @@ export function DeploymentEditService({ clusterCode, namespace, deploymentName,
<Plus className="h-3 w-3 mr-1" />创建 Service
</Button>
</div>
<p className="text-xs dg-text-muted mt-1">仅显示 selector 匹配此 Deployment 的关联 Service</p>
<p className="text-xs dg-text-muted mt-1">{t('kubernetes.deploymenteditservice.sd0ad85')}</p>
</CardHeader>
<CardContent className="pt-0">
{matchedSvcs.length === 0 && showCreate !== 'service' ? (
@@ -356,14 +358,14 @@ export function DeploymentEditService({ clusterCode, namespace, deploymentName,
{matched ? <CheckCircle className="h-4 w-4 dg-text-blue" /> : <Network className="h-4 w-4 dg-text-muted" />}
<span className="text-sm font-semibold text-[var(--dg-text-primary)]">{svc.name}</span>
<Badge variant="outline" className="border-[var(--dg-border)] dg-text-secondary text-[10px]">{svc.type}</Badge>
{matched && <Badge className="bg-blue-500/20 text-blue-300 border-blue-500/30 text-[10px]">关联</Badge>}
{matched && <Badge className="bg-blue-500/20 text-blue-300 border-blue-500/30 text-[10px]">{t('kubernetes.deploymenteditservice.s1c3cf7')}</Badge>}
<code className="text-[11px] dg-text-muted ml-auto">{svc.clusterIP}</code>
<Button size="sm" variant="ghost" className="h-6 text-xs dg-text-green"
onClick={() => setVisualEditor({ resource: 'services', name: svc.name })}>
<Pencil className="h-3 w-3 mr-1" />编辑
</Button>
<Button size="sm" variant="ghost" className="h-6 w-6 p-0 dg-text-red hover:dg-text-red"
title="删除 Service" onClick={() => deleteResource('service', svc.name)}>
title=t('kubernetes.service.deleteService') onClick={() => deleteResource('service', svc.name)}>
<Trash2 className="h-3 w-3" />
</Button>
</div>
@@ -399,13 +401,13 @@ export function DeploymentEditService({ clusterCode, namespace, deploymentName,
{/* 基本信息 */}
<div className="grid grid-cols-2 gap-2">
<div>
<Label className="dg-text-muted text-[11px]">名称</Label>
<Label className="dg-text-muted text-[11px]">{t('common.name')}</Label>
<Input value={svcForm.name} onChange={e => setSvcForm(s => ({ ...s, name: e.target.value }))}
placeholder={`${deploymentName}-svc`}
className="h-7 mt-0.5 dg-input text-[var(--dg-text-secondary)] text-xs font-mono" />
</div>
<div>
<Label className="dg-text-muted text-[11px]">类型</Label>
<Label className="dg-text-muted text-[11px]">{t('common.type')}</Label>
<select value={svcForm.type} onChange={e => setSvcForm(s => ({ ...s, type: e.target.value }))}
className="h-7 mt-0.5 w-full bg-[var(--dg-bg-tertiary)] border border-[var(--dg-border)] rounded text-xs text-[var(--dg-text-secondary)] px-2">
<option value="ClusterIP">ClusterIP</option>
@@ -416,7 +418,7 @@ export function DeploymentEditService({ clusterCode, namespace, deploymentName,
{/* 快速预设 */}
<div>
<Label className="dg-text-muted text-[11px] mb-1 block">快速添加常用端口</Label>
<Label className="dg-text-muted text-[11px] mb-1 block">{t('kubernetes.deploymenteditservice.s83907c')}</Label>
<div className="flex gap-1.5">
{PORT_PRESETS.map(p => (
<button key={p.name} onClick={() => addPort(p)}
@@ -477,19 +479,19 @@ export function DeploymentEditService({ clusterCode, namespace, deploymentName,
{/* Selector 预览 */}
<div className="text-[10px] dg-text-muted border-t border-[var(--dg-border)]/50 pt-2">
<span className="dg-text-muted">selector (自动检测): </span>
<span className="dg-text-muted">{t('kubernetes.deploymenteditservice.sfd3a08')} </span>
{Object.keys(selectorLabels).length > 0 ? (
Object.entries(selectorLabels).map(([k, v]) => (
<code key={k} className="bg-[var(--dg-bg-tertiary)] px-1 py-0.5 rounded dg-text-secondary ml-1">{k}={v}</code>
))
) : (
<span className="dg-text-muted italic">未检测到</span>
<span className="dg-text-muted italic">{t('kubernetes.deploymenteditservice.s5847b0')}</span>
)}
</div>
<div className="flex justify-end gap-2 pt-1">
<Button size="sm" variant="ghost" className="h-7 text-xs dg-text-secondary" onClick={() => setShowCreate(null)}>取消</Button>
<Button size="sm" className="h-7 bg-blue-600 hover:bg-blue-700 text-xs" onClick={createService}>创建</Button>
<Button size="sm" variant="ghost" className="h-7 text-xs dg-text-secondary" onClick={() => setShowCreate(null)}>{t('common.cancel')}</Button>
<Button size="sm" className="h-7 bg-blue-600 hover:bg-blue-700 text-xs" onClick={createService}>{t('common.create')}</Button>
</div>
</div>
)}
@@ -513,7 +515,7 @@ export function DeploymentEditService({ clusterCode, namespace, deploymentName,
<Plus className="h-3 w-3 mr-1" />创建 Ingress
</Button>
</div>
<p className="text-xs dg-text-muted mt-1">backend 指向关联 Service 的 Ingress 自动高亮</p>
<p className="text-xs dg-text-muted mt-1">{t('kubernetes.deploymenteditservice.s847cc9')}</p>
</CardHeader>
<CardContent className="pt-0">
{ingresses.length === 0 ? (
@@ -531,13 +533,13 @@ export function DeploymentEditService({ clusterCode, namespace, deploymentName,
{matched ? <CheckCircle className="h-4 w-4 dg-text-purple" /> : <GitBranch className="h-4 w-4 dg-text-muted" />}
<span className="text-sm font-semibold text-[var(--dg-text-primary)]">{ing.name}</span>
<Badge variant="outline" className="border-[var(--dg-border)] dg-text-secondary text-[10px]">{ing.className}</Badge>
{matched && <Badge className="bg-purple-500/20 text-purple-300 border-purple-500/30 text-[10px]">关联</Badge>}
{matched && <Badge className="bg-purple-500/20 text-purple-300 border-purple-500/30 text-[10px]">{t('kubernetes.deploymenteditservice.s1c3cf7')}</Badge>}
<Button size="sm" variant="ghost" className="h-6 text-xs dg-text-green ml-auto"
onClick={() => setVisualEditor({ resource: 'ingresses', name: ing.name })}>
<Pencil className="h-3 w-3 mr-1" />编辑
</Button>
<Button size="sm" variant="ghost" className="h-6 w-6 p-0 dg-text-red hover:dg-text-red"
title="删除 Ingress" onClick={() => deleteResource('ingress', ing.name)}>
title=t('kubernetes.ingress.deleteIngress') onClick={() => deleteResource('ingress', ing.name)}>
<Trash2 className="h-3 w-3" />
</Button>
</div>
@@ -569,7 +571,7 @@ export function DeploymentEditService({ clusterCode, namespace, deploymentName,
</div>
<div className="grid grid-cols-2 gap-2">
<div>
<Label className="dg-text-muted text-[11px]">名称</Label>
<Label className="dg-text-muted text-[11px]">{t('common.name')}</Label>
<Input value={ingForm.name} onChange={e => setIngForm(s => ({ ...s, name: e.target.value }))}
placeholder={`${deploymentName}-ingress`}
className="h-7 mt-0.5 dg-input text-[var(--dg-text-secondary)] text-xs font-mono" />
@@ -581,7 +583,7 @@ export function DeploymentEditService({ clusterCode, namespace, deploymentName,
className="h-7 mt-0.5 dg-input text-[var(--dg-text-secondary)] text-xs font-mono" />
</div>
<div>
<Label className="dg-text-muted text-[11px]">host (域名)</Label>
<Label className="dg-text-muted text-[11px]">{t('kubernetes.deploymenteditservice.s4d9e8d')}</Label>
<Input value={ingForm.host} onChange={e => setIngForm(s => ({ ...s, host: e.target.value }))}
placeholder="app.example.com"
className="h-7 mt-0.5 dg-input text-[var(--dg-text-secondary)] text-xs font-mono" />
@@ -593,14 +595,14 @@ export function DeploymentEditService({ clusterCode, namespace, deploymentName,
className="h-7 mt-0.5 dg-input text-[var(--dg-text-secondary)] text-xs font-mono" />
</div>
<div>
<Label className="dg-text-muted text-[11px]">Service 端口</Label>
<Label className="dg-text-muted text-[11px]">{t('kubernetes.deploymenteditservice.sef5625')}</Label>
<Input type="number" value={ingForm.svcPort} onChange={e => setIngForm(s => ({ ...s, svcPort: e.target.value }))}
className="h-7 mt-0.5 dg-input text-[var(--dg-text-secondary)] text-xs font-mono" />
</div>
</div>
<div className="flex justify-end gap-2 pt-1">
<Button size="sm" variant="ghost" className="h-7 text-xs dg-text-secondary" onClick={() => setShowCreate(null)}>取消</Button>
<Button size="sm" className="h-7 bg-purple-600 hover:bg-purple-700 text-xs" onClick={createIngress}>创建</Button>
<Button size="sm" variant="ghost" className="h-7 text-xs dg-text-secondary" onClick={() => setShowCreate(null)}>{t('common.cancel')}</Button>
<Button size="sm" className="h-7 bg-purple-600 hover:bg-purple-700 text-xs" onClick={createIngress}>{t('common.create')}</Button>
</div>
</div>
)}
@@ -619,7 +621,7 @@ export function DeploymentEditService({ clusterCode, namespace, deploymentName,
)}
<div className="flex justify-end gap-2 pt-2">
<Button size="sm" variant="outline" className="h-7 text-xs border-[var(--dg-border)] dg-text-secondary" onClick={onCancel}>返回查看</Button>
<Button size="sm" variant="outline" className="h-7 text-xs border-[var(--dg-border)] dg-text-secondary" onClick={onCancel}>{t('kubernetes.deploymenteditservice.s3a7752')}</Button>
</div>
</div>
);
@@ -28,6 +28,8 @@ import {
emptyMountRow,
} from './deployment-volume-utils';
import type { JsonData } from '@/types/common';
import { useTranslation } from 'react-i18next';
import i18n from '@/i18n';
interface Props {
clusterCode: string;
@@ -39,12 +41,12 @@ interface Props {
}
const VOLUME_TYPES: { key: VolumeForm['type']; label: string; icon: typeof HardDrive; color: string }[] = [
{ key: 'persistentVolumeClaim', label: '存储卷声明', icon: Database, color: 'dg-text-green' },
{ key: 'emptyDir', label: '临时目录(EmptyDir)', icon: Disc, color: 'dg-text-secondary' },
{ key: 'persistentVolumeClaim', label: i18n.t('kubernetes.deploymenteditstorage.s18c900'), icon: Database, color: 'dg-text-green' },
{ key: 'emptyDir', label: i18n.t('kubernetes.deploymenteditstorage.s5449b2'), icon: Disc, color: 'dg-text-secondary' },
{ key: 'hostPath', label: 'HostPath', icon: HardDrive, color: 'dg-text-yellow' },
{ key: 'nfs', label: 'NFS', icon: Server, color: 'dg-text-purple' },
{ key: 'configMap', label: '配置字典', icon: File, color: 'dg-text-blue' },
{ key: 'secret', label: '密文', icon: Lock, color: 'text-rose-400' },
{ key: 'configMap', label: i18n.t('kubernetes.deploymenteditstorage.s0986a6'), icon: File, color: 'dg-text-blue' },
{ key: 'secret', label: i18n.t('kubernetes.deploymenteditstorage.sc09936'), icon: Lock, color: 'text-rose-400' },
];
const SELECTABLE_TYPES = new Set(VOLUME_TYPES.map((t) => t.key));
@@ -52,6 +54,7 @@ const SELECTABLE_TYPES = new Set(VOLUME_TYPES.map((t) => t.key));
type CreateResourceKind = 'configmaps' | 'secrets' | 'pvcs';
export function DeploymentEditStorage({ clusterCode, namespace, deploymentName, manifest, onSaved, onCancel }: Props) {
const { t } = useTranslation();
const { toast } = useToast();
const [saving, setSaving] = useState(false);
const [loading, setLoading] = useState(!manifest);
@@ -128,20 +131,20 @@ export function DeploymentEditStorage({ clusterCode, namespace, deploymentName,
const save = async () => {
for (const entry of entries) {
if (!entry.volume.name.trim()) {
toast({ title: '请填写数据卷名称', variant: 'destructive' });
toast({ title: t('kubernetes.deploymenteditstorage.s5b59d2'), variant: 'destructive' });
return;
}
if (!formToVolume(entry.volume)) {
const hint = entry.volume.type === 'configMap' ? '请选择 ConfigMap'
: entry.volume.type === 'secret' ? '请选择 Secret'
: entry.volume.type === 'persistentVolumeClaim' ? '请选择 PVC'
: '的类型必填项';
toast({ title: '数据卷配置不完整', description: `请为「${entry.volume.name}」${hint}`, variant: 'destructive' });
const hint = entry.volume.type === 'configMap' ? t('kubernetes.deploymenteditstorage.s2a6856')
: entry.volume.type === 'secret' ? t('kubernetes.deploymenteditstorage.s1f31e4')
: entry.volume.type === 'persistentVolumeClaim' ? t('kubernetes.deploymenteditstorage.sba9fc6')
: t('kubernetes.deploymenteditstorage.s03480a');
toast({ title: t('kubernetes.deploymenteditstorage.se542a6'), description: t('kubernetes.deploymenteditstorage.s3152b4', { entry.volume.name: entry.volume.name, hint: hint }), variant: 'destructive' });
return;
}
const validMounts = entry.mounts.filter((m) => m.mountPath.trim());
if (validMounts.length === 0) {
toast({ title: '请填写挂载路径', description: `数据卷「${entry.volume.name}」需至少挂载到一个容器`, variant: 'destructive' });
toast({ title: t('kubernetes.deploymenteditstorage.s24b5b9'), description: t('kubernetes.deploymenteditstorage.s5532a8', { entry.volume.name: entry.volume.name }), variant: 'destructive' });
return;
}
}
@@ -150,10 +153,10 @@ export function DeploymentEditStorage({ clusterCode, namespace, deploymentName,
const { volumes, mounts } = volumeEntriesToStorage(entries);
const base = applyStorageToManifest(rawManifest, volumes, mounts, passthroughVolumes);
await saveDeploymentManifest(clusterCode, namespace, deploymentName, base);
toast({ title: '存储配置已保存', description: `${deploymentName} 更新已提交` });
toast({ title: t('kubernetes.deploymenteditstorage.sa8cd7d'), description: t('kubernetes.deploymenteditstorage.s1952a7', { deploymentName: deploymentName }) });
onSaved(base);
} catch (e) {
toast({ title: '保存失败', description: (e as Error)?.message || String(e), variant: 'destructive' });
toast({ title: t('common.saveFailed'), description: (e as Error)?.message || String(e), variant: 'destructive' });
} finally { setSaving(false); }
};
@@ -162,7 +165,7 @@ export function DeploymentEditStorage({ clusterCode, namespace, deploymentName,
<Card className="dg-card">
<CardContent className="p-12 text-center">
<Loader2 className="h-6 w-6 animate-spin mx-auto dg-text-muted" />
<p className="dg-text-muted mt-3 text-sm">加载中...</p>
<p className="dg-text-muted mt-3 text-sm">{t('common.loading')}</p>
</CardContent>
</Card>
);
@@ -171,7 +174,7 @@ export function DeploymentEditStorage({ clusterCode, namespace, deploymentName,
if (!manifest) {
return (
<Card className="dg-card">
<CardContent className="p-8 text-center dg-text-muted">未获取到 manifest 数据,请使用 YAML 编辑模式。</CardContent>
<CardContent className="p-8 text-center dg-text-muted">{t('kubernetes.deploymenteditstorage.s800b9f')}</CardContent>
</Card>
);
}
@@ -198,7 +201,7 @@ export function DeploymentEditStorage({ clusterCode, namespace, deploymentName,
数据卷
<Badge variant="outline" className="border-[var(--dg-border)] dg-text-secondary">{entries.length}</Badge>
</CardTitle>
<p className="text-[11px] dg-text-muted mt-1">定义数据卷,并将其挂载到工作负载的容器中</p>
<p className="text-[11px] dg-text-muted mt-1">{t('kubernetes.deploymenteditstorage.s1e0b32')}</p>
</div>
<Button size="sm" variant="outline" className="h-7 border-[var(--dg-border)] text-[var(--dg-text-secondary)] text-xs shrink-0" onClick={addEntry}>
<Plus className="h-3 w-3 mr-1" />添加数据卷
@@ -222,7 +225,7 @@ export function DeploymentEditStorage({ clusterCode, namespace, deploymentName,
<div className="p-3 space-y-2.5 border-b border-[var(--dg-border)]/80">
<div className="flex items-center gap-2 flex-wrap">
<VIcon className={`h-4 w-4 ${vtype?.color || 'dg-text-secondary'}`} />
<span className="text-xs dg-text-secondary shrink-0">数据卷名称</span>
<span className="text-xs dg-text-secondary shrink-0">{t('kubernetes.deploymenteditstorage.sa3119d')}</span>
<Input
value={vol.name}
onChange={(e) => {
@@ -233,7 +236,7 @@ export function DeploymentEditStorage({ clusterCode, namespace, deploymentName,
if (vol.type === 'persistentVolumeClaim' && !vol.pvcName) patch.pvcName = name;
updateVolume(i, patch);
}}
placeholder="如 app-logs / fluent-bit-config"
placeholder=t('kubernetes.deploymenteditstorage.s478bfa')
className="h-8 w-44 dg-input text-sm font-mono"
/>
{/* 原生 select,避免 Radix Select 在 overflow 容器内无法下拉 // Logan.Li */}
@@ -295,7 +298,7 @@ export function DeploymentEditStorage({ clusterCode, namespace, deploymentName,
onChange={(e) => updateMount(i, mi, { containerName: e.target.value })}
className="h-8 min-w-[140px] max-w-[280px] bg-[var(--dg-bg-tertiary)] border border-[var(--dg-border)] rounded-md text-sm text-[var(--dg-text-primary)] px-2 font-medium truncate"
>
{containers.length === 0 && <option value="">(无容器)</option>}
{containers.length === 0 && <option value="">{t('kubernetes.deploymenteditstorage.s327178')}</option>}
{containers.map((cn) => <option key={cn} value={cn}>{cn}</option>)}
</select>
<div className="flex items-center gap-1 bg-[var(--dg-bg-tertiary)] rounded-lg p-0.5 border border-[var(--dg-border)]">
@@ -311,7 +314,7 @@ export function DeploymentEditStorage({ clusterCode, namespace, deploymentName,
<Input
value={mount.mountPath}
onChange={(e) => updateMount(i, mi, { mountPath: e.target.value })}
placeholder="挂载路径 /bitcloud/app/.../logs"
placeholder=t('kubernetes.deploymenteditstorage.seb88e4')
className="h-8 flex-1 min-w-[200px] dg-input text-sm font-mono"
/>
{entry.mounts.length > 1 && (
@@ -321,11 +324,11 @@ export function DeploymentEditStorage({ clusterCode, namespace, deploymentName,
)}
</div>
<div className="flex items-center gap-2">
<span className="text-[11px] dg-text-muted shrink-0">子路径 subPath</span>
<span className="text-[11px] dg-text-muted shrink-0">{t('kubernetes.deploymenteditstorage.sf4b25a')}</span>
<Input
value={mount.subPath}
onChange={(e) => updateMount(i, mi, { subPath: e.target.value })}
placeholder="如 config.yaml(挂载单文件时填写)"
placeholder=t('kubernetes.deploymenteditstorage.s68ab2e')
className="h-7 flex-1 max-w-md dg-input text-[var(--dg-text-secondary)] text-xs font-mono"
/>
</div>
@@ -339,7 +342,7 @@ export function DeploymentEditStorage({ clusterCode, namespace, deploymentName,
</Card>
<div className="flex justify-end gap-2 pt-2">
<Button variant="outline" className="border-[var(--dg-border)] dg-text-secondary" onClick={onCancel}>取消</Button>
<Button variant="outline" className="border-[var(--dg-border)] dg-text-secondary" onClick={onCancel}>{t('common.cancel')}</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" />}
保存
@@ -25,8 +25,10 @@ import type { DeploymentViewProps, SvcItem, IngItem, EventItem } from './deploym
export type { DeploymentViewProps } from './deployment-view/types';
import type { JsonData } from '@/types/common';
import { useTranslation } from 'react-i18next';
export function DeploymentView(props: DeploymentViewProps) {
const { t } = useTranslation();
const { clusterCode, namespace, deployment, pods, revisions, onRefresh } = props;
const { toast } = useToast();
const confirm = useConfirm();
@@ -138,19 +140,19 @@ export function DeploymentView(props: DeploymentViewProps) {
const handleRollback = async (rev: JsonData) => {
const revision = rev.revision ?? rev.revision_number ?? rev.number;
const ok = await confirm({
title: '回滚版本',
description: `确认回滚到修订版本 #${revision}?`,
confirmText: '回滚',
title: t('kubernetes.deploymentview.s6a374e'),
description: t('kubernetes.deploymentview.s01eec9', { revision: revision }),
confirmText: t('common.rollback'),
variant: 'destructive',
});
if (!ok) return;
setRollbackLoading(revision);
try {
await kubernetesApi.rollbackDeployment(clusterCode, namespace, deployment.name, Number(revision));
toast({ title: '回滚已下发', description: `正在回滚到 #${revision}` });
toast({ title: t('kubernetes.deploymentview.s754d92'), description: t('kubernetes.deploymentview.s817a27', { revision: revision }) });
onRefresh();
} catch (e) {
toast({ title: '回滚失败', description: e?.message || String(e), variant: 'destructive' });
toast({ title: t('pipeline.rollbackFailed'), description: e?.message || String(e), variant: 'destructive' });
} finally { setRollbackLoading(null); }
};
@@ -159,19 +161,19 @@ export function DeploymentView(props: DeploymentViewProps) {
setScaleLoading(true);
try {
await kubernetesApi.scaleDeployment(clusterCode, namespace, deployment.name, scaleValue);
toast({ title: '伸缩已提交', description: `副本数 → ${scaleValue}` });
toast({ title: t('kubernetes.deploymentview.sb9c9e0'), description: t('kubernetes.deploymentview.sb8f328', { scaleValue: scaleValue }) });
onRefresh();
} catch (e) {
toast({ title: '伸缩失败', description: e?.message || String(e), variant: 'destructive' });
toast({ title: t('kubernetes.msg.scaleFailed'), description: e?.message || String(e), variant: 'destructive' });
} finally { setScaleLoading(false); }
};
const TABS = [
{ key: 'pods', label: '容器组', icon: Container, count: pods.length },
{ key: 'services', label: '访问方式', icon: Network, count: services.length },
{ key: 'events', label: '事件', icon: Activity, count: events.length },
{ key: 'scale', label: '容器伸缩', icon: Plus },
{ key: 'history', label: '历史版本', icon: History, count: revisions.length },
{ key: 'pods', label: t('kubernetes.deploymentview.s479692'), icon: Container, count: pods.length },
{ key: 'services', label: t('kubernetes.deploymentview.s706804'), icon: Network, count: services.length },
{ key: 'events', label: t('menu.events'), icon: Activity, count: events.length },
{ key: 'scale', label: t('kubernetes.deploymentview.s3b291d'), icon: Plus },
{ key: 'history', label: t('kubernetes.deployment.revisions'), icon: History, count: revisions.length },
];
return (
@@ -180,24 +182,24 @@ export function DeploymentView(props: DeploymentViewProps) {
<Card className="dg-card">
<CardContent className="p-4">
<div className="grid grid-cols-2 md:grid-cols-3 lg:grid-cols-6 gap-3 text-sm">
<InfoItem label="状态" value={
<InfoItem label=t('common.status') value={
<Badge style={{ background: `${isHealthy ? STATUS_COLORS.green : STATUS_COLORS.orange}22`, color: isHealthy ? STATUS_COLORS.green : STATUS_COLORS.orange, border: `1px solid ${isHealthy ? STATUS_COLORS.green : STATUS_COLORS.orange}44` }}>
{isHealthy ? 'Running' : 'Updating'}
</Badge>
} />
<InfoItem label="副本" value={<span className="font-mono">{ready}/{total}</span>} />
<InfoItem label="策略" value={deployment?.strategy || 'RollingUpdate'} />
<InfoItem label=t('kubernetes.deploymentview.s0428b3') value={<span className="font-mono">{ready}/{total}</span>} />
<InfoItem label=t('kubernetes.deploymentview.s669145') value={deployment?.strategy || 'RollingUpdate'} />
{pods[0] && (
<>
<InfoItem label="所在节点" value={
<InfoItem label=t('kubernetes.pod.nodeName') value={
<button className="text-[var(--dg-blue)] hover:underline" onClick={() => window.open(`/kubernetes/${clusterCode}/nodes/${pods[0].node_name || pods[0].node}`, '_blank')}>
{pods[0].node_name || pods[0].node || '-'}
</button>
} />
<InfoItem label="容器组 IP" value={<span className="font-mono">{pods[0].ip || pods[0].pod_ip || '-'}</span>} />
<InfoItem label=t('kubernetes.deploymentview.s6d2d95') value={<span className="font-mono">{pods[0].ip || pods[0].pod_ip || '-'}</span>} />
</>
)}
<InfoItem label="创建时间" value={formatK8sTime(deployment?.created_at || deployment?.creationTimestamp)} />
<InfoItem label=t('common.createdAt') value={formatK8sTime(deployment?.created_at || deployment?.creationTimestamp)} />
</div>
{pods.length === 1 && (
<div className="mt-3 pt-3 border-t border-[var(--dg-border)]">
@@ -243,7 +245,7 @@ export function DeploymentView(props: DeploymentViewProps) {
{scaleValue !== total && (
<Button size="sm" className="h-7 text-xs bg-[var(--dg-blue)] hover:bg-[var(--dg-blue-hover)]"
disabled={scaleLoading} onClick={handleScale}>
{scaleLoading ? <Loader2 className="h-3 w-3 animate-spin" /> : '应用'}
{scaleLoading ? <Loader2 className="h-3 w-3 animate-spin" /> : t('common.apply')}
</Button>
)}
</div>
@@ -40,10 +40,12 @@ import { CREATE_DEPLOYMENT_SLUG, isCreateDeployment } from './deployment-constan
import { extractContainers } from './deployment-detail/helpers';
import { PageShell } from '@/components/layout/PageShell';
import type { ActionModal, DeploymentWorkloadProps } from './deployment-workload/types';
import { useTranslation } from 'react-i18next';
export type { DeploymentWorkloadProps, WorkloadMode } from './deployment-workload/types';
export function DeploymentWorkload({ clusterCode, namespace, deploymentName, mode, onBack, onModeChange }: DeploymentWorkloadProps) {
const { t } = useTranslation();
const isCreate = isCreateDeployment(deploymentName);
const navigate = useNavigate();
const { toast } = useToast();
@@ -117,7 +119,7 @@ export function DeploymentWorkload({ clusterCode, namespace, deploymentName, mod
setRevisions(toArray(revRes));
} catch (e) {
console.error('加载详情失败:', e);
console.error(t('kubernetes.deploymentworkload.sb46ea9'), e);
} finally {
setLoading(false);
}
@@ -132,7 +134,7 @@ export function DeploymentWorkload({ clusterCode, namespace, deploymentName, mod
const { manifest: parsed } = await parseEditableManifest(yamlText);
setManifest(parsed || deployment);
} catch (e) {
console.warn('加载 manifest 失败(编辑功能降级):', e);
console.warn(t('kubernetes.deploymentworkload.sce123f'), e);
setManifest(deployment);
}
}, [clusterCode, namespace, deploymentName, deployment]);
@@ -160,10 +162,10 @@ export function DeploymentWorkload({ clusterCode, namespace, deploymentName, mod
setActionLoading('scale');
try {
await kubernetesApi.scaleDeployment(clusterCode, namespace, deploymentName, newReplicas);
toast({ title: '扩缩容成功', description: `副本数已设置为 ${newReplicas}` });
toast({ title: t('kubernetes.deploymentworkload.s0b3ea1'), description: t('kubernetes.deploymentworkload.sacbcbd', { newReplicas: newReplicas }) });
loadData();
} catch (e) {
toast({ title: '操作失败', description: e?.message || String(e), variant: 'destructive' });
toast({ title: t('common.operationFailed'), description: e?.message || String(e), variant: 'destructive' });
} finally { setActionLoading(''); }
};
@@ -171,37 +173,37 @@ export function DeploymentWorkload({ clusterCode, namespace, deploymentName, mod
setActionLoading('scale');
try {
await kubernetesApi.scaleDeployment(clusterCode, namespace, deploymentName, scaleValue);
toast({ title: '伸缩成功', description: `副本数已设置为 ${scaleValue}` });
toast({ title: t('kubernetes.msg.scaleSuccess'), description: t('kubernetes.deploymentworkload.s1755d8', { scaleValue: scaleValue }) });
setModal(null);
loadData();
} catch (e) {
toast({ title: '操作失败', description: e?.message || String(e), variant: 'destructive' });
toast({ title: t('common.operationFailed'), description: e?.message || String(e), variant: 'destructive' });
} finally { setActionLoading(''); }
};
const handleRestart = async () => {
const ok = await confirm({
title: '滚动重启',
description: `确认滚动重启 Deployment "${deploymentName}"?`,
confirmText: '重启',
title: t('kubernetes.deployment.restart'),
description: t('kubernetes.deploymentworkload.s0703ab', { deploymentName: deploymentName }),
confirmText: t('common.reboot'),
});
if (!ok) return;
setActionLoading('restart');
try {
await kubernetesApi.restartDeployment(clusterCode, namespace, deploymentName);
toast({ title: '重启指令已下发', description: 'Deployment 正在滚动重启' });
toast({ title: t('kubernetes.deploymentworkload.s68a700'), description: t('kubernetes.deploymentworkload.sd18761') });
setTimeout(loadData, 1500);
} catch (e) {
toast({ title: '重启失败', description: e?.message || String(e), variant: 'destructive' });
toast({ title: t('kubernetes.deployment.restartFailed'), description: e?.message || String(e), variant: 'destructive' });
} finally { setActionLoading(''); }
};
const handleTogglePause = async () => {
const isPaused = !!deployment?.paused;
const action = isPaused ? '恢复' : '暂停';
const action = isPaused ? t('common.resume') : t('common.pause');
const ok = await confirm({
title: `${action}滚动更新`,
description: `确认${action} Deployment "${deploymentName}" 的滚动更新?`,
title: t('kubernetes.deploymentworkload.s704225', { action: action }),
description: t('kubernetes.deploymentworkload.se0945f', { action: action, deploymentName: deploymentName }),
confirmText: action,
});
if (!ok) return;
@@ -212,10 +214,10 @@ export function DeploymentWorkload({ clusterCode, namespace, deploymentName, mod
} else {
await kubernetesApi.pauseDeployment(clusterCode, namespace, deploymentName);
}
toast({ title: `${action}成功`, description: `Deployment 滚动更新已${action}` });
toast({ title: t('kubernetes.deploymentworkload.s408125', { action: action }), description: t('kubernetes.deploymentworkload.s6c1899', { action: action }) });
setTimeout(loadData, 1000);
} catch (e) {
toast({ title: `${action}失败`, description: e?.message || String(e), variant: 'destructive' });
toast({ title: t('kubernetes.deploymentworkload.s74fa4c', { action: action }), description: e?.message || String(e), variant: 'destructive' });
} finally { setActionLoading(''); }
};
@@ -232,11 +234,11 @@ export function DeploymentWorkload({ clusterCode, namespace, deploymentName, mod
await kubernetesApi.updateDeploymentImage(
clusterCode, namespace, deploymentName, newImage, cicdContainerName || undefined,
);
toast({ title: '镜像更新成功', description: `正在滚动更新为 ${newImage}` });
toast({ title: t('kubernetes.deploymentworkload.s6df3c3'), description: t('kubernetes.deploymentworkload.sa982c3', { newImage: newImage }) });
setModal(null);
loadData();
} catch (e) {
toast({ title: '更新失败', description: e?.message || String(e), variant: 'destructive' });
toast({ title: t('alert.updateFailed'), description: e?.message || String(e), variant: 'destructive' });
} finally { setActionLoading(''); }
};
@@ -249,11 +251,11 @@ export function DeploymentWorkload({ clusterCode, namespace, deploymentName, mod
const url = `${baseUrl}/api/v1/kubernetes/${clusterCode}/namespace/${namespace}/deployments/${deploymentName}`;
const resp = await fetch(url, { method: 'DELETE', headers: { Authorization: `Bearer ${tk}` } });
if (!resp.ok) throw new Error(`HTTP ${resp.status}`);
toast({ title: '删除成功', description: `${deploymentName} 已删除` });
toast({ title: t('common.deleteSuccess'), description: t('kubernetes.deploymentworkload.saaac2f', { deploymentName: deploymentName }) });
setModal(null);
setTimeout(() => navigate(`/kubernetes/${clusterCode}/namespace/${namespace}/deployments`), 800);
} catch (e) {
toast({ title: '删除失败', description: e?.message || String(e), variant: 'destructive' });
toast({ title: t('common.deleteFailed'), description: e?.message || String(e), variant: 'destructive' });
} finally { setActionLoading(''); }
};
@@ -269,24 +271,24 @@ export function DeploymentWorkload({ clusterCode, namespace, deploymentName, mod
const handleDeletePod = async (pod: any) => {
const ok = await confirm({
title: '删除 Pod',
description: `确认删除 Pod "${pod.name}"?操作不可恢复。`,
confirmText: '删除',
title: t('kubernetes.pod.deletePod'),
description: t('kubernetes.deploymentworkload.s96e132', { pod.name: pod.name }),
confirmText: t('common.delete'),
});
if (!ok) return;
try {
await kubernetesApi.deletePod(clusterCode, namespace, pod.name);
toast({ title: 'Pod 已删除' });
toast({ title: t('kubernetes.pod.deleted') });
loadData();
} catch (e) {
toast({ title: '删除失败', description: (e as any)?.message || String(e), variant: 'destructive' });
toast({ title: t('common.deleteFailed'), description: (e as any)?.message || String(e), variant: 'destructive' });
}
};
// ============ 渲染 // Logan.Li ============
if (loading) {
return (
<PageShell variant="workspace" title={deploymentName} subtitle={`${clusterCode} / ${namespace}`} loading loadingLabel="加载 Deployment..." actions={<Button variant="outline" size="sm" className="dg-btn-secondary" onClick={onBack}><ArrowLeft className="h-4 w-4 mr-1" />返回</Button>}>
<PageShell variant="workspace" title={deploymentName} subtitle={`${clusterCode} / ${namespace}`} loading loadingLabel=t('kubernetes.deploymentworkload.seb300b') actions={<Button variant="outline" size="sm" className="dg-btn-secondary" onClick={onBack}><ArrowLeft className="h-4 w-4 mr-1" />{t('common.back')}</Button>}>
{null}
</PageShell>
);
@@ -294,7 +296,7 @@ export function DeploymentWorkload({ clusterCode, namespace, deploymentName, mod
if (!deployment && !isCreate) {
return (
<PageShell variant="default" title={deploymentName} subtitle={`${clusterCode} / ${namespace}`} actions={<Button variant="outline" size="sm" className="dg-btn-secondary" onClick={onBack}><ArrowLeft className="h-4 w-4 mr-1" />返回</Button>}>
<PageShell variant="default" title={deploymentName} subtitle={`${clusterCode} / ${namespace}`} actions={<Button variant="outline" size="sm" className="dg-btn-secondary" onClick={onBack}><ArrowLeft className="h-4 w-4 mr-1" />{t('common.back')}</Button>}>
<Card className="dg-card"><CardContent className="p-12 text-center"><XCircle className="h-8 w-8 mx-auto dg-text-red" /><p className="dg-text-secondary mt-3">未找到 Deployment: {deploymentName}</p></CardContent></Card>
</PageShell>
);
@@ -306,7 +308,7 @@ export function DeploymentWorkload({ clusterCode, namespace, deploymentName, mod
if (name) navigate(`/kubernetes/${clusterCode}/namespace/${namespace}/workload/view/Deployment/${name}`);
};
return (
<PageShell variant="workspace" title="新建 Deployment" subtitle={`${clusterCode} / ${namespace}`} actions={<Button variant="outline" size="sm" className="dg-btn-secondary" onClick={onBack}><ArrowLeft className="h-4 w-4 mr-1" />返回</Button>}>
<PageShell variant="workspace" title=t('kubernetes.deploymentworkload.se2c85a') subtitle={`${clusterCode} / ${namespace}`} actions={<Button variant="outline" size="sm" className="dg-btn-secondary" onClick={onBack}><ArrowLeft className="h-4 w-4 mr-1" />{t('common.back')}</Button>}>
<EditModeContainer clusterCode={clusterCode} namespace={namespace} deploymentName={CREATE_DEPLOYMENT_SLUG} manifest={manifest} isCreate onSaved={handleCreated} onCancel={onBack} />
</PageShell>
);
@@ -318,8 +320,8 @@ export function DeploymentWorkload({ clusterCode, namespace, deploymentName, mod
const modeTabs = (
<div className="inline-flex rounded-md border border-[var(--dg-border)] overflow-hidden">
<button className={`px-3 py-1.5 text-xs font-medium transition-colors ${mode === 'view' ? 'bg-[var(--dg-bg-active)] text-[var(--dg-text-primary)]' : 'bg-transparent dg-text-secondary hover:text-[var(--dg-text-primary)]'}`} onClick={() => onModeChange('view')}>查看</button>
<button className={`px-3 py-1.5 text-xs font-medium transition-colors ${mode === 'edit' ? 'bg-blue-600 text-white' : 'bg-transparent dg-text-secondary hover:text-[var(--dg-text-primary)]'}`} onClick={() => onModeChange('edit')}>编辑</button>
<button className={`px-3 py-1.5 text-xs font-medium transition-colors ${mode === 'view' ? 'bg-[var(--dg-bg-active)] text-[var(--dg-text-primary)]' : 'bg-transparent dg-text-secondary hover:text-[var(--dg-text-primary)]'}`} onClick={() => onModeChange('view')}>{t('common.view')}</button>
<button className={`px-3 py-1.5 text-xs font-medium transition-colors ${mode === 'edit' ? 'bg-blue-600 text-white' : 'bg-transparent dg-text-secondary hover:text-[var(--dg-text-primary)]'}`} onClick={() => onModeChange('edit')}>{t('common.edit')}</button>
<button className={`px-3 py-1.5 text-xs font-medium transition-colors ${mode === 'yaml' ? 'bg-emerald-600 text-white' : 'bg-transparent dg-text-secondary hover:text-[var(--dg-text-primary)]'}`} onClick={() => onModeChange('yaml')}>YAML</button>
</div>
);
@@ -328,19 +330,19 @@ export function DeploymentWorkload({ clusterCode, namespace, deploymentName, mod
<PageShell
variant="workspace"
title={deploymentName}
subtitle={`${clusterCode} / ${namespace} · Deployment · 镜像: ${deployment?.image || '-'}`}
subtitle={t('kubernetes.deploymentworkload.s804752', { clusterCode: clusterCode, namespace: namespace, deployment?.image || '-': deployment?.image || '-' })}
actions={(
<>
<Button variant="outline" size="sm" className="dg-btn-secondary" onClick={onBack}><ArrowLeft className="h-4 w-4 mr-1" />返回</Button>
<Button variant="outline" size="sm" className="dg-btn-secondary" onClick={onBack}><ArrowLeft className="h-4 w-4 mr-1" />{t('common.back')}</Button>
{modeTabs}
<Button variant="outline" size="sm" className="dg-btn-secondary" onClick={loadData}><RefreshCw className="h-4 w-4" /></Button>
<Button variant="outline" size="sm" className="dg-btn-secondary" onClick={() => { setNewImage(deployment?.image || ''); setModal({ kind: 'image' }); }}><ImageIcon className="h-3.5 w-3.5 mr-1" />调整镜像</Button>
<Button variant="outline" size="sm" className="dg-btn-secondary" onClick={handleRestart}><RotateCw className="h-3.5 w-3.5 mr-1" />重启</Button>
<Button variant="outline" size="sm" className="dg-btn-secondary" onClick={() => { setNewImage(deployment?.image || ''); setModal({ kind: 'image' }); }}><ImageIcon className="h-3.5 w-3.5 mr-1" />{t('kubernetes.deploymentworkload.sf2e020')}</Button>
<Button variant="outline" size="sm" className="dg-btn-secondary" onClick={handleRestart}><RotateCw className="h-3.5 w-3.5 mr-1" />{t('common.reboot')}</Button>
<Button variant="outline" size="sm" className="dg-btn-secondary" disabled={!!actionLoading} onClick={handleTogglePause}>
{deployment?.paused ? <><Play className="h-3.5 w-3.5 mr-1 dg-text-green" />恢复</> : <><Pause className="h-3.5 w-3.5 mr-1 dg-text-orange" />暂停</>}
{deployment?.paused ? <><Play className="h-3.5 w-3.5 mr-1 dg-text-green" />{t('common.resume')}</> : <><Pause className="h-3.5 w-3.5 mr-1 dg-text-orange" />{t('common.pause')}</>}
</Button>
<Button variant="outline" size="sm" className="dg-btn-secondary" onClick={handleCICD}><Rocket className="h-3.5 w-3.5 mr-1 dg-text-purple" />CI/CD</Button>
<Button variant="outline" size="sm" className="dg-btn-danger" onClick={() => setModal({ kind: 'delete' })}><Trash2 className="h-3.5 w-3.5 mr-1" />删除</Button>
<Button variant="outline" size="sm" className="dg-btn-danger" onClick={() => setModal({ kind: 'delete' })}><Trash2 className="h-3.5 w-3.5 mr-1" />{t('common.delete')}</Button>
</>
)}
>
@@ -350,7 +352,7 @@ export function DeploymentWorkload({ clusterCode, namespace, deploymentName, mod
<Badge className={isHealthy ? 'bg-emerald-500/20 dg-text-green border-emerald-500/30' : 'bg-amber-500/20 dg-text-yellow border-amber-500/30'}>
{isHealthy ? <CheckCircle className="h-3 w-3 mr-1" /> : <AlertTriangle className="h-3 w-3 mr-1" />}{ready}/{total}
</Badge>
{deployment?.paused && <Badge className="bg-orange-500/20 dg-text-orange border-orange-500/30"><Pause className="h-3 w-3 mr-1" />已暂停更新</Badge>}
{deployment?.paused && <Badge className="bg-orange-500/20 dg-text-orange border-orange-500/30"><Pause className="h-3 w-3 mr-1" />{t('kubernetes.deploymentworkload.s8be252')}</Badge>}
</div>
{/* ============ 主体:view / edit / yaml ============ */}
@@ -377,7 +379,7 @@ export function DeploymentWorkload({ clusterCode, namespace, deploymentName, mod
resource="deployments"
name={deploymentName}
inline
resourceHint="含关联 Service"
resourceHint=t('kubernetes.deploymentworkload.s239604')
loadYamlFn={loadBundleYaml}
saveYamlFn={saveBundleYaml}
onSaved={loadData}
@@ -402,7 +404,7 @@ export function DeploymentWorkload({ clusterCode, namespace, deploymentName, mod
namespace={namespace}
resource="deployments"
name={deploymentName}
resourceHint="含关联 Service"
resourceHint=t('kubernetes.deploymentworkload.s239604')
loadYamlFn={loadBundleYaml}
saveYamlFn={saveBundleYaml}
onClose={() => setModal(null)}
@@ -5,6 +5,8 @@ import { useVirtualizer } from '@tanstack/react-virtual';
import { Badge } from '@/components/ui/badge';
import { Loader2 } from 'lucide-react';
import {
import { useTranslation } from 'react-i18next';
import i18n from '@/i18n';
type NormalizedEvent,
formatEventRepeatSpan,
formatEventTimeCell,
@@ -30,10 +32,11 @@ const MIN_W = '980px';
export function EventTable({
events,
loading = false,
emptyText = '暂无事件',
emptyText = i18n.t('k8s.empty.events'),
showNamespace = false,
scrollHeight = 600,
}: EventTableProps) {
const { t } = useTranslation();
const [expandedRow, setExpandedRow] = useState<string | null>(null);
const isLoading = loading === true || loading === 'events';
const scrollRef = useRef<HTMLDivElement>(null);
@@ -41,8 +44,8 @@ export function EventTable({
const gridCols = showNamespace ? COLS_NS : COLS;
const minWidth = showNamespace ? MIN_W_NS : MIN_W;
const headers = showNamespace
? ['最后时间', '首次时间', '次数', '重复', '类型', '原因', '对象', '命名空间', '来源', '消息']
: ['最后时间', '首次时间', '次数', '重复', '类型', '原因', '对象', '来源', '消息'];
? [t('kubernetes.eventtable.sc00582'), t('kubernetes.eventtable.s0b2f54'), t('kubernetes.event.eventCount'), t('kubernetes.eventtable.s33e3c0'), t('common.type'), t('kubernetes.event.eventReason'), t('kubernetes.event.eventObject'), t('k8s.column.namespace'), t('common.source'), t('kubernetes.event.eventMessage')]
: [t('kubernetes.eventtable.sc00582'), t('kubernetes.eventtable.s0b2f54'), t('kubernetes.event.eventCount'), t('kubernetes.eventtable.s33e3c0'), t('common.type'), t('kubernetes.event.eventReason'), t('kubernetes.event.eventObject'), t('common.source'), t('kubernetes.event.eventMessage')];
const virtualizer = useVirtualizer({
count: events.length,
@@ -163,7 +166,7 @@ export function EventTable({
{/* 行数统计 */}
{events.length > 0 && (
<div className="text-center py-2 text-xs text-[var(--dg-text-muted)] border-t border-[var(--dg-border)]">
共 {events.length} 条事件 {events.length > 500 && '· 虚拟滚动渲染'}
共 {events.length} 条事件 {events.length > 500 && t('kubernetes.eventtable.sd0a696')}
</div>
)}
</div>
@@ -13,6 +13,7 @@ import { PageShell } from '@/components/layout/PageShell';
import { ContentPanel } from '@/components/layout/ContentPanel';
import { StatStrip } from '@/components/ui/stat-strip';
import type { JsonData } from '@/types/common';
import { useTranslation } from 'react-i18next';
interface RankItem { name: string; count: number }
@@ -26,13 +27,14 @@ function RankPanel({
onSelect?: (name: string) => void;
emptyText?: string;
}) {
const { t } = useTranslation();
const max = Math.max(...items.map((i) => i.count), 1);
return (
<Card className="bg-[var(--dg-bg-secondary)] border-[var(--dg-border)]">
<CardContent className="p-4">
<h3 className="text-sm font-medium text-[var(--dg-text-primary)] mb-3">{title}</h3>
{items.length === 0 ? (
<p className="text-xs text-[var(--dg-text-muted)] py-6 text-center">{emptyText || '暂无数据'}</p>
<p className="text-xs text-[var(--dg-text-muted)] py-6 text-center">{emptyText || t('common.noData')}</p>
) : (
<div className="space-y-1.5 max-h-[220px] overflow-y-auto pr-1">
{items.map((item) => {
@@ -67,6 +69,7 @@ function RankPanel({
}
export default function EventsPage() {
const { t } = useTranslation();
const { clusterCode } = useParams<{ clusterCode: string }>();
const navigate = useNavigate();
const [loading, setLoading] = useState(false);
@@ -160,7 +163,7 @@ export default function EventsPage() {
const filterToolbar = (selectedReason || selectedKind) ? (
<div className="flex items-center gap-2 text-xs">
<span className="text-[var(--dg-text-muted)]">筛选:</span>
<span className="text-[var(--dg-text-muted)]">{t('kubernetes.eventspage.s841389')}</span>
{selectedReason && (
<button type="button" className="inline-flex items-center gap-1 rounded border border-[var(--dg-border)] px-2 py-0.5 text-[var(--dg-text-secondary)] hover:bg-[var(--dg-bg-tertiary)]" onClick={() => setSelectedReason('')}>
原因 {selectedReason} <X className="h-3 w-3" />
@@ -177,16 +180,16 @@ export default function EventsPage() {
return (
<PageShell
variant="list"
title="事件中心"
subtitle={clusterName ? `${clusterName} · 集群事件与告警` : '集群事件与告警'}
title=t('kubernetes.eventspage.s08bf79')
subtitle={clusterName ? t('kubernetes.eventspage.s49c5d1', { clusterName: clusterName }) : t('kubernetes.eventspage.s6bef2b')}
icon={<Bell className="h-5 w-5" />}
metrics={!loading ? (
<StatStrip
items={[
{ label: '事件总数', value: summary?.total ?? events.length, color: 'muted' },
{ label: '告警事件', value: summary?.warning_count ?? warningCount, color: 'amber' },
{ label: '正常事件', value: summary?.normal_count ?? normalCount, color: 'green' },
{ label: '告警类型', value: reasonData.length, color: 'red' },
{ label: t('kubernetes.eventspage.s0d3047'), value: summary?.total ?? events.length, color: 'muted' },
{ label: t('kubernetes.eventspage.s0e5b83'), value: summary?.warning_count ?? warningCount, color: 'amber' },
{ label: t('kubernetes.eventspage.s349c62'), value: summary?.normal_count ?? normalCount, color: 'green' },
{ label: t('kubernetes.eventspage.sc62e34'), value: reasonData.length, color: 'red' },
]}
/>
) : undefined}
@@ -202,20 +205,20 @@ export default function EventsPage() {
</SelectContent>
</Select>
<Select value={selectedNs} onValueChange={(v) => { setSelectedNs(v); setSelectedReason(''); setSelectedKind(''); }}>
<SelectTrigger className="w-36 h-9 dg-input"><SelectValue placeholder="命名空间" /></SelectTrigger>
<SelectTrigger className="w-36 h-9 dg-input"><SelectValue placeholder=t('k8s.column.namespace') /></SelectTrigger>
<SelectContent>
<SelectItem value="all">所有命名空间</SelectItem>
<SelectItem value="all">{t('kubernetes.eventspage.s58173b')}</SelectItem>
{namespaces.map((n) => <SelectItem key={n} value={n}>{n}</SelectItem>)}
</SelectContent>
</Select>
<Select value={timeWindow} onValueChange={setTimeWindow}>
<SelectTrigger className="w-32 h-9 dg-input"><SelectValue /></SelectTrigger>
<SelectContent>
<SelectItem value="0">全部时间</SelectItem>
<SelectItem value="1">近 1 小时</SelectItem>
<SelectItem value="6">近 6 小时</SelectItem>
<SelectItem value="24">近 24 小时</SelectItem>
<SelectItem value="168">近 7 天</SelectItem>
<SelectItem value="0">{t('kubernetes.eventspage.s98c99f')}</SelectItem>
<SelectItem value="1">{t('kubernetes.eventspage.sf972b7')}</SelectItem>
<SelectItem value="6">{t('monitor.siteProtocol.rangeDefault')}</SelectItem>
<SelectItem value="24">{t('kubernetes.eventspage.s6e99b7')}</SelectItem>
<SelectItem value="168">{t('kubernetes.eventspage.sd765ef')}</SelectItem>
</SelectContent>
</Select>
<Button variant="outline" size="sm" className="dg-btn-secondary" onClick={() => { loadEvents(); loadSummary(); }} disabled={loading}>
@@ -227,10 +230,10 @@ export default function EventsPage() {
>
{reasonData.length > 0 && (
<div className="grid grid-cols-1 lg:grid-cols-3 gap-4">
<RankPanel title="告警原因" items={reasonData} selected={selectedReason} onSelect={setSelectedReason} />
{nsData.length > 0 && <RankPanel title="命名空间" items={nsData} />}
<RankPanel title=t('kubernetes.eventspage.s8c894f') items={reasonData} selected={selectedReason} onSelect={setSelectedReason} />
{nsData.length > 0 && <RankPanel title=t('k8s.column.namespace') items={nsData} />}
{kindData.length > 0 && (
<RankPanel title="资源类型" items={kindData} selected={selectedKind} onSelect={setSelectedKind} />
<RankPanel title=t('kubernetes.eventspage.s14871a') items={kindData} selected={selectedKind} onSelect={setSelectedKind} />
)}
</div>
)}
@@ -268,7 +271,7 @@ export default function EventsPage() {
<Select value={filterType} onValueChange={setFilterType}>
<SelectTrigger className="w-28 h-8 dg-input text-xs"><SelectValue /></SelectTrigger>
<SelectContent>
<SelectItem value="all">所有类型</SelectItem>
<SelectItem value="all">{t('kubernetes.eventspage.sfb9951')}</SelectItem>
<SelectItem value="Warning">Warning</SelectItem>
<SelectItem value="Normal">Normal</SelectItem>
</SelectContent>
@@ -4,6 +4,7 @@ import { useNavigate } from 'react-router-dom';
import { Loader2 } from 'lucide-react';
import { kubernetesApi } from '@/api';
import type { JsonData } from '@/types/common';
import { useTranslation } from 'react-i18next';
interface Props {
/** 集群下路径,如 events、namespace/default/deployments */
@@ -11,6 +12,7 @@ interface Props {
}
export default function K8sShortcutRedirect({ target }: Props) {
const { t } = useTranslation();
const navigate = useNavigate();
useEffect(() => {
@@ -30,7 +32,7 @@ export default function K8sShortcutRedirect({ target }: Props) {
return (
<div className="flex flex-col items-center justify-center py-24 dg-text-muted gap-2">
<Loader2 className="h-6 w-6 animate-spin" />
<span className="text-sm">正在跳转...</span>
<span className="text-sm">{t('kubernetes.k8sshortcutredirect.s9d1aae')}</span>
</div>
);
}
@@ -11,6 +11,7 @@ import 'xterm/css/xterm.css';
import { Terminal, Maximize2, Minimize2, X, Loader2 } from 'lucide-react';
import { cn } from '@/lib/utils';
import { useUserStore } from '@/store';
import { useTranslation } from 'react-i18next';
interface KubectlTerminalProps {
open: boolean;
@@ -20,6 +21,7 @@ interface KubectlTerminalProps {
}
export function KubectlTerminal({ open, onOpenChange, clusterId, clusterName }: KubectlTerminalProps) {
const { t } = useTranslation();
const containerRef = useRef<HTMLDivElement>(null);
const termRef = useRef<XTerm | null>(null);
const wsRef = useRef<WebSocket | null>(null);
@@ -106,12 +108,12 @@ export function KubectlTerminal({ open, onOpenChange, clusterId, clusterName }:
ws.onclose = () => {
setConnected(false);
term.write('\r\n\x1b[31m[连接已断开]\x1b[0m\r\n');
term.write(t('kubernetes.kubectlterminal.sf4ee00'));
};
ws.onerror = () => {
setError('WebSocket 连接失败');
term.write('\r\n\x1b[31m[连接发生错误]\x1b[0m\r\n');
setError(t('kubernetes.kubectlterminal.s5b4a67'));
term.write(t('kubernetes.kubectlterminal.sc81077'));
};
return () => {
@@ -174,7 +176,7 @@ export function KubectlTerminal({ open, onOpenChange, clusterId, clusterName }:
style={fullscreen ? { maxWidth: '100vw', width: '100vw', height: '100vh' } : { maxWidth: '900px', width: '90vw' }}
>
<DialogTitle className="sr-only">kubectl — {clusterName}</DialogTitle>
<DialogDescription className="sr-only">Kubernetes 集群命令行终端</DialogDescription>
<DialogDescription className="sr-only">{t('kubernetes.kubectlterminal.s66981e')}</DialogDescription>
{/* 头部 */}
<div className="flex items-center justify-between px-4 py-2 border-b border-[var(--dg-border)]">
@@ -15,6 +15,7 @@ import {
import { kubernetesApi } from '@/api';
import { toast } from 'sonner';
import type { JsonData } from '@/types/common';
import { useTranslation } from 'react-i18next';
// 名称即 code,只允许英文/数字/连字符
const NAME_RE = /^[a-zA-Z0-9]([a-zA-Z0-9-]*[a-zA-Z0-9])?$/;
@@ -40,6 +41,7 @@ export function KubernetesClusterDialog({
editingCluster?: JsonData;
onSaved: () => void;
}) {
const { t } = useTranslation();
const [formData, setFormData] = useState({ ...emptyForm });
const [submitting, setSubmitting] = useState(false);
const [hasToken, setHasToken] = useState(false);
@@ -88,7 +90,7 @@ export function KubernetesClusterDialog({
if (!value.trim()) {
setNameError('');
} else if (!NAME_RE.test(value)) {
setNameError('只允许英文、数字和连字符(-),首尾不能是连字符');
setNameError(t('kubernetes.kubernetesclusterdialog.sc7ec6c'));
} else {
setNameError('');
}
@@ -110,7 +112,7 @@ export function KubernetesClusterDialog({
const handleSubmit = async () => {
if (!formData.name.trim() || !NAME_RE.test(formData.name.trim())) {
toast.error('请输入有效的集群名称(英文/数字/连字符)'); return;
toast.error(t('kubernetes.kubernetesclusterdialog.s38bbfe')); return;
}
try {
setSubmitting(true);
@@ -132,7 +134,7 @@ export function KubernetesClusterDialog({
onOpenChange(false);
onSaved();
} catch (e) {
console.error('保存集群失败:', e);
console.error(t('kubernetes.kubernetesclusterdialog.s7aa44b'), e);
} finally {
setSubmitting(false);
}
@@ -145,20 +147,20 @@ export function KubernetesClusterDialog({
<DialogContent className="bg-[var(--dg-bg-secondary)] border-[var(--dg-border)] max-w-2xl">
<DialogHeader>
<DialogTitle className="text-[var(--dg-text-primary)]">
{editingCluster ? '编辑集群' : '添加集群'}
{editingCluster ? t('kubernetes.cluster.editCluster') : t('kubernetes.cluster.addCluster')}
</DialogTitle>
<DialogDescription className="text-[var(--dg-text-secondary)]">
{editingCluster ? '修改集群接入配置' : '配置新的 Kubernetes 集群接入信息'}
{editingCluster ? t('kubernetes.kubernetesclusterdialog.s2d42f2') : t('kubernetes.kubernetesclusterdialog.sfe6c79')}
</DialogDescription>
</DialogHeader>
<div className="space-y-4 py-2 max-h-[60vh] overflow-y-auto pr-1">
<div className="grid grid-cols-2 gap-4">
<div className="space-y-2">
<Label className="text-[var(--dg-text-secondary)]">集群名称</Label>
<Label className="text-[var(--dg-text-secondary)]">{t('kubernetes.cluster.clusterName')}</Label>
<Input
value={formData.name}
onChange={(e) => handleNameChange(e.target.value)}
placeholder="如: prod-cluster"
placeholder=t('kubernetes.kubernetesclusterdialog.s298c86')
className={`bg-[var(--dg-bg-tertiary)] border-[var(--dg-border)] text-[var(--dg-text-primary)] placeholder:text-[var(--dg-text-muted)] ${nameError ? 'border-red-500' : ''}`}
/>
{nameError && <p className="text-xs dg-text-red">{nameError}</p>}
@@ -167,28 +169,28 @@ export function KubernetesClusterDialog({
</p>
</div>
<div className="space-y-2">
<Label className="text-[var(--dg-text-secondary)]">版本(可选)</Label>
<Label className="text-[var(--dg-text-secondary)]">{t('kubernetes.kubernetesclusterdialog.sbf23eb')}</Label>
<Input
value={formData.version}
onChange={(e) => setFormData({ ...formData, version: e.target.value })}
placeholder="如: 1.28.0"
placeholder=t('kubernetes.kubernetesclusterdialog.s90a9ef')
className="bg-[var(--dg-bg-tertiary)] border-[var(--dg-border)] text-[var(--dg-text-primary)] placeholder:text-[var(--dg-text-muted)]"
/>
</div>
</div>
<div className="space-y-2">
<Label className="text-[var(--dg-text-secondary)]">描述</Label>
<Label className="text-[var(--dg-text-secondary)]">{t('common.description')}</Label>
<Input
value={formData.description}
onChange={(e) => setFormData({ ...formData, description: e.target.value })}
placeholder="集群用途描述"
placeholder=t('kubernetes.kubernetesclusterdialog.s33a940')
className="bg-[var(--dg-bg-tertiary)] border-[var(--dg-border)] text-[var(--dg-text-primary)] placeholder:text-[var(--dg-text-muted)]"
/>
</div>
<div className="space-y-2">
<Label className="text-[var(--dg-text-secondary)]">接入方式</Label>
<Label className="text-[var(--dg-text-secondary)]">{t('kubernetes.kubernetesclusterdialog.saaa159')}</Label>
<RadioGroup
value={String(formData.config_type)}
onValueChange={(v) => setFormData({ ...formData, config_type: Number(v) })}
@@ -218,12 +220,12 @@ export function KubernetesClusterDialog({
{formData.config_type === 0 ? (
<div className="space-y-2">
<Label className="text-[var(--dg-text-secondary)]">
Token {hasToken && <span className="dg-text-green text-xs ml-1">✓ 已配置(留空不修改)</span>}
Token {hasToken && <span className="dg-text-green text-xs ml-1">{t('kubernetes.kubernetesclusterdialog.sb7caaa')}</span>}
</Label>
<Textarea
value={formData.token}
onChange={(e) => setFormData({ ...formData, token: e.target.value })}
placeholder={hasToken ? '已配置,输入新值覆盖...' : '粘贴 Service Account Token...'}
placeholder={hasToken ? t('kubernetes.kubernetesclusterdialog.sf26ca5') : t('kubernetes.kubernetesclusterdialog.s105008')}
rows={4}
className="bg-[var(--dg-bg-tertiary)] border-[var(--dg-border)] text-[var(--dg-text-primary)] placeholder:text-[var(--dg-text-muted)] font-mono text-xs"
/>
@@ -231,12 +233,12 @@ export function KubernetesClusterDialog({
) : (
<div className="space-y-2">
<Label className="text-[var(--dg-text-secondary)]">
Kubeconfig {hasKubeConfig && <span className="dg-text-green text-xs ml-1">✓ 已配置(留空不修改)</span>}
Kubeconfig {hasKubeConfig && <span className="dg-text-green text-xs ml-1">{t('kubernetes.kubernetesclusterdialog.sb7caaa')}</span>}
</Label>
<Textarea
value={formData.kube_config}
onChange={(e) => handleKubeConfigChange(e.target.value)}
placeholder={hasKubeConfig ? '已配置,输入新值覆盖...' : 'apiVersion: v1\nkind: Config\nclusters:\n- cluster:\n server: https://10.0.0.1:6443\n ...'}
placeholder={hasKubeConfig ? t('kubernetes.kubernetesclusterdialog.sf26ca5') : 'apiVersion: v1\nkind: Config\nclusters:\n- cluster:\n server: https://10.0.0.1:6443\n ...'}
rows={10}
className="bg-[var(--dg-bg-tertiary)] border-[var(--dg-border)] text-[var(--dg-text-primary)] placeholder:text-[var(--dg-text-muted)] font-mono text-xs"
/>
@@ -261,7 +263,7 @@ export function KubernetesClusterDialog({
disabled={canSubmit}
className="bg-[var(--dg-blue)] hover:opacity-90 text-white"
>
{submitting ? '保存中...' : editingCluster ? '保存' : '添加'}
{submitting ? i18n.t('k8s.topology.saving') : editingCluster ? i18n.t('common.save') : i18n.t('common.add')}
</Button>
</DialogFooter>
</DialogContent>
@@ -36,8 +36,10 @@ import { KubernetesClusterDialog } from './KubernetesClusterDialog';
import { KubectlTerminal } from './KubectlTerminal';
import { PageShell } from '@/components/layout/PageShell';
import type { JsonData } from '@/types/common';
import { useTranslation } from 'react-i18next';
export function KubernetesClusters() {
const { t } = useTranslation();
const [clusters, setClusters] = useState<JsonData[]>([]);
const [loading, setLoading] = useState(true);
const [selectedCluster, setSelectedCluster] = useState<string | null>(null);
@@ -61,7 +63,7 @@ export function KubernetesClusters() {
const res: JsonData = await kubernetesApi.getClusters();
setClusters(res?.list || []);
} catch (e) {
console.error('加载集群列表失败:', e);
console.error(t('kubernetes.kubernetesclusters.s64090a'), e);
setClusters([]);
} finally {
setLoading(false);
@@ -95,18 +97,18 @@ export function KubernetesClusters() {
await kubernetesApi.deleteCluster(id);
loadData();
} catch (e) {
console.error('删除集群失败:', e);
console.error(t('kubernetes.kubernetesclusters.s3d78e3'), e);
}
};
const handleSync = async (id: number | string, silent?: boolean) => {
try {
if (!silent) toast.info('正在同步集群资源...');
if (!silent) toast.info(t('kubernetes.kubernetesclusters.sf31179'));
const res: JsonData = await kubernetesApi.syncCluster(id);
if (!silent) toast.success(res?.message || '同步完成');
if (!silent) toast.success(res?.message || t('kubernetes.kubernetesclusters.s02f667'));
loadData();
} catch (e) {
if (!silent) toast.error(e?.message || '同步失败');
if (!silent) toast.error(e?.message || t('cloud.syncFailed'));
}
};
@@ -115,12 +117,12 @@ export function KubernetesClusters() {
const code = exportCluster.code || String(exportCluster.id);
try {
setExporting(true);
toast.info(`正在导出 ${exportCluster.name} 所有命名空间的资源...`);
toast.info(t('kubernetes.kubernetesclusters.s1d9a60', { exportCluster.name: exportCluster.name }));
await kubernetesApi.exportAllResources(code);
toast.success('导出完成,已开始下载');
toast.success(t('kubernetes.kubernetesclusters.s10a4f7'));
setExportCluster(null);
} catch (e) {
toast.error(e?.message || '导出失败');
toast.error(e?.message || t('common.exportFailed'));
} finally {
setExporting(false);
}
@@ -166,7 +168,7 @@ export function KubernetesClusters() {
<div className="relative w-80">
<Search className="absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 dg-text-muted" />
<Input
placeholder="搜索集群名称或版本..."
placeholder=t('kubernetes.kubernetesclusters.s317554')
value={searchQuery}
onChange={(e) => setSearchQuery(e.target.value)}
className="pl-9 h-9 dg-input"
@@ -177,12 +179,12 @@ export function KubernetesClusters() {
return (
<PageShell
variant="list"
title="集群列表"
subtitle="管理 Kubernetes 集群资源"
title=t('menu.clusterList')
subtitle=t('kubernetes.kubernetesclusters.sb0fcb9')
icon={<Cloud className="h-5 w-5" />}
toolbar={searchToolbar}
loading={loading}
loadingLabel="加载集群..."
loadingLabel=t('kubernetes.kubernetesclusters.se5a067')
actions={(
<>
<Button variant="outline" size="sm" className="dg-btn-secondary" onClick={loadData}>
@@ -200,7 +202,7 @@ export function KubernetesClusters() {
<div className="grid grid-cols-1 lg:grid-cols-2 xl:grid-cols-3 gap-4">
{!loading && filteredClusters.length === 0 ? (
<Card className="bg-[var(--dg-bg-secondary)] border-[var(--dg-border)] col-span-full">
<CardContent className="p-12 text-center text-[var(--dg-text-muted)]">暂无集群数据</CardContent>
<CardContent className="p-12 text-center text-[var(--dg-text-muted)]">{t('dashboard.clusters.empty')}</CardContent>
</Card>
) : (
filteredClusters.map((cluster) => {
@@ -243,7 +245,7 @@ export function KubernetesClusters() {
</Button>
</DropdownMenuTrigger>
<DropdownMenuContent align="end" className="w-48 bg-[var(--dg-bg-tertiary)] border-[var(--dg-border)]">
<DropdownMenuLabel className="text-[var(--dg-text-secondary)]">操作</DropdownMenuLabel>
<DropdownMenuLabel className="text-[var(--dg-text-secondary)]">{t('common.actions')}</DropdownMenuLabel>
<DropdownMenuSeparator className="bg-[var(--dg-border-hover)]" />
<DropdownMenuItem className="text-[var(--dg-text-secondary)] focus:bg-[var(--dg-bg-hover)] focus:text-[var(--dg-text-primary)]">
<Eye className="h-4 w-4 mr-2" />
@@ -343,7 +345,7 @@ export function KubernetesClusters() {
<span className="text-xs text-[var(--dg-text-secondary)] w-10 text-right">{cpuUsage.toFixed(1)}%</span>
</div>
<div className="flex items-center gap-2">
<span className="text-xs text-[var(--dg-text-muted)] w-10">内存</span>
<span className="text-xs text-[var(--dg-text-muted)] w-10">{t('k8s.pods.memory')}</span>
<div className="flex-1 h-1.5 bg-[var(--dg-bg-tertiary)] rounded-full overflow-hidden">
<div
className={cn(
@@ -402,7 +404,7 @@ export function KubernetesClusters() {
onClick={() => { if (!exporting) setExportCluster(null); }}
>
<div className="bg-[var(--dg-bg-secondary)] border border-[var(--dg-border)] rounded-lg p-5 w-[420px] shadow-xl" onClick={(e) => e.stopPropagation()}>
<h3 className="text-base font-semibold text-[var(--dg-text-primary)] mb-1">导出集群资源</h3>
<h3 className="text-base font-semibold text-[var(--dg-text-primary)] mb-1">{t('kubernetes.yaml.exportCluster')}</h3>
{exporting ? (
<div className="flex flex-col items-center py-6 gap-3">
<Loader2 className="h-9 w-9 animate-spin text-[var(--dg-blue)]" />
@@ -420,7 +422,7 @@ export function KubernetesClusters() {
Deployment、Service、Ingress、ConfigMap、Secret 为 tar.gz
</p>
<div className="flex justify-end gap-2">
<Button variant="outline" className="border-[var(--dg-border)] text-[var(--dg-text-secondary)]" onClick={() => setExportCluster(null)}>取消</Button>
<Button variant="outline" className="border-[var(--dg-border)] text-[var(--dg-text-secondary)]" onClick={() => setExportCluster(null)}>{t('common.cancel')}</Button>
<Button className="bg-[var(--dg-blue)] hover:opacity-90 text-white" onClick={handleExport}>
<Download className="h-4 w-4 mr-1.5" />
确认导出
@@ -13,8 +13,10 @@ import { kubernetesApi } from '@/api';
import { PageShell } from '@/components/layout/PageShell';
import { ContentPanel } from '@/components/layout/ContentPanel';
import type { JsonData } from '@/types/common';
import { useTranslation } from 'react-i18next';
export function KubernetesNodes() {
const { t } = useTranslation();
const [clusters, setClusters] = useState<JsonData[]>([]);
const [selectedCluster, setSelectedCluster] = useState('');
const [nodes, setNodes] = useState<JsonData[]>([]);
@@ -63,14 +65,14 @@ export function KubernetesNodes() {
<div className="flex items-center gap-3 flex-wrap">
<div className="relative w-56">
<Search className="absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 dg-text-muted" />
<Input placeholder="搜索节点..." value={search} onChange={(e) => setSearch(e.target.value)} className="pl-9 h-9 dg-input" />
<Input placeholder=t('k8s.topology.searchPlaceholder') value={search} onChange={(e) => setSearch(e.target.value)} className="pl-9 h-9 dg-input" />
</div>
<Select value={roleFilter} onValueChange={setRoleFilter}>
<SelectTrigger className="w-32 h-9 dg-input">
<SelectValue />
</SelectTrigger>
<SelectContent>
<SelectItem value="all">全部角色</SelectItem>
<SelectItem value="all">{t('kubernetes.kubernetesnodes.s5bcc10')}</SelectItem>
<SelectItem value="master">Master</SelectItem>
<SelectItem value="worker">Worker</SelectItem>
</SelectContent>
@@ -83,14 +85,14 @@ export function KubernetesNodes() {
return (
<PageShell
variant="list"
title="节点管理"
subtitle={clusterLabel ? `${clusterLabel} · 工作节点状态与资源` : 'Kubernetes 集群工作节点状态与资源'}
title=t('menu.nodeManagement')
subtitle={clusterLabel ? t('kubernetes.kubernetesnodes.s055d95', { clusterLabel: clusterLabel }) : t('kubernetes.kubernetesnodes.s01b441')}
icon={<Server className="h-5 w-5" />}
actions={(
<>
<Select value={selectedCluster} onValueChange={setSelectedCluster}>
<SelectTrigger className="w-48 h-9 dg-input">
<SelectValue placeholder="选择集群" />
<SelectValue placeholder=t('k8s.topology.selectCluster') />
</SelectTrigger>
<SelectContent>
{clusters.map((c) => (
@@ -109,21 +111,21 @@ export function KubernetesNodes() {
<Table>
<TableHeader>
<TableRow className="border-[var(--dg-border)] hover:bg-transparent">
<TableHead className="text-[var(--dg-text-secondary)]">节点名称</TableHead>
<TableHead className="text-[var(--dg-text-secondary)]">{t('k8s.topology.nodeName')}</TableHead>
<TableHead className="text-[var(--dg-text-secondary)]">IP</TableHead>
<TableHead className="text-[var(--dg-text-secondary)]">角色</TableHead>
<TableHead className="text-[var(--dg-text-secondary)]">状态</TableHead>
<TableHead className="text-[var(--dg-text-secondary)]">配置</TableHead>
<TableHead className="text-[var(--dg-text-secondary)]">使用率</TableHead>
<TableHead className="text-[var(--dg-text-secondary)]">{t('pipeline.role')}</TableHead>
<TableHead className="text-[var(--dg-text-secondary)]">{t('common.status')}</TableHead>
<TableHead className="text-[var(--dg-text-secondary)]">{t('common.config')}</TableHead>
<TableHead className="text-[var(--dg-text-secondary)]">{t('server.usage')}</TableHead>
<TableHead className="text-[var(--dg-text-secondary)]">Pods</TableHead>
<TableHead className="text-[var(--dg-text-secondary)]">Kubelet</TableHead>
</TableRow>
</TableHeader>
<TableBody>
{loading ? (
<TableRow><TableCell colSpan={8} className="text-center text-[var(--dg-text-muted)] py-12"><Loader2 className="h-5 w-5 animate-spin mx-auto mb-2" />加载中...</TableCell></TableRow>
<TableRow><TableCell colSpan={8} className="text-center text-[var(--dg-text-muted)] py-12"><Loader2 className="h-5 w-5 animate-spin mx-auto mb-2" />{t('common.loading')}</TableCell></TableRow>
) : filtered.length === 0 ? (
<TableRow><TableCell colSpan={8} className="text-center text-[var(--dg-text-muted)] py-12"><Server className="h-8 w-8 mx-auto mb-2 opacity-50" />{selectedCluster ? '暂无节点数据' : '请选择集群'}</TableCell></TableRow>
<TableRow><TableCell colSpan={8} className="text-center text-[var(--dg-text-muted)] py-12"><Server className="h-8 w-8 mx-auto mb-2 opacity-50" />{selectedCluster ? t('k8s.empty.nodes') : t('kubernetes.kubernetesnodes.sf8c388')}</TableCell></TableRow>
) : (
filtered.map((n) => (
<TableRow key={n.id} className="border-[var(--dg-border)] hover:bg-[var(--dg-bg-tertiary)]/30">
@@ -132,7 +134,7 @@ export function KubernetesNodes() {
<TableCell>{getRoleBadge(n.role)}</TableCell>
<TableCell>{getStatusBadge(n.status)}</TableCell>
<TableCell className="text-sm text-[var(--dg-text-secondary)]">
{n.cpu ? `${n.cpu}核` : '-'} / {n.memory ? `${Math.round(n.memory / 1024)}GB` : '-'}
{n.cpu ? t('kubernetes.kubernetesnodes.s90ecb6', { n.cpu: n.cpu }) : '-'} / {n.memory ? `${Math.round(n.memory / 1024)}GB` : '-'}
</TableCell>
<TableCell>
{(() => {
@@ -26,8 +26,10 @@ import { kubernetesApi } from '@/api';
import { useToast } from '@/hooks/use-toast';
import { DeploymentDetail } from './DeploymentDetail';
import type { JsonData } from '@/types/common';
import { useTranslation } from 'react-i18next';
export function KubernetesWorkloads() {
const { t } = useTranslation();
const { toast } = useToast();
const [clusters, setClusters] = useState<JsonData[]>([]);
const [selectedCluster, setSelectedCluster] = useState('');
@@ -119,10 +121,10 @@ export function KubernetesWorkloads() {
const newReplicas = (dep.replicas || 0) + delta;
if (newReplicas < 0) return;
await kubernetesApi.scaleDeployment(selectedCluster, dep.namespace, dep.name, newReplicas);
toast({ title: '扩缩容成功', description: `${dep.name} → ${newReplicas} 副本` });
toast({ title: t('kubernetes.kubernetesworkloads.s0b3ea1'), description: t('kubernetes.kubernetesworkloads.scf7f1c', { dep.name: dep.name, newReplicas: newReplicas }) });
loadData();
} catch (e) {
toast({ title: '操作失败', description: e?.message || String(e), variant: 'destructive' });
toast({ title: t('common.operationFailed'), description: e?.message || String(e), variant: 'destructive' });
} finally {
setActionLoading((prev) => { const n = { ...prev }; delete n[key]; return n; });
}
@@ -144,13 +146,13 @@ export function KubernetesWorkloads() {
<div className="space-y-6">
<div className="flex items-center justify-between">
<div>
<h1 className="text-2xl font-bold text-[var(--dg-text-primary)]">工作负载</h1>
<p className="text-sm dg-text-muted mt-1">Deployment 与 Pod 运行状态</p>
<h1 className="text-2xl font-bold text-[var(--dg-text-primary)]">{t('menu.workloads')}</h1>
<p className="text-sm dg-text-muted mt-1">{t('kubernetes.kubernetesworkloads.sf90ced')}</p>
</div>
<div className="flex items-center gap-2">
<Select value={selectedCluster} onValueChange={(v) => { setSelectedCluster(v); setSelectedNamespace('all'); }}>
<SelectTrigger className="w-48 h-9 dg-input">
<SelectValue placeholder="选择集群" />
<SelectValue placeholder=t('k8s.topology.selectCluster') />
</SelectTrigger>
<SelectContent className="dg-input">
{clusters.map((c) => (
@@ -160,10 +162,10 @@ export function KubernetesWorkloads() {
</Select>
<Select value={selectedNamespace} onValueChange={setSelectedNamespace}>
<SelectTrigger className="w-40 h-9 dg-input">
<SelectValue placeholder="命名空间" />
<SelectValue placeholder=t('k8s.column.namespace') />
</SelectTrigger>
<SelectContent className="dg-input max-h-[300px]">
<SelectItem value="all">全部命名空间</SelectItem>
<SelectItem value="all">{t('kubernetes.namespace.allNamespaces')}</SelectItem>
{namespaces.map((ns) => (
<SelectItem key={ns} value={ns}>{ns}</SelectItem>
))}
@@ -178,9 +180,9 @@ export function KubernetesWorkloads() {
<div className="grid grid-cols-2 md:grid-cols-4 gap-4">
{[
{ label: 'Deployment', value: deployments.length, icon: <Boxes className="h-5 w-5" />, color: 'text-rose-400' },
{ label: 'Pod 总数', value: pods.length, icon: <Container className="h-5 w-5" />, color: 'dg-text-blue' },
{ label: t('kubernetes.kubernetesworkloads.s83481f'), value: pods.length, icon: <Container className="h-5 w-5" />, color: 'dg-text-blue' },
{ label: 'Running', value: pods.filter((p) => p.status === 'Running').length, icon: <Container className="h-5 w-5" />, color: 'dg-text-green' },
{ label: '异常', value: pods.filter((p) => ['Failed', 'Pending'].includes(p.status)).length, icon: <Container className="h-5 w-5" />, color: 'dg-text-red' },
{ label: t('common.abnormal'), value: pods.filter((p) => ['Failed', 'Pending'].includes(p.status)).length, icon: <Container className="h-5 w-5" />, color: 'dg-text-red' },
].map((s) => (
<Card key={s.label} className="dg-card">
<CardContent className="p-4">
@@ -198,7 +200,7 @@ export function KubernetesWorkloads() {
<div className="relative w-56">
<Search className="absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 dg-text-muted" />
<Input placeholder="搜索..." value={search} onChange={(e) => setSearch(e.target.value)} className="pl-9 h-9 dg-input" />
<Input placeholder=t('kubernetes.kubernetesworkloads.s64e327') value={search} onChange={(e) => setSearch(e.target.value)} className="pl-9 h-9 dg-input" />
</div>
<Tabs value={activeTab} onValueChange={setActiveTab}>
@@ -213,18 +215,18 @@ export function KubernetesWorkloads() {
<Table>
<TableHeader>
<TableRow className="border-[var(--dg-border)] hover:bg-transparent">
<TableHead className="dg-text-secondary">名称</TableHead>
<TableHead className="dg-text-secondary">命名空间</TableHead>
<TableHead className="dg-text-secondary">副本</TableHead>
<TableHead className="dg-text-secondary">镜像</TableHead>
<TableHead className="dg-text-secondary w-[140px]">操作</TableHead>
<TableHead className="dg-text-secondary">{t('common.name')}</TableHead>
<TableHead className="dg-text-secondary">{t('k8s.column.namespace')}</TableHead>
<TableHead className="dg-text-secondary">{t('kubernetes.kubernetesworkloads.s0428b3')}</TableHead>
<TableHead className="dg-text-secondary">{t('k8s.column.image')}</TableHead>
<TableHead className="dg-text-secondary w-[140px]">{t('common.actions')}</TableHead>
</TableRow>
</TableHeader>
<TableBody>
{loading ? (
<TableRow><TableCell colSpan={5} className="text-center dg-text-muted py-12"><Loader2 className="h-5 w-5 animate-spin mx-auto mb-2" />加载中...</TableCell></TableRow>
<TableRow><TableCell colSpan={5} className="text-center dg-text-muted py-12"><Loader2 className="h-5 w-5 animate-spin mx-auto mb-2" />{t('common.loading')}</TableCell></TableRow>
) : filteredDeps.length === 0 ? (
<TableRow><TableCell colSpan={5} className="text-center dg-text-muted py-12"><Boxes className="h-8 w-8 mx-auto mb-2 opacity-50" />暂无 Deployment</TableCell></TableRow>
<TableRow><TableCell colSpan={5} className="text-center dg-text-muted py-12"><Boxes className="h-8 w-8 mx-auto mb-2 opacity-50" />{t('kubernetes.kubernetesworkloads.s5689d3')}</TableCell></TableRow>
) : (
filteredDeps.map((d) => (
<TableRow key={d.id || d.name} className="border-[var(--dg-border)] hover:bg-[var(--dg-bg-hover)] cursor-pointer"
@@ -251,16 +253,16 @@ export function KubernetesWorkloads() {
<TableCell onClick={(e) => e.stopPropagation()}>
<div className="flex items-center gap-0.5">
<Button variant="ghost" size="icon" className="h-7 w-7 dg-text-secondary hover:text-[var(--dg-text-primary)]"
title="减少副本" disabled={(d.replicas || 0) <= 0}
title=t('kubernetes.kubernetesworkloads.sd4db1c') disabled={(d.replicas || 0) <= 0}
onClick={() => handleQuickScale(d, -1)}>
<Minus className="h-3.5 w-3.5" />
</Button>
<Button variant="ghost" size="icon" className="h-7 w-7 dg-text-secondary hover:text-[var(--dg-text-primary)]"
title="增加副本" onClick={() => handleQuickScale(d, 1)}>
title=t('kubernetes.kubernetesworkloads.se80820') onClick={() => handleQuickScale(d, 1)}>
<Plus className="h-3.5 w-3.5" />
</Button>
<Button variant="ghost" size="icon" className="h-7 w-7 dg-text-secondary hover:dg-text-blue"
title="查看详情" onClick={() => setSelectedDeployment({ name: d.name, namespace: d.namespace })}>
title=t('common.viewDetail') onClick={() => setSelectedDeployment({ name: d.name, namespace: d.namespace })}>
<Eye className="h-3.5 w-3.5" />
</Button>
</div>
@@ -280,21 +282,21 @@ export function KubernetesWorkloads() {
<Table>
<TableHeader>
<TableRow className="border-[var(--dg-border)] hover:bg-transparent">
<TableHead className="dg-text-secondary">名称</TableHead>
<TableHead className="dg-text-secondary">命名空间</TableHead>
<TableHead className="dg-text-secondary">状态</TableHead>
<TableHead className="dg-text-secondary">节点</TableHead>
<TableHead className="dg-text-secondary">{t('common.name')}</TableHead>
<TableHead className="dg-text-secondary">{t('k8s.column.namespace')}</TableHead>
<TableHead className="dg-text-secondary">{t('common.status')}</TableHead>
<TableHead className="dg-text-secondary">{t('k8s.tab.nodes')}</TableHead>
<TableHead className="dg-text-secondary">CPU</TableHead>
<TableHead className="dg-text-secondary">内存</TableHead>
<TableHead className="dg-text-secondary">重启</TableHead>
<TableHead className="dg-text-secondary">镜像</TableHead>
<TableHead className="dg-text-secondary">{t('k8s.pods.memory')}</TableHead>
<TableHead className="dg-text-secondary">{t('common.reboot')}</TableHead>
<TableHead className="dg-text-secondary">{t('k8s.column.image')}</TableHead>
</TableRow>
</TableHeader>
<TableBody>
{loading ? (
<TableRow><TableCell colSpan={8} className="text-center dg-text-muted py-12"><Loader2 className="h-5 w-5 animate-spin mx-auto mb-2" />加载中...</TableCell></TableRow>
<TableRow><TableCell colSpan={8} className="text-center dg-text-muted py-12"><Loader2 className="h-5 w-5 animate-spin mx-auto mb-2" />{t('common.loading')}</TableCell></TableRow>
) : filteredPods.length === 0 ? (
<TableRow><TableCell colSpan={8} className="text-center dg-text-muted py-12"><Container className="h-8 w-8 mx-auto mb-2 opacity-50" />暂无 Pod</TableCell></TableRow>
<TableRow><TableCell colSpan={8} className="text-center dg-text-muted py-12"><Container className="h-8 w-8 mx-auto mb-2 opacity-50" />{t('k8s.deploymentDetail.noPod')}</TableCell></TableRow>
) : (
filteredPods.map((p) => (
<TableRow key={p.id} className="border-[var(--dg-border)] hover:bg-[var(--dg-bg-hover)]">
@@ -19,6 +19,7 @@ import { toast } from 'sonner';
import { PageShell } from '@/components/layout/PageShell';
import { ContentPanel } from '@/components/layout/ContentPanel';
import { StatStrip } from '@/components/ui/stat-strip';
import { useTranslation } from 'react-i18next';
interface NamespaceDetail {
name: string;
@@ -39,6 +40,7 @@ const SYSTEM_NAMESPACES = new Set([
]);
export default function NamespaceManagementPage() {
const { t } = useTranslation();
const { clusterCode } = useParams<{ clusterCode: string }>();
const navigate = useNavigate();
const [namespaces, setNamespaces] = useState<NamespaceDetail[]>([]);
@@ -78,7 +80,7 @@ export default function NamespaceManagementPage() {
setCreateOpen(false);
await loadData();
} catch (err) {
toast.error(err?.message || '创建失败');
toast.error(err?.message || t('monitor.quickSetupFailed'));
} finally {
setCreating(false);
}
@@ -92,7 +94,7 @@ export default function NamespaceManagementPage() {
setDeleteTarget(null);
await loadData();
} catch (err) {
toast.error(err?.message || '删除失败');
toast.error(err?.message || t('common.deleteFailed'));
} finally {
setDeleting(false);
}
@@ -111,7 +113,7 @@ export default function NamespaceManagementPage() {
<Input
value={searchQuery}
onChange={(e) => setSearchQuery(e.target.value)}
placeholder="搜索命名空间..."
placeholder=t('kubernetes.namespacemanagementpage.se91247')
className="max-w-xs dg-input"
/>
);
@@ -119,17 +121,17 @@ export default function NamespaceManagementPage() {
return (
<PageShell
variant="list"
title="命名空间管理"
subtitle={`${clusterCode} · 资源配额与生命周期管理`}
title=t('kubernetes.namespacemanagementpage.se935a3')
subtitle={t('kubernetes.namespacemanagementpage.s81e4b3', { clusterCode: clusterCode })}
icon={<Boxes className="h-5 w-5" />}
metrics={!loading ? (
<StatStrip
items={[
{ label: '命名空间', value: namespaces.length, color: 'green' },
{ label: t('k8s.column.namespace'), value: namespaces.length, color: 'green' },
{ label: 'Deployments', value: totalDeploys, color: 'blue' },
{ label: 'Pods', value: totalPods, color: 'purple' },
{ label: 'Services', value: totalSvcs, color: 'cyan' },
{ label: '配额限制', value: quotaCount, color: 'amber' },
{ label: t('kubernetes.namespacemanagementpage.s47c3ae'), value: quotaCount, color: 'amber' },
]}
/>
) : undefined}
@@ -147,15 +149,15 @@ export default function NamespaceManagementPage() {
</DialogTrigger>
<DialogContent>
<DialogHeader>
<DialogTitle>创建命名空间</DialogTitle>
<DialogTitle>{t('kubernetes.namespacemanagementpage.s737f41')}</DialogTitle>
</DialogHeader>
<div className="space-y-4 py-4">
<div className="space-y-2">
<Label>命名空间名称</Label>
<Label>{t('kubernetes.namespace.namespaceName')}</Label>
<Input
value={newName}
onChange={(e) => setNewName(e.target.value)}
placeholder="例如: my-app"
placeholder=t('kubernetes.namespacemanagementpage.scba008')
onKeyDown={(e) => e.key === 'Enter' && handleCreate()}
/>
<p className="text-xs text-[var(--dg-text-muted)]">
@@ -164,7 +166,7 @@ export default function NamespaceManagementPage() {
</div>
</div>
<DialogFooter>
<Button variant="outline" onClick={() => setCreateOpen(false)}>取消</Button>
<Button variant="outline" onClick={() => setCreateOpen(false)}>{t('common.cancel')}</Button>
<Button onClick={handleCreate} disabled={creating || !newName.trim()}>
{creating ? <Loader2 className="h-4 w-4 animate-spin mr-1" /> : null}
创建
@@ -179,15 +181,15 @@ export default function NamespaceManagementPage() {
<Table>
<TableHeader>
<TableRow className="border-[var(--dg-border)] hover:bg-transparent">
<TableHead className="text-[var(--dg-text-secondary)]">名称</TableHead>
<TableHead className="text-[var(--dg-text-secondary)]">状态</TableHead>
<TableHead className="text-[var(--dg-text-secondary)]">年龄</TableHead>
<TableHead className="text-[var(--dg-text-secondary)]">{t('common.name')}</TableHead>
<TableHead className="text-[var(--dg-text-secondary)]">{t('common.status')}</TableHead>
<TableHead className="text-[var(--dg-text-secondary)]">{t('kubernetes.namespacemanagementpage.sa01a99')}</TableHead>
<TableHead className="text-[var(--dg-text-secondary)] text-center">Deploy</TableHead>
<TableHead className="text-[var(--dg-text-secondary)] text-center">Pods</TableHead>
<TableHead className="text-[var(--dg-text-secondary)] text-center">Svc</TableHead>
<TableHead className="text-[var(--dg-text-secondary)] text-center">配额</TableHead>
<TableHead className="text-[var(--dg-text-secondary)]">标签</TableHead>
<TableHead className="text-[var(--dg-text-secondary)] text-center">操作</TableHead>
<TableHead className="text-[var(--dg-text-secondary)] text-center">{t('common.quota')}</TableHead>
<TableHead className="text-[var(--dg-text-secondary)]">{t('common.tag')}</TableHead>
<TableHead className="text-[var(--dg-text-secondary)] text-center">{t('common.actions')}</TableHead>
</TableRow>
</TableHeader>
<TableBody>
@@ -247,13 +249,13 @@ export default function NamespaceManagementPage() {
</TableCell>
<TableCell className="text-center">
{isSystem ? (
<span className="text-xs text-[var(--dg-text-muted)]">系统</span>
<span className="text-xs text-[var(--dg-text-muted)]">{t('common.system3')}</span>
) : (
<Button
variant="ghost" size="icon"
className="h-7 w-7 text-[var(--dg-red)] hover:text-[var(--dg-red)] hover:bg-[var(--dg-red)]/10"
onClick={() => setDeleteTarget(ns.name)}
title="删除命名空间"
title=t('kubernetes.namespace.deleteNamespace')
>
<Trash2 className="h-3.5 w-3.5" />
</Button>
@@ -286,7 +288,7 @@ export default function NamespaceManagementPage() {
</div>
</div>
<DialogFooter>
<Button variant="outline" onClick={() => setDeleteTarget(null)}>取消</Button>
<Button variant="outline" onClick={() => setDeleteTarget(null)}>{t('common.cancel')}</Button>
<Button variant="destructive" onClick={handleDelete} disabled={deleting}>
{deleting ? <Loader2 className="h-4 w-4 animate-spin mr-1" /> : null}
确认删除
@@ -16,19 +16,22 @@ import {
import { kubernetesApi } from '@/api';
import { PageShell } from '@/components/layout/PageShell';
import type { JsonData } from '@/types/common';
import { useTranslation } from 'react-i18next';
import i18n from '@/i18n';
const RESOURCE_LINKS = [
{ type: 'deployments', label: 'Deployments', icon: Boxes, desc: '工作负载副本管理' },
{ type: 'pods', label: 'Pods', icon: Container, desc: '容器实例运行状态' },
{ type: 'cronjobs', label: 'CronJobs', icon: Clock, desc: '定时任务管理' },
{ type: 'services', label: 'Services', icon: Network, desc: '服务发现与负载均衡' },
{ type: 'ingresses', label: 'Ingresses', icon: Network, desc: '外部流量路由规则' },
{ type: 'configmaps', label: 'ConfigMaps', icon: FileText, desc: '配置字典' },
{ type: 'secrets', label: 'Secrets', icon: Shield, desc: '密钥与凭证' },
{ type: 'hpas', label: 'HPAs', icon: Activity, desc: '水平自动伸缩策略' },
{ type: 'deployments', label: 'Deployments', icon: Boxes, desc: i18n.t('kubernetes.namespaceoverviewpage.sb68c63') },
{ type: 'pods', label: 'Pods', icon: Container, desc: i18n.t('kubernetes.namespaceoverviewpage.sfdac25') },
{ type: 'cronjobs', label: 'CronJobs', icon: Clock, desc: i18n.t('kubernetes.namespaceoverviewpage.s9c9fc5') },
{ type: 'services', label: 'Services', icon: Network, desc: i18n.t('kubernetes.namespaceoverviewpage.s3a3f6d') },
{ type: 'ingresses', label: 'Ingresses', icon: Network, desc: i18n.t('kubernetes.namespaceoverviewpage.scc6971') },
{ type: 'configmaps', label: 'ConfigMaps', icon: FileText, desc: i18n.t('kubernetes.namespaceoverviewpage.s0986a6') },
{ type: 'secrets', label: 'Secrets', icon: Shield, desc: i18n.t('kubernetes.namespaceoverviewpage.sb3fb72') },
{ type: 'hpas', label: 'HPAs', icon: Activity, desc: i18n.t('kubernetes.namespaceoverviewpage.sa84da2') },
];
export default function NamespaceOverviewPage() {
const { t } = useTranslation();
const { clusterCode, namespace } = useParams<{ clusterCode: string; namespace: string }>();
const [counts, setCounts] = useState<Record<string, number>>({});
const [loading, setLoading] = useState(false);
@@ -66,11 +69,11 @@ export default function NamespaceOverviewPage() {
return (
<PageShell
variant="default"
title={namespace || '命名空间'}
subtitle={`${clusterCode} · 命名空间概览`}
title={namespace || t('k8s.column.namespace')}
subtitle={t('kubernetes.namespaceoverviewpage.s6d60aa', { clusterCode: clusterCode })}
icon={<Cloud className="h-5 w-5" />}
loading={loading}
loadingLabel="加载资源统计..."
loadingLabel=t('kubernetes.namespaceoverviewpage.sfa525a')
>
<div className="grid grid-cols-2 md:grid-cols-4 gap-4">
{RESOURCE_LINKS.map((r) => (
@@ -25,6 +25,8 @@ import { useToast } from '@/hooks/use-toast';
import { useConfirm } from '@/components/ui/confirm-dialog';
import { PageShell } from '@/components/layout/PageShell';
import { ContentPanel } from '@/components/layout/ContentPanel';
import { useTranslation } from 'react-i18next';
import i18n from '@/i18n';
type ResourceType =
| 'deployments' | 'pods' | 'services' | 'ingresses'
@@ -43,8 +45,8 @@ const BULK_EXPORT_TYPES: ResourceType[] = ['services', 'ingresses', 'configmaps'
const VisualActions = ({ name, opts }: { name: string; opts: { onYaml?: (n: string) => void; onEdit?: (n: string) => void } }) => (
<div className="flex items-center gap-0.5">
<Button variant="ghost" size="sm" className="h-7 px-2 text-xs text-[var(--dg-green)] hover:text-[var(--dg-green)]" title="可视化编辑"
onClick={() => opts.onEdit?.(name)}><Pencil className="h-3.5 w-3.5 mr-1" />编辑</Button>
<Button variant="ghost" size="sm" className="h-7 px-2 text-xs text-[var(--dg-green)] hover:text-[var(--dg-green)]" title=i18n.t('k8s.resource.visualEditor')
onClick={() => opts.onEdit?.(name)}><Pencil className="h-3.5 w-3.5 mr-1" />{i18n.t('common.edit')}</Button>
<Button variant="ghost" size="sm" className="h-7 px-2 text-xs text-[var(--dg-text-secondary)] hover:text-[var(--dg-text-secondary)]" title="YAML"
onClick={() => opts.onYaml?.(name)}><FileCode className="h-3.5 w-3.5 mr-1" />YAML</Button>
</div>
@@ -58,8 +60,8 @@ const RESOURCE_CONFIG: Record<ResourceType, {
renderRow: ( item: any, opts: { clusterCode: string; namespace: string; onDetail?: ( item: any) => void; onYaml?: (name: string) => void; onEdit?: (name: string) => void; onTerminal?: ( item: any) => void; onFileBrowser?: ( item: any) => void; onDeletePod?: ( item: any) => void; onPodDetail?: ( item: any) => void }) => React.ReactNode;
}> = {
deployments: {
title: 'Deployments', subtitle: 'Deployment 工作负载运行状态', icon: Boxes,
columns: ['名称', '命名空间', '副本', '镜像'],
title: 'Deployments', subtitle: i18n.t('kubernetes.namespaceresourcepage.s35c744'), icon: Boxes,
columns: [i18n.t('common.name'), i18n.t('k8s.column.namespace'), i18n.t('kubernetes.namespaceresourcepage.s0428b3'), i18n.t('k8s.column.image')],
renderRow: (d, opts) => (
<TableRow key={d.name} className="border-[var(--dg-border)] hover:bg-[var(--dg-bg-tertiary)]/30 cursor-pointer" onClick={() => opts.onDetail?.(d)}>
<TableCell className="font-medium text-[var(--dg-text-primary)]">{d.name}</TableCell>
@@ -83,8 +85,8 @@ const RESOURCE_CONFIG: Record<ResourceType, {
),
},
pods: {
title: 'Pods', subtitle: 'Pod 实例运行状态', icon: Container,
columns: ['名称', '命名空间', '状态', '节点', 'CPU', '内存', '重启', '镜像', '操作'],
title: 'Pods', subtitle: i18n.t('kubernetes.namespaceresourcepage.s780b7d'), icon: Container,
columns: [i18n.t('common.name'), i18n.t('k8s.column.namespace'), i18n.t('common.status'), i18n.t('k8s.tab.nodes'), 'CPU', i18n.t('k8s.pods.memory'), i18n.t('common.reboot'), i18n.t('k8s.column.image'), i18n.t('common.actions')],
renderRow: (p, opts) => {
const statusMap: Record<string, string> = { Running: 'bg-[var(--dg-green)]/20 text-[var(--dg-green)] border-[var(--dg-green)]/30', Pending: 'bg-[var(--dg-orange)]/20 text-[var(--dg-orange)] border-[var(--dg-orange)]/30', Failed: 'bg-[var(--dg-red)]/20 text-[var(--dg-red)] border-[var(--dg-red)]/30' };
return (
@@ -104,13 +106,13 @@ const RESOURCE_CONFIG: Record<ResourceType, {
<TableCell className="text-xs text-[var(--dg-text-muted)] max-w-[200px] truncate">{p.image || '-'}</TableCell>
<TableCell>
<div className="flex items-center gap-0.5">
<Button variant="ghost" size="sm" className="h-7 w-7 p-0 shrink-0 text-[var(--dg-green)]" title="终端"
<Button variant="ghost" size="sm" className="h-7 w-7 p-0 shrink-0 text-[var(--dg-green)]" title=i18n.t('kubernetes.pod.terminal')
onClick={() => (opts as Record<string, any>).onTerminal?.(p)}><Terminal className="h-3.5 w-3.5" /></Button>
<Button variant="ghost" size="sm" className="h-7 w-7 p-0 shrink-0 text-[var(--dg-orange)]" title="文件"
<Button variant="ghost" size="sm" className="h-7 w-7 p-0 shrink-0 text-[var(--dg-orange)]" title=i18n.t('k8s.pods.action.file')
onClick={() => (opts as Record<string, any>).onFileBrowser?.(p)}><HardDrive className="h-3.5 w-3.5" /></Button>
<Button variant="ghost" size="sm" className="h-7 w-7 p-0 shrink-0 text-[var(--dg-blue)]" title="YAML"
onClick={() => opts.onYaml?.(p.name)}><FileCode className="h-3.5 w-3.5" /></Button>
<Button variant="ghost" size="sm" className="h-7 w-7 p-0 shrink-0 text-[var(--dg-red)] hover:text-[var(--dg-red)]" title="删除"
<Button variant="ghost" size="sm" className="h-7 w-7 p-0 shrink-0 text-[var(--dg-red)] hover:text-[var(--dg-red)]" title=i18n.t('common.delete')
onClick={() => opts.onDeletePod?.(p)}><Trash2 className="h-3.5 w-3.5" /></Button>
</div>
</TableCell>
@@ -119,8 +121,8 @@ const RESOURCE_CONFIG: Record<ResourceType, {
},
},
services: {
title: 'Services', subtitle: 'Service 网络服务', icon: Network,
columns: ['名称', '命名空间', '类型', 'Cluster IP', '端口', '操作'],
title: 'Services', subtitle: i18n.t('kubernetes.namespaceresourcepage.s5e76b6'), icon: Network,
columns: [i18n.t('common.name'), i18n.t('k8s.column.namespace'), i18n.t('common.type'), 'Cluster IP', i18n.t('server.csv.port'), i18n.t('common.actions')],
renderRow: (s, opts) => (
<TableRow key={s.name} className="border-[var(--dg-border)] hover:bg-[var(--dg-bg-tertiary)]/30">
<TableCell className="font-medium text-[var(--dg-text-primary)]">{s.name}</TableCell>
@@ -133,8 +135,8 @@ const RESOURCE_CONFIG: Record<ResourceType, {
),
},
ingresses: {
title: 'Ingresses', subtitle: 'Ingress 路由规则', icon: Network,
columns: ['名称', '命名空间', 'Hosts', 'TLS', '操作'],
title: 'Ingresses', subtitle: i18n.t('kubernetes.namespaceresourcepage.s8d5014'), icon: Network,
columns: [i18n.t('common.name'), i18n.t('k8s.column.namespace'), 'Hosts', 'TLS', i18n.t('common.actions')],
renderRow: (i, opts) => {
const hosts = i.hosts || [];
return (
@@ -149,8 +151,8 @@ const RESOURCE_CONFIG: Record<ResourceType, {
},
},
configmaps: {
title: 'ConfigMaps', subtitle: '配置字典', icon: FileText,
columns: ['名称', '命名空间', '键数量', '操作'],
title: 'ConfigMaps', subtitle: i18n.t('kubernetes.namespaceresourcepage.s0986a6'), icon: FileText,
columns: [i18n.t('common.name'), i18n.t('k8s.column.namespace'), i18n.t('kubernetes.namespaceresourcepage.sbd1fa0'), i18n.t('common.actions')],
renderRow: (c, opts) => (
<TableRow key={c.name} className="border-[var(--dg-border)] hover:bg-[var(--dg-bg-tertiary)]/30">
<TableCell className="font-medium text-[var(--dg-text-primary)]">{c.name}</TableCell>
@@ -161,8 +163,8 @@ const RESOURCE_CONFIG: Record<ResourceType, {
),
},
secrets: {
title: 'Secrets', subtitle: '密钥管理(仅名称与类型)', icon: Shield,
columns: ['名称', '命名空间', '类型', '操作'],
title: 'Secrets', subtitle: i18n.t('kubernetes.namespaceresourcepage.sd1424a'), icon: Shield,
columns: [i18n.t('common.name'), i18n.t('k8s.column.namespace'), i18n.t('common.type'), i18n.t('common.actions')],
renderRow: (s, opts) => (
<TableRow key={s.name} className="border-[var(--dg-border)] hover:bg-[var(--dg-bg-tertiary)]/30">
<TableCell className="font-medium text-[var(--dg-text-primary)]">{s.name}</TableCell>
@@ -173,8 +175,8 @@ const RESOURCE_CONFIG: Record<ResourceType, {
),
},
hpas: {
title: 'HPAs', subtitle: '水平自动伸缩', icon: Activity,
columns: ['名称', '命名空间', '目标', '最小/最大', 'CPU%', 'Mem%'],
title: 'HPAs', subtitle: i18n.t('kubernetes.namespaceresourcepage.s9abc8d'), icon: Activity,
columns: [i18n.t('common.name'), i18n.t('k8s.column.namespace'), i18n.t('common.target'), i18n.t('k8s.hpaCronHpa.col.minMax'), 'CPU%', 'Mem%'],
renderRow: (h, _opts) => (
<TableRow key={h.name} className="border-[var(--dg-border)] hover:bg-[var(--dg-bg-tertiary)]/30">
<TableCell className="font-medium text-[var(--dg-text-primary)]">{h.name}</TableCell>
@@ -187,21 +189,21 @@ const RESOURCE_CONFIG: Record<ResourceType, {
),
},
cronjobs: {
title: 'CronJobs', subtitle: '定时任务', icon: Clock,
columns: ['名称', '命名空间', '调度', '状态', '上次执行'],
title: 'CronJobs', subtitle: i18n.t('menu.cronJobs'), icon: Clock,
columns: [i18n.t('common.name'), i18n.t('k8s.column.namespace'), i18n.t('k8s.workload.scheduling'), i18n.t('common.status'), i18n.t('common.lastRun')],
renderRow: (cj) => (
<TableRow key={cj.name} className="border-[var(--dg-border)] hover:bg-[var(--dg-bg-tertiary)]/30">
<TableCell className="font-medium text-[var(--dg-text-primary)]">{cj.name}</TableCell>
<TableCell><Badge variant="outline" className="border-[var(--dg-border)] text-[var(--dg-text-secondary)]">{cj.namespace}</Badge></TableCell>
<TableCell className="text-sm font-mono text-[var(--dg-text-secondary)]">{cj.schedule || '-'}</TableCell>
<TableCell><Badge className={cj.suspend ? 'bg-[var(--dg-orange)]/20 text-[var(--dg-orange)]' : 'bg-[var(--dg-green)]/20 text-[var(--dg-green)]'}>{cj.suspend ? '已暂停' : '运行中'}</Badge></TableCell>
<TableCell><Badge className={cj.suspend ? 'bg-[var(--dg-orange)]/20 text-[var(--dg-orange)]' : 'bg-[var(--dg-green)]/20 text-[var(--dg-green)]'}>{cj.suspend ? i18n.t('kubernetes.deployment.paused') : i18n.t('common.running')}</Badge></TableCell>
<TableCell className="text-sm text-[var(--dg-text-secondary)]">{cj.last_schedule || '-'}</TableCell>
</TableRow>
),
},
pvcs: {
title: '存储卷声明', subtitle: 'PersistentVolumeClaim', icon: Boxes,
columns: ['名称', '命名空间', '状态', '大小', 'StorageClass', '操作'],
title: i18n.t('kubernetes.namespaceresourcepage.s18c900'), subtitle: 'PersistentVolumeClaim', icon: Boxes,
columns: [i18n.t('common.name'), i18n.t('k8s.column.namespace'), i18n.t('common.status'), i18n.t('deploy.table.size'), 'StorageClass', i18n.t('common.actions')],
renderRow: (p, opts) => (
<TableRow key={p.name} className="border-[var(--dg-border)] hover:bg-[var(--dg-bg-tertiary)]/30">
<TableCell className="font-medium text-[var(--dg-text-primary)]">{p.name}</TableCell>
@@ -214,8 +216,8 @@ const RESOURCE_CONFIG: Record<ResourceType, {
),
},
statefulsets: {
title: 'StatefulSets', subtitle: '有状态应用', icon: Boxes,
columns: ['名称', '命名空间', '副本', '就绪', '镜像'],
title: 'StatefulSets', subtitle: i18n.t('kubernetes.namespaceresourcepage.sbfeb44'), icon: Boxes,
columns: [i18n.t('common.name'), i18n.t('k8s.column.namespace'), i18n.t('kubernetes.namespaceresourcepage.s0428b3'), i18n.t('common.ready'), i18n.t('k8s.column.image')],
renderRow: (s, opts) => (
<TableRow key={s.name} className="border-[var(--dg-border)] hover:bg-[var(--dg-bg-tertiary)]/30 cursor-pointer" onClick={() => opts.onDetail?.(s)}>
<TableCell className="font-medium text-[var(--dg-text-primary)]">{s.name}</TableCell>
@@ -227,8 +229,8 @@ const RESOURCE_CONFIG: Record<ResourceType, {
),
},
daemonsets: {
title: 'DaemonSets', subtitle: '守护进程集', icon: Boxes,
columns: ['名称', '命名空间', '期望', '当前', '就绪', '镜像'],
title: 'DaemonSets', subtitle: i18n.t('kubernetes.namespaceresourcepage.se1c074'), icon: Boxes,
columns: [i18n.t('common.name'), i18n.t('k8s.column.namespace'), i18n.t('monitor.siteProtocol.http.expectedPrefix'), i18n.t('common.current'), i18n.t('common.ready'), i18n.t('k8s.column.image')],
renderRow: (d, opts) => (
<TableRow key={d.name} className="border-[var(--dg-border)] hover:bg-[var(--dg-bg-tertiary)]/30 cursor-pointer" onClick={() => opts.onDetail?.(d)}>
<TableCell className="font-medium text-[var(--dg-text-primary)]">{d.name}</TableCell>
@@ -241,8 +243,8 @@ const RESOURCE_CONFIG: Record<ResourceType, {
),
},
serviceaccounts: {
title: 'ServiceAccounts', subtitle: '服务账号(RBAC 身份标识)', icon: Shield,
columns: ['名称', '命名空间', 'Secret数', '镜像拉取凭证', '创建时间', '操作'],
title: 'ServiceAccounts', subtitle: i18n.t('kubernetes.namespaceresourcepage.s645c9a'), icon: Shield,
columns: [i18n.t('common.name'), i18n.t('k8s.column.namespace'), i18n.t('kubernetes.namespaceresourcepage.sbaf7ed'), i18n.t('kubernetes.namespaceresourcepage.s260c11'), i18n.t('common.createdAt'), i18n.t('common.actions')],
renderRow: (sa, opts) => (
<TableRow key={sa.name} className="border-[var(--dg-border)] hover:bg-[var(--dg-bg-tertiary)]/30">
<TableCell className="font-medium text-[var(--dg-text-primary)]">{sa.name}</TableCell>
@@ -253,15 +255,15 @@ const RESOURCE_CONFIG: Record<ResourceType, {
</TableCell>
<TableCell className="text-xs text-[var(--dg-text-muted)]">{sa.age || '-'}</TableCell>
<TableCell onClick={(e) => e.stopPropagation()}>
<Button variant="ghost" size="icon" className="h-7 w-7 text-[var(--dg-text-secondary)] hover:text-[var(--dg-blue)]" title="查看YAML"
<Button variant="ghost" size="icon" className="h-7 w-7 text-[var(--dg-text-secondary)] hover:text-[var(--dg-blue)]" title=i18n.t('kubernetes.namespaceresourcepage.s4bde08')
onClick={() => opts.onYaml?.(sa.name)}><FileCode className="h-3.5 w-3.5" /></Button>
</TableCell>
</TableRow>
),
},
roles: {
title: 'Roles', subtitle: '命名空间级角色权限(RBAC)', icon: Shield,
columns: ['名称', '命名空间', '规则数', '权限范围', '创建时间', '操作'],
title: 'Roles', subtitle: i18n.t('kubernetes.namespaceresourcepage.s8905a6'), icon: Shield,
columns: [i18n.t('common.name'), i18n.t('k8s.column.namespace'), i18n.t('kubernetes.namespaceresourcepage.secde03'), i18n.t('system.apiKeyScope'), i18n.t('common.createdAt'), i18n.t('common.actions')],
renderRow: (r, opts) => {
const verbs = r.verbs || [];
const resources = r.resources || [];
@@ -281,9 +283,9 @@ const RESOURCE_CONFIG: Record<ResourceType, {
<TableCell className="text-xs text-[var(--dg-text-muted)]">{r.age || '-'}</TableCell>
<TableCell onClick={(e) => e.stopPropagation()}>
<div className="flex items-center gap-0.5">
<Button variant="ghost" size="icon" className="h-7 w-7 text-[var(--dg-text-secondary)] hover:text-[var(--dg-blue)]" title="查看YAML"
<Button variant="ghost" size="icon" className="h-7 w-7 text-[var(--dg-text-secondary)] hover:text-[var(--dg-blue)]" title=i18n.t('kubernetes.namespaceresourcepage.s4bde08')
onClick={() => opts.onYaml?.(r.name)}><FileCode className="h-3.5 w-3.5" /></Button>
<Button variant="ghost" size="icon" className="h-7 w-7 text-[var(--dg-green)] hover:text-[var(--dg-green)]" title="编辑"
<Button variant="ghost" size="icon" className="h-7 w-7 text-[var(--dg-green)] hover:text-[var(--dg-green)]" title=i18n.t('common.edit')
onClick={() => opts.onEdit?.(r.name)}><Pencil className="h-3.5 w-3.5" /></Button>
</div>
</TableCell>
@@ -292,8 +294,8 @@ const RESOURCE_CONFIG: Record<ResourceType, {
},
},
rolebindings: {
title: 'RoleBindings', subtitle: '角色绑定关系(RBAC 授权)', icon: Shield,
columns: ['名称', '命名空间', '角色引用', '绑定主体', '创建时间', '操作'],
title: 'RoleBindings', subtitle: i18n.t('kubernetes.namespaceresourcepage.sca10fe'), icon: Shield,
columns: [i18n.t('common.name'), i18n.t('k8s.column.namespace'), i18n.t('kubernetes.namespaceresourcepage.s227e5e'), i18n.t('kubernetes.namespaceresourcepage.s2667c7'), i18n.t('common.createdAt'), i18n.t('common.actions')],
renderRow: (rb, opts) => {
const subjects = rb.subjects || [];
const subjStr = subjects.length > 3 ? subjects.slice(0, 3).join(', ') + ` +${subjects.length - 3}` : subjects.join(', ');
@@ -312,9 +314,9 @@ const RESOURCE_CONFIG: Record<ResourceType, {
<TableCell className="text-xs text-[var(--dg-text-muted)]">{rb.age || '-'}</TableCell>
<TableCell onClick={(e) => e.stopPropagation()}>
<div className="flex items-center gap-0.5">
<Button variant="ghost" size="icon" className="h-7 w-7 text-[var(--dg-text-secondary)] hover:text-[var(--dg-blue)]" title="查看YAML"
<Button variant="ghost" size="icon" className="h-7 w-7 text-[var(--dg-text-secondary)] hover:text-[var(--dg-blue)]" title=i18n.t('kubernetes.namespaceresourcepage.s4bde08')
onClick={() => opts.onYaml?.(rb.name)}><FileCode className="h-3.5 w-3.5" /></Button>
<Button variant="ghost" size="icon" className="h-7 w-7 text-[var(--dg-green)] hover:text-[var(--dg-green)]" title="编辑"
<Button variant="ghost" size="icon" className="h-7 w-7 text-[var(--dg-green)] hover:text-[var(--dg-green)]" title=i18n.t('common.edit')
onClick={() => opts.onEdit?.(rb.name)}><Pencil className="h-3.5 w-3.5" /></Button>
</div>
</TableCell>
@@ -325,6 +327,7 @@ const RESOURCE_CONFIG: Record<ResourceType, {
};
export default function NamespaceResourcePage() {
const { t } = useTranslation();
const { clusterCode, namespace } = useParams<{ clusterCode: string; namespace: string }>();
const location = useLocation();
const navigate = useNavigate();
@@ -439,26 +442,26 @@ export default function NamespaceResourcePage() {
if (!clusterCode || !namespace) return;
try {
await kubernetesApi.exportNamespaceResources(clusterCode, namespace);
toast({ title: '导出完成', description: `${namespace} 资源 YAML 已开始下载` });
toast({ title: t('common.exportComplete'), description: t('kubernetes.namespaceresourcepage.sadafd4', { namespace: namespace }) });
} catch (e) {
toast({ title: '导出失败', description: (e as Error)?.message || String(e), variant: 'destructive' });
toast({ title: t('common.exportFailed'), description: (e as Error)?.message || String(e), variant: 'destructive' });
}
};
// Pod 删除 // Logan.Li
const handleDeletePod = async (p: any) => {
const ok = await confirm({
title: '删除 Pod',
description: '确认删除 Pod "' + (p.name || '') + '"?操作不可恢复。',
confirmText: '删除',
title: t('kubernetes.pod.deletePod'),
description: t('kubernetes.namespaceresourcepage.sc5bb25') + (p.name || '') + t('kubernetes.namespaceresourcepage.s3ec1f4'),
confirmText: t('common.delete'),
});
if (!ok) return;
try {
await kubernetesApi.deletePod(clusterCode || '', namespace || '', p.name);
toast({ title: 'Pod 已删除' });
toast({ title: t('kubernetes.pod.deleted') });
loadData();
} catch (e) {
toast({ title: '删除失败', description: (e as any)?.message || String(e), variant: 'destructive' });
toast({ title: t('common.deleteFailed'), description: (e as any)?.message || String(e), variant: 'destructive' });
}
};
@@ -467,7 +470,7 @@ export default function NamespaceResourcePage() {
const searchToolbar = (
<div className="relative w-56 flex-1 min-w-[200px] max-w-xs">
<Search className="absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 dg-text-muted" />
<Input placeholder="搜索..." value={search} onChange={(e) => setSearch(e.target.value)} className="pl-9 h-9 dg-input" />
<Input placeholder=t('kubernetes.namespaceresourcepage.s64e327') value={search} onChange={(e) => setSearch(e.target.value)} className="pl-9 h-9 dg-input" />
</div>
);
@@ -482,11 +485,11 @@ export default function NamespaceResourcePage() {
actions={(
<>
<Select value={clusterCode || ''} onValueChange={(v) => navigate(`/kubernetes/${v}/namespace/${namespace || 'default'}/${type}`)}>
<SelectTrigger className="w-48 h-9 dg-input"><SelectValue placeholder="选择集群" /></SelectTrigger>
<SelectTrigger className="w-48 h-9 dg-input"><SelectValue placeholder=t('k8s.topology.selectCluster') /></SelectTrigger>
<SelectContent>{clusters.map((c) => <SelectItem key={c.id} value={c.code || String(c.id)}>{c.name}</SelectItem>)}</SelectContent>
</Select>
<Select value={namespace || ''} onValueChange={(v) => navigate(`/kubernetes/${clusterCode}/namespace/${v}/${type}`)}>
<SelectTrigger className="w-40 h-9 dg-input"><SelectValue placeholder="命名空间" /></SelectTrigger>
<SelectTrigger className="w-40 h-9 dg-input"><SelectValue placeholder=t('k8s.column.namespace') /></SelectTrigger>
<SelectContent className="max-h-[300px]">{namespaces.map((ns) => <SelectItem key={ns} value={ns}>{ns}</SelectItem>)}</SelectContent>
</Select>
<Button variant="outline" size="sm" className="dg-btn-secondary" onClick={loadData} disabled={loading}>
@@ -495,16 +498,16 @@ export default function NamespaceResourcePage() {
</Button>
{BULK_EXPORT_TYPES.includes(type) && (
<>
<Button variant="outline" size="sm" className="dg-btn-secondary text-xs" onClick={handleExportCSV} title="导出CSV">
<Button variant="outline" size="sm" className="dg-btn-secondary text-xs" onClick={handleExportCSV} title=t('kubernetes.namespaceresourcepage.sef28d5')>
<Download className="h-3 w-3 mr-1" />CSV
</Button>
<Button variant="outline" size="sm" className="dg-btn-secondary text-xs" onClick={handleExportJSON} title="导出JSON">
<Button variant="outline" size="sm" className="dg-btn-secondary text-xs" onClick={handleExportJSON} title=t('kubernetes.namespaceresourcepage.se11b48')>
<Download className="h-3 w-3 mr-1" />JSON
</Button>
</>
)}
{EXPORT_YAML_TYPES.includes(type) && (
<Button variant="outline" size="sm" className="dg-btn-secondary text-xs" onClick={handleExportYaml} title="导出命名空间 YAML(tar.gz)">
<Button variant="outline" size="sm" className="dg-btn-secondary text-xs" onClick={handleExportYaml} title=t('kubernetes.namespaceresourcepage.s2f8992')>
<Download className="h-3 w-3 mr-1" />导出YAML
</Button>
)}
@@ -556,7 +559,7 @@ export default function NamespaceResourcePage() {
<TableHeader><TableRow className="border-[var(--dg-border)] hover:bg-transparent">{config.columns.map((col) => <TableHead key={col} className="text-[var(--dg-text-secondary)]">{col}</TableHead>)}</TableRow></TableHeader>
<TableBody>
{loading ? (
<TableRow><TableCell colSpan={config.columns.length} className="text-center text-[var(--dg-text-muted)] py-12"><Loader2 className="h-5 w-5 animate-spin mx-auto mb-2" />加载中...</TableCell></TableRow>
<TableRow><TableCell colSpan={config.columns.length} className="text-center text-[var(--dg-text-muted)] py-12"><Loader2 className="h-5 w-5 animate-spin mx-auto mb-2" />{t('common.loading')}</TableCell></TableRow>
) : filtered.length === 0 ? (
<TableRow><TableCell colSpan={config.columns.length} className="text-center text-[var(--dg-text-muted)] py-12"><config.icon className="h-8 w-8 mx-auto mb-2 opacity-50" />暂无 {config.title}</TableCell></TableRow>
) : (
@@ -598,7 +601,7 @@ export default function NamespaceResourcePage() {
<div className="p-5 space-y-5">
{/* 基本信息 */}
<div>
<h4 className="text-sm font-medium text-[var(--dg-text-primary)] mb-3">基本信息</h4>
<h4 className="text-sm font-medium text-[var(--dg-text-primary)] mb-3">{t('deploy.label.basicInfo')}</h4>
{(() => {
const p = podDetail;
const labels = p.labels || p.metadata?.labels || {};
@@ -609,23 +612,23 @@ export default function NamespaceResourcePage() {
return (
<div className="grid grid-cols-2 gap-x-6 gap-y-2.5">
<div>
<span className="text-xs text-[var(--dg-text-muted)]">名称</span>
<span className="text-xs text-[var(--dg-text-muted)]">{t('common.name')}</span>
<p className="text-sm text-[var(--dg-text-primary)] font-mono">{p.name || '-'}</p>
</div>
<div>
<span className="text-xs text-[var(--dg-text-muted)]">命名空间</span>
<span className="text-xs text-[var(--dg-text-muted)]">{t('k8s.column.namespace')}</span>
<p className="text-sm text-[var(--dg-text-primary)]">{p.namespace || '-'}</p>
</div>
<div>
<span className="text-xs text-[var(--dg-text-muted)]">状态</span>
<span className="text-xs text-[var(--dg-text-muted)]">{t('common.status')}</span>
<div><Badge className={statusMap[st] || 'bg-[var(--dg-text-muted)]/20 text-[var(--dg-text-secondary)]'}>{st}</Badge></div>
</div>
<div>
<span className="text-xs text-[var(--dg-text-muted)]">创建时间</span>
<span className="text-xs text-[var(--dg-text-muted)]">{t('common.createdAt')}</span>
<p className="text-sm text-[var(--dg-text-primary)]">{created ? new Date(created).toLocaleString('zh-CN') : '-'}</p>
</div>
<div>
<span className="text-xs text-[var(--dg-text-muted)]">节点</span>
<span className="text-xs text-[var(--dg-text-muted)]">{t('k8s.tab.nodes')}</span>
<p className="text-sm text-[var(--dg-text-primary)]">{p.node_name || p.node || '-'}</p>
</div>
<div>
@@ -633,7 +636,7 @@ export default function NamespaceResourcePage() {
<p className="text-sm text-[var(--dg-text-primary)] font-mono">{p.ip || p.pod_ip || '-'}</p>
</div>
<div className="col-span-2">
<span className="text-xs text-[var(--dg-text-muted)]">标签</span>
<span className="text-xs text-[var(--dg-text-muted)]">{t('common.tag')}</span>
<div className="flex flex-wrap gap-1 mt-0.5">
{Object.keys(labels).length === 0 ? <span className="text-xs text-[var(--dg-text-muted)]">-</span>
: Object.entries(labels).map(([k, v]) => (
@@ -643,7 +646,7 @@ export default function NamespaceResourcePage() {
</div>
</div>
<div className="col-span-2">
<span className="text-xs text-[var(--dg-text-muted)]">注解</span>
<span className="text-xs text-[var(--dg-text-muted)]">{t('common.annotation')}</span>
<div className="flex flex-wrap gap-1 mt-0.5">
{Object.keys(annotations).length === 0 ? <span className="text-xs text-[var(--dg-text-muted)]">-</span>
: Object.entries(annotations).slice(0, 6).map(([k, v]) => (
@@ -659,19 +662,19 @@ export default function NamespaceResourcePage() {
{/* 现状详情(Conditions) */}
<div>
<h4 className="text-sm font-medium text-[var(--dg-text-primary)] mb-3">现状详情</h4>
<h4 className="text-sm font-medium text-[var(--dg-text-primary)] mb-3">{t('kubernetes.namespaceresourcepage.s1d8d6e')}</h4>
{(() => {
const cond: any[] = podDetail.conditions || podDetail.pod_conditions || [];
if (cond.length === 0) return <p className="text-xs text-[var(--dg-text-muted)] py-2">暂无数据</p>;
if (cond.length === 0) return <p className="text-xs text-[var(--dg-text-muted)] py-2">{t('common.noData')}</p>;
return (
<Table>
<TableHeader>
<TableRow className="border-[var(--dg-border)] hover:bg-transparent">
<TableHead className="text-[var(--dg-text-muted)] text-xs">类型</TableHead>
<TableHead className="text-[var(--dg-text-muted)] text-xs">状态</TableHead>
<TableHead className="text-[var(--dg-text-muted)] text-xs">更新时间</TableHead>
<TableHead className="text-[var(--dg-text-muted)] text-xs">原因</TableHead>
<TableHead className="text-[var(--dg-text-muted)] text-xs">消息</TableHead>
<TableHead className="text-[var(--dg-text-muted)] text-xs">{t('common.type')}</TableHead>
<TableHead className="text-[var(--dg-text-muted)] text-xs">{t('common.status')}</TableHead>
<TableHead className="text-[var(--dg-text-muted)] text-xs">{t('common.updatedAt')}</TableHead>
<TableHead className="text-[var(--dg-text-muted)] text-xs">{t('kubernetes.event.eventReason')}</TableHead>
<TableHead className="text-[var(--dg-text-muted)] text-xs">{t('kubernetes.event.eventMessage')}</TableHead>
</TableRow>
</TableHeader>
<TableBody>
@@ -702,7 +705,7 @@ export default function NamespaceResourcePage() {
</div>
</div>
<div className="flex justify-end px-5 py-3 border-t border-[var(--dg-border)]">
<Button variant="outline" className="border-[var(--dg-border)] text-[var(--dg-text-secondary)]" onClick={() => setPodDetail(null)}>关闭</Button>
<Button variant="outline" className="border-[var(--dg-border)] text-[var(--dg-text-secondary)]" onClick={() => setPodDetail(null)}>{t('common.close')}</Button>
</div>
</div>
</div>
@@ -22,8 +22,10 @@ import {
import { kubernetesApi } from '@/api';
import { PageShell } from '@/components/layout/PageShell';
import { useTranslation } from 'react-i18next';
export default function NodeDetailPage() {
const { t } = useTranslation();
const { clusterCode, nodeName } = useParams<{ clusterCode: string; nodeName: string }>();
const navigate = useNavigate();
const [data, setData] = useState<any>(null);
@@ -95,11 +97,11 @@ export default function NodeDetailPage() {
return (
<PageShell
variant="default"
title={nodeName || '节点详情'}
title={nodeName || t('kubernetes.nodedetailpage.sb88b98')}
subtitle={nodeSubtitle || clusterCode}
icon={<Server className="h-5 w-5" />}
loading={loading && !data}
loadingLabel="加载节点详情..."
loadingLabel=t('kubernetes.nodedetailpage.sfdff61')
actions={(
<>
<Button variant="outline" size="sm" className="dg-btn-secondary" onClick={() => navigate(-1)}>
@@ -143,7 +145,7 @@ export default function NodeDetailPage() {
</h2>
<div className="space-y-2 text-xs">
<div className="flex items-center justify-between py-1.5 border-b border-[var(--dg-border)]/50">
<span className="dg-text-muted">容器运行时</span>
<span className="dg-text-muted">{t('kubernetes.node.containerRuntime')}</span>
<span className="text-[var(--dg-text-secondary)] font-mono">{data.container_runtime || '-'}</span>
</div>
<div className="flex items-center justify-between py-1.5 border-b border-[var(--dg-border)]/50">
@@ -151,19 +153,19 @@ export default function NodeDetailPage() {
<span className="text-[var(--dg-text-secondary)] font-mono">{data.kubelet_version || '-'}</span>
</div>
<div className="flex items-center justify-between py-1.5 border-b border-[var(--dg-border)]/50">
<span className="dg-text-muted">操作系统</span>
<span className="dg-text-muted">{t('server.csv.os')}</span>
<span className="text-[var(--dg-text-secondary)]">{data.os_image || '-'}</span>
</div>
<div className="flex items-center justify-between py-1.5 border-b border-[var(--dg-border)]/50">
<span className="dg-text-muted">内核版本</span>
<span className="dg-text-muted">{t('monitor.systemInfo.kernel')}</span>
<span className="text-[var(--dg-text-secondary)] font-mono">{data.kernel_version || '-'}</span>
</div>
<div className="flex items-center justify-between py-1.5 border-b border-[var(--dg-border)]/50">
<span className="dg-text-muted">架构</span>
<span className="dg-text-muted">{t('agent.agentArch')}</span>
<span className="text-[var(--dg-text-secondary)] font-mono">{data.architecture || '-'}</span>
</div>
<div className="flex items-center justify-between py-1.5 border-b border-[var(--dg-border)]/50">
<span className="dg-text-muted">创建时间</span>
<span className="dg-text-muted">{t('common.createdAt')}</span>
<span className="text-[var(--dg-text-secondary)]">{data.creation_time ? new Date(data.creation_time).toLocaleString('zh-CN') : '-'}</span>
</div>
<div className="flex items-center justify-between py-1.5">
@@ -183,9 +185,9 @@ export default function NodeDetailPage() {
<div className="space-y-4 mt-4">
{/* CPU allocation (requested vs allocatable) */}
<ResourceBar
label="CPU 已分配"
used={`${(data.cpu_request_m / 1000).toFixed(2)} 核`}
total={`${data.cpu_allocatable} 核`}
label=t('kubernetes.nodedetailpage.s7c3900')
used={t('kubernetes.nodedetailpage.s8c635b', { (data.cpu_request_m / 1000).toFixed(2): (data.cpu_request_m / 1000).toFixed(2) })}
total={t('kubernetes.nodedetailpage.s3523f6', { data.cpu_allocatable: data.cpu_allocatable })}
unit=""
pct={data.cpu_alloc_pct}
color="dg-text-green"
@@ -193,9 +195,9 @@ export default function NodeDetailPage() {
{/* CPU real usage (from metrics) */}
{data.cpu_usage_m && (
<ResourceBar
label="CPU 实时使用"
label=t('kubernetes.nodedetailpage.s1ce996')
used={data.cpu_usage_m}
total={`${data.cpu_capacity} 核`}
total={t('kubernetes.nodedetailpage.s2d6586', { data.cpu_capacity: data.cpu_capacity })}
unit=""
pct={(parseFloat(data.cpu_usage_m.replace('m', '')) / (data.cpu_capacity * 1000)) * 100}
color="dg-text-blue"
@@ -203,7 +205,7 @@ export default function NodeDetailPage() {
)}
{/* Memory allocation */}
<ResourceBar
label="内存已分配"
label=t('kubernetes.nodedetailpage.sccf1cf')
used={`${data.mem_request_mi} Mi`}
total={`${data.mem_allocatable_mb} Mi`}
unit=""
@@ -213,7 +215,7 @@ export default function NodeDetailPage() {
{/* Memory real usage */}
{data.mem_usage_mi && (
<ResourceBar
label="内存实时使用"
label=t('kubernetes.nodedetailpage.s841b8a')
used={data.mem_usage_mi}
total={`${data.mem_capacity_mb} Mi`}
unit=""
@@ -223,7 +225,7 @@ export default function NodeDetailPage() {
)}
{/* Pod allocation */}
<ResourceBar
label="Pod 数量"
label=t('kubernetes.nodedetailpage.s55edf2')
used={`${data.pod_count}`}
total={`${data.pod_allocatable}`}
unit=""
@@ -234,15 +236,15 @@ export default function NodeDetailPage() {
{/* Capacity vs Allocatable raw */}
<div className="mt-4 pt-3 border-t border-[var(--dg-border)]/50 space-y-1 text-[11px] dg-text-muted">
<div className="flex justify-between">
<span>CPU 容量 / 可分配</span>
<span>{t('kubernetes.nodedetailpage.s8babfd')}</span>
<span className="font-mono">{data.cpu_capacity} / {data.cpu_allocatable} 核</span>
</div>
<div className="flex justify-between">
<span>内存容量 / 可分配</span>
<span>{t('kubernetes.nodedetailpage.s503852')}</span>
<span className="font-mono">{data.mem_capacity_mb} / {data.mem_allocatable_mb} Mi</span>
</div>
<div className="flex justify-between">
<span>Pod 容量 / 可分配</span>
<span>{t('kubernetes.nodedetailpage.s674f45')}</span>
<span className="font-mono">{data.pod_capacity} / {data.pod_allocatable}</span>
</div>
</div>
@@ -259,7 +261,7 @@ export default function NodeDetailPage() {
<CheckCircle2 className="h-4 w-4 dg-text-blue" />节点条件
</h2>
{(!data.conditions || data.conditions.length === 0) ? (
<p className="text-xs dg-text-muted py-4 text-center">无条件数据</p>
<p className="text-xs dg-text-muted py-4 text-center">{t('kubernetes.nodedetailpage.s0f03f9')}</p>
) : (
<div className="space-y-2">
{data.conditions.map(( cond: any, i: number) => (
@@ -286,7 +288,7 @@ export default function NodeDetailPage() {
<AlertTriangle className="h-4 w-4 dg-text-yellow" />污点 (Taints)
</h2>
{(!data.taints || data.taints.length === 0) ? (
<p className="text-xs dg-text-muted py-4 text-center">无污点</p>
<p className="text-xs dg-text-muted py-4 text-center">{t('kubernetes.node.noTaint')}</p>
) : (
<div className="space-y-2">
{data.taints.map(( t: any, i: number) => (
@@ -333,18 +335,18 @@ export default function NodeDetailPage() {
</h2>
</div>
{(!data.pods || data.pods.length === 0) ? (
<p className="text-xs dg-text-muted py-8 text-center">该节点上暂无 Pod</p>
<p className="text-xs dg-text-muted py-8 text-center">{t('kubernetes.nodedetailpage.s86d276')}</p>
) : (
<Table>
<TableHeader>
<TableRow className="border-[var(--dg-border)] hover:bg-transparent">
<TableHead className="dg-text-secondary">命名空间</TableHead>
<TableHead className="dg-text-secondary">名称</TableHead>
<TableHead className="dg-text-secondary">状态</TableHead>
<TableHead className="dg-text-secondary">{t('k8s.column.namespace')}</TableHead>
<TableHead className="dg-text-secondary">{t('common.name')}</TableHead>
<TableHead className="dg-text-secondary">{t('common.status')}</TableHead>
<TableHead className="dg-text-secondary">IP</TableHead>
<TableHead className="dg-text-secondary">CPU 请求</TableHead>
<TableHead className="dg-text-secondary">内存请求</TableHead>
<TableHead className="dg-text-secondary">重启次数</TableHead>
<TableHead className="dg-text-secondary">{t('kubernetes.node.cpuRequests')}</TableHead>
<TableHead className="dg-text-secondary">{t('kubernetes.node.memoryRequests')}</TableHead>
<TableHead className="dg-text-secondary">{t('k8s.column.restartCount')}</TableHead>
</TableRow>
</TableHeader>
<TableBody>
@@ -22,6 +22,7 @@ import {
import { cn } from '@/lib/utils';
import { kubernetesApi } from '@/api';
import { useToast } from '@/hooks/use-toast';
import { useTranslation } from 'react-i18next';
export interface PodExecTerminalProps {
open: boolean;
@@ -49,6 +50,7 @@ export function PodExecTerminal({
containers = [],
initialContainer,
}: PodExecTerminalProps) {
const { t } = useTranslation();
const { toast } = useToast();
const containerRef = useRef<HTMLDivElement>(null);
const termRef = useRef<XTerm | null>(null);
@@ -92,7 +94,7 @@ export function PodExecTerminal({
setConnState('connecting');
term.clear();
term.writeln(`\x1b[36m[正在连接 ${podName}${container ? '/' + container : ''} shell=${shell} ...]\x1b[0m`);
term.writeln(t('kubernetes.podexecterminal.s2f4703', { podName: podName, container ? '/' + container : '': container ? '/' + container : '', shell: shell }));
const wsUrl = kubernetesApi.buildPodExecWsUrl(clusterId, namespace, podName, container || undefined, shell);
@@ -116,9 +118,9 @@ export function PodExecTerminal({
if (msg.status === 0 && typeof msg.data === 'string') {
term.write(msg.data);
} else if (msg.status === 2 || msg.error) {
const errMsg = msg.data || msg.message || msg.error || '执行错误';
const errMsg = msg.data || msg.message || msg.error || t('kubernetes.podexecterminal.s05f6e9');
if (errMsg.includes('not found') && shell === 'bash') {
term.writeln('\r\n\x1b[33m⚠ bash 不可用,请切换 /bin/sh 后重连。\x1b[0m');
term.writeln(t('kubernetes.podexecterminal.s14481b'));
errorShownRef.current = true;
return;
}
@@ -132,14 +134,14 @@ export function PodExecTerminal({
ws.onclose = (_ev) => {
setConnState((s) => (s === 'error' ? s : 'closed'));
if (!errorShownRef.current) {
term.write('\r\n\x1b[33m[连接已关闭]\x1b[0m\r\n');
term.write(t('kubernetes.podexecterminal.s123d94'));
}
};
ws.onerror = (ev) => {
console.error('[PodExec:connect] WS error event fired, readyState=', ws.readyState, 'type=', ev.type);
setConnState('error');
term.write('\r\n\x1b[31m[连接发生错误]\x1b[0m\r\n');
term.write(t('kubernetes.podexecterminal.sc81077'));
};
}, [clusterId, namespace, podName, container, shell]);
@@ -266,10 +268,10 @@ export function PodExecTerminal({
const statusColor = connState === 'connected' ? 'bg-emerald-400'
: connState === 'error' ? 'bg-red-400'
: connState === 'closed' ? 'bg-[var(--dg-bg-active)]' : 'bg-amber-400';
const statusText = connState === 'connected' ? '已连接'
: connState === 'connecting' ? '连接中'
: connState === 'error' ? '连接错误'
: connState === 'closed' ? '已断开' : '空闲';
const statusText = connState === 'connected' ? t('common.connected')
: connState === 'connecting' ? t('common.connecting')
: connState === 'error' ? t('kubernetes.podexecterminal.sd52359')
: connState === 'closed' ? t('common.disconnected') : t('common.idle');
const handleTerminalClick = useCallback(() => {
try { termRef.current?.focus(); } catch { /* noop */ }
@@ -289,7 +291,7 @@ export function PodExecTerminal({
style={fullscreen ? { maxWidth: '100vw', width: '100vw', height: '100vh' } : { maxWidth: '960px', width: '92vw' }}
>
<DialogTitle className="sr-only">exec — {podName}</DialogTitle>
<DialogDescription className="sr-only">进入 Pod 容器执行命令</DialogDescription>
<DialogDescription className="sr-only">{t('kubernetes.podexecterminal.s1a62d4')}</DialogDescription>
{/* 工具栏 */}
<div className="flex items-center justify-between gap-2 px-4 py-2 border-b border-[var(--dg-border)] flex-wrap">
@@ -305,7 +307,7 @@ export function PodExecTerminal({
<Select value={container} onValueChange={setContainer}>
<SelectTrigger className="h-8 w-[150px] text-xs bg-[var(--dg-bg-hover)] border-[var(--dg-border)]">
<Box className="h-3 w-3 mr-1 text-[var(--dg-text-muted)]" />
<SelectValue placeholder="容器" />
<SelectValue placeholder=t('k8s.pods.containers') />
</SelectTrigger>
<SelectContent>{containers.map((c) => <SelectItem key={c} value={c}>{c}</SelectItem>)}</SelectContent>
</Select>
@@ -317,13 +319,13 @@ export function PodExecTerminal({
<SelectContent>{SHELLS.map(s => <SelectItem key={s.value} value={s.value}>{s.label}</SelectItem>)}</SelectContent>
</Select>
<Button variant="ghost" size="sm" className="h-8 px-2 text-[var(--dg-text-secondary)] hover:text-[var(--dg-text-primary)]"
onClick={() => { connect(); toast({ title: '正在重连…' }); }} title="重连">
onClick={() => { connect(); toast({ title: t('kubernetes.podexecterminal.sad127c') }); }} title=t('kubernetes.podexecterminal.s114d0e')>
<RotateCw className="h-3.5 w-3.5" />
</Button>
<button onClick={() => setFullscreen(!fullscreen)} className="p-1.5 rounded hover:bg-[var(--dg-bg-hover)] text-[var(--dg-text-secondary)]" title={fullscreen ? '退出全屏' : '全屏'}>
<button onClick={() => setFullscreen(!fullscreen)} className="p-1.5 rounded hover:bg-[var(--dg-bg-hover)] text-[var(--dg-text-secondary)]" title={fullscreen ? t('common.exitFullscreen') : t('common.fullscreen')}>
{fullscreen ? <Minimize2 className="h-4 w-4" /> : <Maximize2 className="h-4 w-4" />}
</button>
<button onClick={() => onOpenChange(false)} className="p-1.5 rounded hover:bg-[var(--dg-bg-hover)] text-[var(--dg-text-secondary)]" title="关闭">
<button onClick={() => onOpenChange(false)} className="p-1.5 rounded hover:bg-[var(--dg-bg-hover)] text-[var(--dg-text-secondary)]" title=t('common.close')>
<X className="h-4 w-4" />
</button>
</div>
@@ -18,6 +18,7 @@ import {
HardDrive,
} from 'lucide-react';
import type { JsonData } from '@/types/common';
import { useTranslation } from 'react-i18next';
export interface PodFileBrowserProps {
@@ -40,6 +41,7 @@ interface FileEntry {
export function PodFileBrowser({
open, onOpenChange, clusterCode, namespace, podName, containers = [], initialContainer,
}: PodFileBrowserProps) {
const { t } = useTranslation();
const [container, setContainer] = useState(initialContainer || containers[0] || '');
const [currentPath, setCurrentPath] = useState('/');
const [entries, setEntries] = useState<FileEntry[]>([]);
@@ -67,7 +69,7 @@ export function PodFileBrowser({
setEntries(list);
setCurrentPath(path);
} catch (e) {
setError((e as JsonData).message || '加载文件列表失败');
setError((e as JsonData).message || t('kubernetes.podfilebrowser.s78d4a7'));
setEntries([]);
} finally {
setLoading(false);
@@ -117,7 +119,7 @@ export function PodFileBrowser({
const text = await kubernetesApi.readPodFileText(clusterCode, namespace, podName, filePath, container || undefined);
setPreview({ file: fileName, content: text });
} catch (e) {
setPreview({ file: fileName, content: `读取失败: ${(e as JsonData).message}` });
setPreview({ file: fileName, content: t('kubernetes.podfilebrowser.s888006', { (e as JsonData).message: (e as JsonData).message }) });
}
};
@@ -135,7 +137,7 @@ export function PodFileBrowser({
await kubernetesApi.uploadPodFile(clusterCode, namespace, podName, currentPath, file, container || undefined);
loadFiles(currentPath);
} catch (err) {
setError(`上传失败: ${(err as JsonData).message}`);
setError(t('kubernetes.podfilebrowser.s560770', { (err as JsonData).message: (err as JsonData).message }));
} finally {
setUploading(false);
if (fileInputRef.current) fileInputRef.current.value = '';
@@ -225,7 +227,7 @@ export function PodFileBrowser({
{loading ? (
<div className="flex items-center justify-center h-32"><Loader2 className="h-5 w-5 animate-spin dg-text-muted" /></div>
) : entries.length === 0 ? (
<p className="text-xs dg-text-muted p-4 text-center">空目录</p>
<p className="text-xs dg-text-muted p-4 text-center">{t('kubernetes.workload.emptyDir')}</p>
) : (
<div className="space-y-0.5">
{entries.sort((a, b) => (a.isDir === b.isDir ? a.name.localeCompare(b.name) : a.isDir ? -1 : 1)).map((entry) => (
@@ -249,7 +251,7 @@ export function PodFileBrowser({
<Button
variant="ghost" size="icon" className="h-5 w-5 opacity-0 group-hover:opacity-100 dg-text-secondary hover:dg-text-green shrink-0"
onClick={(e) => { e.stopPropagation(); handleDownload(entry.name); }}
title="下载"
title=t('common.download')
>
<Download className="h-3 w-3" />
</Button>
@@ -271,7 +273,7 @@ export function PodFileBrowser({
</div>
<div className="flex-1 overflow-auto p-3">
<pre className="text-xs text-[var(--dg-text-secondary)] font-mono whitespace-pre-wrap break-all bg-[var(--dg-bg-primary)] rounded p-3">
{preview.content || '(空文件)'}
{preview.content || t('kubernetes.podfilebrowser.sf42649')}
</pre>
</div>
</div>
@@ -22,6 +22,8 @@ import { cn } from '@/lib/utils';
import { kubernetesApi } from '@/api';
import { useToast } from '@/hooks/use-toast';
import type { JsonData } from '@/types/common';
import { useTranslation } from 'react-i18next';
import i18n from '@/i18n';
/**
* 增强版 Pod 日志查看器 — 增强 DeploymentDetail 的日志体验
@@ -51,10 +53,10 @@ interface PodLogsViewerProps {
}
const TAIL_OPTIONS = [
{ value: '100', label: '最近 100 行' },
{ value: '500', label: '最近 500 行' },
{ value: '1000', label: '最近 1000 行' },
{ value: '0', label: '全部' },
{ value: '100', label: i18n.t('kubernetes.podlogsviewer.s58b02a') },
{ value: '500', label: i18n.t('kubernetes.podlogsviewer.s9a0368') },
{ value: '1000', label: i18n.t('kubernetes.podlogsviewer.sf89a33') },
{ value: '0', label: i18n.t('common.all') },
];
// 环形缓冲大小(借鉴 opsx-agent)
@@ -74,6 +76,7 @@ export function PodLogsViewer({
containers = [],
initialContainer,
}: PodLogsViewerProps) {
const { t } = useTranslation();
const { toast } = useToast();
const [fullscreen, setFullscreen] = useState(false);
@@ -164,8 +167,8 @@ export function PodLogsViewer({
const arr = typeof raw === 'string' ? raw.split('\n') : (Array.isArray(raw) ? raw : String(raw).split('\n'));
appendLines(arr);
} catch (e) {
appendLines([`\x1b[31m[获取日志失败: ${e?.message || String(e)}]\x1b[0m`]);
toast({ title: '获取日志失败', description: e?.message || String(e), variant: 'destructive' });
appendLines([t('kubernetes.podlogsviewer.s69828a', { e?.message || String(e): e?.message || String(e) })]);
toast({ title: t('kubernetes.podlogsviewer.sc93f33'), description: e?.message || String(e), variant: 'destructive' });
} finally {
setLoading(false);
}
@@ -225,12 +228,12 @@ export function PodLogsViewer({
}
}
flush(); // 收尾
appendLines(['\x1b[33m— 流式结束 —\x1b[0m']);
appendLines([t('kubernetes.podlogsviewer.s4f0e17')]);
} catch (e) {
if (e?.name === 'AbortError') {
appendLines(['\x1b[33m— 已停止 —\x1b[0m']);
appendLines([t('kubernetes.podlogsviewer.s1ca901')]);
} else {
appendLines([`\x1b[31m[流式连接中断: ${e?.message || String(e)}]\x1b[0m`]);
appendLines([t('kubernetes.podlogsviewer.s11530d', { e?.message || String(e): e?.message || String(e) })]);
}
} finally {
setStreaming(false);
@@ -275,7 +278,7 @@ export function PodLogsViewer({
a.download = filename;
a.click();
URL.revokeObjectURL(a.href);
toast({ title: '已导出', description: filename });
toast({ title: t('kubernetes.podlogsviewer.s5c51c3'), description: filename });
}, [podName, container, previous, toast]);
// 关键字过滤
@@ -330,7 +333,7 @@ export function PodLogsViewer({
style={fullscreen ? { maxWidth: '100vw', width: '100vw', height: '100vh' } : { maxWidth: '1100px', width: '94vw' }}
>
<DialogTitle className="sr-only">日志 — {podName}</DialogTitle>
<DialogDescription className="sr-only">Pod 容器日志查看</DialogDescription>
<DialogDescription className="sr-only">{t('kubernetes.podlogsviewer.s24ae3a')}</DialogDescription>
{/* 头部工具栏 */}
<div className="flex items-center justify-between gap-2 px-4 py-2 border-b border-[var(--dg-border)] flex-wrap">
@@ -343,8 +346,8 @@ export function PodLogsViewer({
<span className="text-[var(--dg-text-primary)] font-medium truncate">日志 — {podName}</span>
{loading && <Loader2 className="h-3 w-3 animate-spin text-[var(--dg-text-muted)]" />}
<span className="text-xs text-[var(--dg-text-muted)]">
{streaming ? (paused ? '已暂停' : '实时跟踪') : '已停止'} · {matchedCount}{keyword ? `/${lineCount}` : ''} 行
{lineCount >= RING_BUFFER_MAX && ' (缓冲已满)'}
{streaming ? (paused ? t('kubernetes.deployment.paused') : t('kubernetes.podlogsviewer.sd9c71f')) : t('common.stopped')} · {matchedCount}{keyword ? `/${lineCount}` : ''} 行
{lineCount >= RING_BUFFER_MAX && t('kubernetes.podlogsviewer.sf3280b')}
</span>
</div>
@@ -352,14 +355,14 @@ export function PodLogsViewer({
<button
onClick={() => setFullscreen(!fullscreen)}
className="p-1.5 rounded hover:bg-[var(--dg-bg-hover)] text-[var(--dg-text-secondary)]"
title={fullscreen ? '退出全屏' : '全屏'}
title={fullscreen ? t('common.exitFullscreen') : t('common.fullscreen')}
>
{fullscreen ? <Minimize2 className="h-4 w-4" /> : <Maximize2 className="h-4 w-4" />}
</button>
<button
onClick={handleClose}
className="p-1.5 rounded hover:bg-[var(--dg-bg-hover)] text-[var(--dg-text-secondary)]"
title="关闭"
title=t('common.close')
>
<X className="h-4 w-4" />
</button>
@@ -373,7 +376,7 @@ export function PodLogsViewer({
<Select value={container} onValueChange={setContainer}>
<SelectTrigger className="h-8 w-[150px] text-xs bg-[var(--dg-bg-hover)] border-[var(--dg-border)]">
<Box className="h-3 w-3 mr-1 text-[var(--dg-text-muted)]" />
<SelectValue placeholder="容器" />
<SelectValue placeholder=t('k8s.pods.containers') />
</SelectTrigger>
<SelectContent>
{containers.map((c) => (
@@ -401,7 +404,7 @@ export function PodLogsViewer({
size="sm"
className={cn('h-8 text-xs', previous ? 'bg-amber-600 hover:bg-amber-700' : 'border-[var(--dg-border)] text-[var(--dg-text-secondary)]')}
onClick={() => setPrevious(!previous)}
title="查看上一次(崩溃)容器的日志"
title=t('kubernetes.podlogsviewer.s76a2e6')
>
<History className="h-3.5 w-3.5 mr-1" />
previous
@@ -418,7 +421,7 @@ export function PodLogsViewer({
setSinceTime(v ? new Date(v).toISOString() : '');
}}
className="h-8 w-[170px] text-xs bg-[var(--dg-bg-hover)] border-[var(--dg-border)] text-[var(--dg-text-primary)]"
title="起始时间(sinceTime)"
title=t('kubernetes.podlogsviewer.s127892')
/>
</div>
@@ -430,7 +433,7 @@ export function PodLogsViewer({
<Input
value={keyword}
onChange={(e) => setKeyword(e.target.value)}
placeholder="关键字过滤…"
placeholder=t('kubernetes.podlogsviewer.s7558f1')
className="h-8 w-[160px] pl-7 text-xs bg-[var(--dg-bg-hover)] border-[var(--dg-border)] text-[var(--dg-text-primary)]"
/>
</div>
@@ -440,7 +443,7 @@ export function PodLogsViewer({
variant="outline" size="sm"
className="h-8 text-xs border-[var(--dg-border)] text-[var(--dg-text-secondary)]"
onClick={handleDownload}
title="导出当前日志"
title=t('kubernetes.podlogsviewer.s1a023d')
disabled={filteredLines.length === 0}
>
<Download className="h-3.5 w-3.5 mr-1" />导出
@@ -452,7 +455,7 @@ export function PodLogsViewer({
className="h-8 text-xs border-[var(--dg-border)] text-[var(--dg-text-secondary)]"
onClick={fetchLogs}
disabled={loading}
title="重新拉取"
title=t('kubernetes.podlogsviewer.s930b4e')
>
<RefreshCw className={cn('h-3.5 w-3.5 mr-1', loading && 'animate-spin')} />刷新
</Button>
@@ -464,7 +467,7 @@ export function PodLogsViewer({
className="h-8 text-xs bg-emerald-600 hover:bg-emerald-700"
onClick={startStream}
disabled={loading}
title="实时跟踪(tail -f)"
title=t('kubernetes.podlogsviewer.s0d519c')
>
<Play className="h-3.5 w-3.5 mr-1" />实时
</Button>
@@ -474,16 +477,16 @@ export function PodLogsViewer({
variant="outline" size="sm"
className={cn('h-8 text-xs', paused ? 'border-emerald-500 dg-text-green' : 'border-amber-500 dg-text-yellow')}
onClick={() => setPaused(!paused)}
title={paused ? '继续' : '暂停'}
title={paused ? t('common.continue') : t('common.pause')}
>
{paused ? <Play className="h-3.5 w-3.5 mr-1" /> : <Pause className="h-3.5 w-3.5 mr-1" />}
{paused ? '继续' : '暂停'}
{paused ? t('common.continue') : t('common.pause')}
</Button>
<Button
variant="outline" size="sm"
className="h-8 text-xs border-red-500 dg-text-red"
onClick={stopStream}
title="停止"
title=t('common.stop')
>
<Pause className="h-3.5 w-3.5 mr-1" />停止
</Button>
@@ -510,7 +513,7 @@ export function PodLogsViewer({
{lineCount === 0 && !loading && (
<div className="flex flex-col items-center justify-center h-full text-[var(--dg-text-muted)]">
<AlertCircle className="h-8 w-8 mb-2 opacity-50" />
<span>暂无日志</span>
<span>{t('pipeline.noLog')}</span>
</div>
)}
{loading && lineCount === 0 && (
@@ -542,7 +545,7 @@ export function PodLogsViewer({
}
}}
>
<Maximize2 className="h-3 w-3" />{autoScroll ? '跟随底部' : '已暂停跟随'}
<Maximize2 className="h-3 w-3" />{autoScroll ? t('kubernetes.podlogsviewer.sd7eb1e') : t('kubernetes.podlogsviewer.s130db3')}
</button>
</div>
</DialogContent>
@@ -14,8 +14,10 @@ import { PageShell } from '@/components/layout/PageShell';
import { ContentPanel } from '@/components/layout/ContentPanel';
import { StatStrip } from '@/components/ui/stat-strip';
import type { JsonData } from '@/types/common';
import { useTranslation } from 'react-i18next';
export default function PodMetricsPage() {
const { t } = useTranslation();
const { clusterCode } = useParams<{ clusterCode: string }>();
const navigate = useNavigate();
const [loading, setLoading] = useState(false);
@@ -85,15 +87,15 @@ export default function PodMetricsPage() {
return (
<PageShell
variant="list"
title="Pod 资源用量"
subtitle={clusterName ? `${clusterName} · 容器 CPU/内存实时指标` : '容器 CPU/内存实时指标'}
title=t('kubernetes.podmetricspage.s94c067')
subtitle={clusterName ? t('kubernetes.podmetricspage.sc3a5a8', { clusterName: clusterName }) : t('kubernetes.podmetricspage.s6dbb5e')}
icon={<Activity className="h-5 w-5" />}
metrics={!loading ? (
<StatStrip
items={[
{ label: 'Pod 数', value: metrics.length, color: 'muted' },
{ label: '总 CPU', value: `${totalCPU}m`, color: 'blue' },
{ label: '总内存', value: `${totalMem.toFixed(0)}Mi`, color: 'green' },
{ label: t('kubernetes.node.podCount'), value: metrics.length, color: 'muted' },
{ label: t('kubernetes.podmetricspage.sac1fc3'), value: `${totalCPU}m`, color: 'blue' },
{ label: t('monitor.systemInfo.memTotal'), value: `${totalMem.toFixed(0)}Mi`, color: 'green' },
]}
/>
) : undefined}
@@ -106,9 +108,9 @@ export default function PodMetricsPage() {
</SelectContent>
</Select>
<Select value={selectedNs} onValueChange={setSelectedNs}>
<SelectTrigger className="w-36 h-9 dg-input"><SelectValue placeholder="所有命名空间" /></SelectTrigger>
<SelectTrigger className="w-36 h-9 dg-input"><SelectValue placeholder=t('kubernetes.podmetricspage.s58173b') /></SelectTrigger>
<SelectContent>
<SelectItem value="all">所有命名空间</SelectItem>
<SelectItem value="all">{t('kubernetes.podmetricspage.s58173b')}</SelectItem>
{namespaces.map(n => <SelectItem key={n} value={n}>{n}</SelectItem>)}
</SelectContent>
</Select>
@@ -123,8 +125,8 @@ export default function PodMetricsPage() {
<Table>
<TableHeader><TableRow className="border-[var(--dg-border)] hover:bg-transparent">
<TableHead className="dg-text-secondary">Pod</TableHead>
<TableHead className="dg-text-secondary">命名空间</TableHead>
<TableHead className="dg-text-secondary">容器</TableHead>
<TableHead className="dg-text-secondary">{t('k8s.column.namespace')}</TableHead>
<TableHead className="dg-text-secondary">{t('k8s.pods.containers')}</TableHead>
<TableHead className="dg-text-secondary"><Cpu className="h-3 w-3 inline mr-1" />CPU</TableHead>
<TableHead className="dg-text-secondary"><HardDrive className="h-3 w-3 inline mr-1" />Memory</TableHead>
</TableRow></TableHeader>
@@ -17,6 +17,7 @@ import { YamlEditorToolbar } from './YamlEditorToolbar';
import { YamlCodeMirror } from './YamlCodeMirror';
import { getYamlResourceConfig, yamlDownloadFilename } from './k8s-yaml-resource-config';
import { downloadYamlFile } from '@/utils/export';
import { useTranslation } from 'react-i18next';
interface ResourceVisualEditorProps {
clusterCode: string;
@@ -30,6 +31,7 @@ interface ResourceVisualEditorProps {
}
export function ResourceVisualEditor({ clusterCode, namespace, resource, name, onClose, onSaved, isCreate = false }: ResourceVisualEditorProps) {
const { t } = useTranslation();
const { toast } = useToast();
const [loading, setLoading] = useState(true);
const [saving, setSaving] = useState(false);
@@ -66,10 +68,10 @@ export function ResourceVisualEditor({ clusterCode, namespace, resource, name, o
setManifest(parsed);
if (!parsed) {
setMode('yaml');
toast({ title: '可视化编辑不可用', description: '无法解析资源结构,已切换到 YAML 编辑模式' });
toast({ title: t('kubernetes.resourcevisualeditor.s80ca4f'), description: t('kubernetes.resourcevisualeditor.scc94aa') });
}
} catch (e) {
toast({ title: '加载失败', description: e instanceof Error ? e.message : String(e), variant: 'destructive' });
toast({ title: t('common.loadFailed'), description: e instanceof Error ? e.message : String(e), variant: 'destructive' });
} finally { setLoading(false); }
}, [clusterCode, namespace, resource, name, isCreate]);
@@ -82,19 +84,19 @@ export function ResourceVisualEditor({ clusterCode, namespace, resource, name, o
const resName = updatedManifest?.metadata?.name || name;
if (isCreate) {
if (!resName?.trim()) {
toast({ title: '请填写名称', variant: 'destructive' });
toast({ title: t('deploy.form.nameRequired'), variant: 'destructive' });
return;
}
await kubernetesApi.applyYAML(clusterCode, yamlStr);
toast({ title: '创建成功', description: `${resource}/${resName}` });
toast({ title: t('monitor.dashboard.custom.toastCreateSuccess'), description: `${resource}/${resName}` });
} else {
await kubernetesApi.updateResourceYaml(clusterCode, namespace, resource, name, yamlStr);
toast({ title: '保存成功', description: `${resource}/${name} 已更新` });
toast({ title: t('common.savedSuccessfully'), description: t('kubernetes.resourcevisualeditor.se7e1ac_0', { resource: resource, name: name }) });
}
onSaved?.();
onClose();
} catch (e) {
toast({ title: isCreate ? '创建失败' : '保存失败', description: e instanceof Error ? e.message : String(e), variant: 'destructive' });
toast({ title: isCreate ? t('monitor.quickSetupFailed') : t('common.saveFailed'), description: e instanceof Error ? e.message : String(e), variant: 'destructive' });
} finally { setSaving(false); }
};
@@ -104,10 +106,10 @@ export function ResourceVisualEditor({ clusterCode, namespace, resource, name, o
const yamlStr = await prepareYamlForSave(editYaml);
if (isCreate) {
await kubernetesApi.applyYAML(clusterCode, yamlStr);
toast({ title: '创建成功', description: 'YAML 已应用' });
toast({ title: t('monitor.dashboard.custom.toastCreateSuccess'), description: t('kubernetes.resourcevisualeditor.se5ff4b') });
} else {
await kubernetesApi.updateResourceYaml(clusterCode, namespace, resource, name, yamlStr);
toast({ title: '保存成功', description: `${resource}/${name} 已更新` });
toast({ title: t('common.savedSuccessfully'), description: t('kubernetes.resourcevisualeditor.se7e1ac', { resource: resource, name: name }) });
}
setYamlEditing(false);
setDisplayYaml(yamlStr);
@@ -116,7 +118,7 @@ export function ResourceVisualEditor({ clusterCode, namespace, resource, name, o
onSaved?.();
onClose();
} catch (e) {
toast({ title: '保存失败', description: e instanceof Error ? e.message : String(e), variant: 'destructive' });
toast({ title: t('common.saveFailed'), description: e instanceof Error ? e.message : String(e), variant: 'destructive' });
} finally { setSaving(false); }
};
@@ -124,7 +126,7 @@ export function ResourceVisualEditor({ clusterCode, namespace, resource, name, o
const switchToVisual = async () => {
const parsed = await parseManifest(editYaml);
if (!parsed) {
toast({ title: '无法解析 YAML', description: '请检查语法后继续用 YAML 模式', variant: 'destructive' });
toast({ title: t('kubernetes.resourcevisualeditor.sf53bdf'), description: t('kubernetes.resourcevisualeditor.sf2219a'), variant: 'destructive' });
return;
}
setManifest(parsed);
@@ -153,7 +155,7 @@ export function ResourceVisualEditor({ clusterCode, namespace, resource, name, o
const downloadYamlContent = () => {
const fname = yamlDownloadFilename(resource, namespace, name || manifest?.metadata?.name || 'resource');
downloadYamlFile(fname, currentYamlText());
toast({ title: '已下载', description: fname });
toast({ title: t('kubernetes.resourcevisualeditor.s9719fe'), description: fname });
};
const resCfg = getYamlResourceConfig(resource);
@@ -179,7 +181,7 @@ export function ResourceVisualEditor({ clusterCode, namespace, resource, name, o
<MetaIcon className={`h-5 w-5 shrink-0 ${meta.color}`} />
<div className="min-w-0">
<h2 className="text-lg font-bold text-[var(--dg-text-primary)] truncate">
{isCreate ? `新建 ${meta.title}` : `${meta.title} 编辑`}
{isCreate ? t('kubernetes.resourcevisualeditor.s1876b4', { meta.title: meta.title }) : t('kubernetes.resourcevisualeditor.sc05c9e', { meta.title: meta.title })}
</h2>
<p
className="text-xs text-[var(--dg-text-muted)] truncate"
@@ -196,11 +198,11 @@ export function ResourceVisualEditor({ clusterCode, namespace, resource, name, o
className={`px-3 py-1.5 text-xs font-medium transition-colors ${mode === 'visual' ? 'bg-blue-600 text-white' : 'bg-transparent text-[var(--dg-text-secondary)] hover:bg-[var(--dg-bg-tertiary)]'}`}
onClick={() => { if (mode === 'yaml') switchToVisual(); else setMode('visual'); }}
disabled={!manifest && mode !== 'yaml'}
>可视化编辑</button>
>{t('k8s.resource.visualEditor')}</button>
<button
className={`px-3 py-1.5 text-xs font-medium transition-colors ${mode === 'yaml' ? 'bg-blue-600 text-white' : 'bg-transparent text-[var(--dg-text-secondary)] hover:bg-[var(--dg-bg-tertiary)]'}`}
onClick={() => { if (mode === 'visual') switchToYaml(); else setMode('yaml'); }}
>YAML 编辑</button>
>{t('k8s.resource.yamlEditor')}</button>
</div>
<Button variant="ghost" size="icon" className="h-8 w-8 text-[var(--dg-text-secondary)]" onClick={onClose}><X className="h-4 w-4" /></Button>
</div>
@@ -259,16 +261,16 @@ export function ResourceVisualEditor({ clusterCode, namespace, resource, name, o
{!['configmaps', 'secrets', 'services', 'ingresses', 'pvcs'].includes(resource) && (
<div className="flex-1 flex items-center justify-center text-center text-[var(--dg-text-muted)]">
<div>
<p>该资源类型暂不支持可视化编辑</p>
<Button variant="outline" size="sm" className="mt-4" onClick={() => setMode('yaml')}>切换到 YAML 编辑</Button>
<p>{t('kubernetes.resourcevisualeditor.sfeb34f')}</p>
<Button variant="outline" size="sm" className="mt-4" onClick={() => setMode('yaml')}>{t('kubernetes.resourcevisualeditor.s54c78d')}</Button>
</div>
</div>
)}
</div>
) : (
<div className="text-center py-12 text-[var(--dg-text-muted)]">
<p>无法解析资源结构</p>
<Button variant="outline" size="sm" className="mt-4" onClick={() => setMode('yaml')}>切换到 YAML 编辑</Button>
<p>{t('kubernetes.resourcevisualeditor.s8fe0ae')}</p>
<Button variant="outline" size="sm" className="mt-4" onClick={() => setMode('yaml')}>{t('kubernetes.resourcevisualeditor.s54c78d')}</Button>
</div>
)}
</div>
@@ -281,6 +283,7 @@ export function ResourceVisualEditor({ clusterCode, namespace, resource, name, o
// ConfigMap 编辑器 — 键值对表格
// ══════════════════════════════════════════════
function ConfigMapEditor({ manifest, onSave, saving, isCreate }: { manifest: any; onSave: (m: any) => void; saving: boolean; isCreate?: boolean }) {
const { t } = useTranslation();
const data = manifest?.data || {};
const [resName, setResName] = useState(manifest?.metadata?.name || '');
const [entries, setEntries] = useState<{ key: string; value: string }[]>(
@@ -308,18 +311,18 @@ function ConfigMapEditor({ manifest, onSave, saving, isCreate }: { manifest: any
return (
<div className="flex flex-col h-full">
<div className="shrink-0">
<Label className="text-[var(--dg-text-secondary)] text-xs">名称</Label>
<Label className="text-[var(--dg-text-secondary)] text-xs">{t('common.name')}</Label>
<Input value={resName} onChange={(e) => setResName(e.target.value)} readOnly={!isCreate} className="mt-1 font-mono text-xs bg-[var(--dg-bg-tertiary)]" />
</div>
<div className="flex-1 min-h-0 flex flex-col mt-3">
<div className="flex items-center justify-between mb-2 shrink-0">
<Label className="text-[var(--dg-text-secondary)] text-sm">配置数据 (键值对)</Label>
<Label className="text-[var(--dg-text-secondary)] text-sm">{t('kubernetes.resourcevisualeditor.s6bd91c')}</Label>
<div className="flex gap-1">
<Button variant="outline" size="sm" className="h-7 text-xs" onClick={() => setExpandAll(!expandAll)}>
{expandAll ? '折叠全部' : '展开全部'}
{expandAll ? t('kubernetes.resourcevisualeditor.s880e84') : t('common.expandAll')}
</Button>
<Button variant="outline" size="sm" className="h-7 text-xs" onClick={addRow}><Plus className="h-3 w-3 mr-1" />添加</Button>
<Button variant="outline" size="sm" className="h-7 text-xs" onClick={addRow}><Plus className="h-3 w-3 mr-1" />{t('common.add')}</Button>
</div>
</div>
<div className="flex-1 min-h-0 overflow-y-auto pr-1 space-y-2 border border-[var(--dg-border)] rounded-lg bg-[var(--dg-bg-secondary)] p-2">
@@ -328,13 +331,13 @@ function ConfigMapEditor({ manifest, onSave, saving, isCreate }: { manifest: any
<Input
value={entry.key}
onChange={e => update(i, 'key', e.target.value)}
placeholder="键名 (如 LOG_LEVEL)"
placeholder=t('kubernetes.resourcevisualeditor.s65017d')
className="flex-1 font-mono text-xs h-8 bg-[var(--dg-bg-tertiary)] border-[var(--dg-border)] text-[var(--dg-text-primary)]"
/>
<Textarea
value={entry.value}
onChange={e => update(i, 'value', e.target.value)}
placeholder="值"
placeholder=t('k8s.resource.value')
rows={expandAll || entry.value.length > 300 ? 10 : (entry.value.length > 100 ? 6 : 3)}
className="flex-[2] font-mono text-xs min-h-[70px] max-h-[420px] resize-y bg-[var(--dg-bg-tertiary)] border-[var(--dg-border)] text-[var(--dg-text-primary)] leading-relaxed"
/>
@@ -344,7 +347,7 @@ function ConfigMapEditor({ manifest, onSave, saving, isCreate }: { manifest: any
</div>
))}
{entries.length === 0 && (
<div className="text-center py-8 text-[var(--dg-text-muted)] text-xs">暂无配置数据,点击「添加」创建</div>
<div className="text-center py-8 text-[var(--dg-text-muted)] text-xs">{t('kubernetes.resourcevisualeditor.saf7696')}</div>
)}
</div>
</div>
@@ -363,6 +366,7 @@ function ConfigMapEditor({ manifest, onSave, saving, isCreate }: { manifest: any
// Secret 编辑器 — 键值对表格 (Base64 编码/解码)
// ══════════════════════════════════════════════
function SecretEditor({ manifest, onSave, saving, isCreate }: { manifest: any; onSave: (m: any) => void; saving: boolean; isCreate?: boolean }) {
const { t } = useTranslation();
const rawData = manifest?.data || {};
const [resName, setResName] = useState(manifest?.metadata?.name || '');
const [expandAll, setExpandAll] = useState(false);
@@ -404,23 +408,23 @@ function SecretEditor({ manifest, onSave, saving, isCreate }: { manifest: any; o
<div className="flex flex-col h-full">
<div className="shrink-0 grid grid-cols-2 gap-4">
<div>
<Label className="text-[var(--dg-text-secondary)] text-xs">名称</Label>
<Label className="text-[var(--dg-text-secondary)] text-xs">{t('common.name')}</Label>
<Input value={resName} onChange={(e) => setResName(e.target.value)} readOnly={!isCreate} className="mt-1 font-mono text-xs bg-[var(--dg-bg-tertiary)]" />
</div>
<div>
<Label className="text-[var(--dg-text-secondary)] text-xs">类型</Label>
<Label className="text-[var(--dg-text-secondary)] text-xs">{t('common.type')}</Label>
<Input value={manifest?.type || 'Opaque'} readOnly className="mt-1 font-mono text-xs bg-[var(--dg-bg-tertiary)]" />
</div>
</div>
<div className="flex-1 min-h-0 flex flex-col mt-3">
<div className="flex items-center justify-between mb-2 shrink-0">
<Label className="text-[var(--dg-text-secondary)] text-sm">密钥数据 (已自动解码 Base64)</Label>
<Label className="text-[var(--dg-text-secondary)] text-sm">{t('kubernetes.resourcevisualeditor.se19370')}</Label>
<div className="flex gap-1">
<Button variant="outline" size="sm" className="h-7 text-xs" onClick={() => setExpandAll(!expandAll)}>
{expandAll ? '折叠全部' : '展开全部'}
{expandAll ? t('kubernetes.resourcevisualeditor.s880e84') : t('common.expandAll')}
</Button>
<Button variant="outline" size="sm" className="h-7 text-xs" onClick={addRow}><Plus className="h-3 w-3 mr-1" />添加</Button>
<Button variant="outline" size="sm" className="h-7 text-xs" onClick={addRow}><Plus className="h-3 w-3 mr-1" />{t('common.add')}</Button>
</div>
</div>
<div className="flex-1 min-h-0 overflow-y-auto pr-1 space-y-2 border border-[var(--dg-border)] rounded-lg bg-[var(--dg-bg-secondary)] p-2">
@@ -429,13 +433,13 @@ function SecretEditor({ manifest, onSave, saving, isCreate }: { manifest: any; o
<Input
value={entry.key}
onChange={e => update(i, 'key', e.target.value)}
placeholder="键名 (如 password)"
placeholder=t('kubernetes.resourcevisualeditor.scdecc4')
className="flex-1 font-mono text-xs h-8 bg-[var(--dg-bg-tertiary)] border-[var(--dg-border)] text-[var(--dg-text-primary)]"
/>
<Textarea
value={entry.value}
onChange={e => update(i, 'value', e.target.value)}
placeholder="明文值"
placeholder=t('kubernetes.resourcevisualeditor.s7f123d')
rows={expandAll || entry.value.length > 300 ? 10 : (entry.value.length > 100 ? 6 : 3)}
className="flex-[2] font-mono text-xs min-h-[70px] max-h-[420px] resize-y bg-[var(--dg-bg-tertiary)] border-[var(--dg-border)] text-[var(--dg-text-primary)] leading-relaxed"
/>
@@ -445,7 +449,7 @@ function SecretEditor({ manifest, onSave, saving, isCreate }: { manifest: any; o
</div>
))}
{entries.length === 0 && (
<div className="text-center py-8 text-[var(--dg-text-muted)] text-xs">暂无密钥数据,点击「添加」创建</div>
<div className="text-center py-8 text-[var(--dg-text-muted)] text-xs">{t('kubernetes.resourcevisualeditor.s47ff69')}</div>
)}
</div>
</div>
@@ -464,6 +468,7 @@ function SecretEditor({ manifest, onSave, saving, isCreate }: { manifest: any; o
// Service 编辑器 — 端口配置 + 类型 + 选择器
// ══════════════════════════════════════════════
function ServiceEditor({ manifest, onSave, saving, isCreate }: { manifest: any; onSave: (m: any) => void; saving: boolean; isCreate?: boolean }) {
const { t } = useTranslation();
const spec = manifest?.spec || {};
const [resName, setResName] = useState(manifest?.metadata?.name || '');
const [svcType, setSvcType] = useState(spec.type || 'ClusterIP');
@@ -524,11 +529,11 @@ function ServiceEditor({ manifest, onSave, saving, isCreate }: { manifest: any;
return (
<div className="flex flex-col h-full">
<div className="shrink-0">
<Label className="text-[var(--dg-text-secondary)] text-xs">服务名称</Label>
<Label className="text-[var(--dg-text-secondary)] text-xs">{t('agent.agentServiceName')}</Label>
<Input value={resName} onChange={(e) => setResName(e.target.value)} readOnly={!isCreate} className="mt-1 font-mono text-xs bg-[var(--dg-bg-tertiary)]" />
</div>
<div className="shrink-0 mt-3">
<Label className="text-[var(--dg-text-secondary)] text-xs mb-2 block">服务类型</Label>
<Label className="text-[var(--dg-text-secondary)] text-xs mb-2 block">{t('k8s.resource.serviceType')}</Label>
<div className="flex rounded-lg border border-[var(--dg-border)] overflow-hidden w-fit">
{svcTypes.map((t) => (
<button
@@ -547,16 +552,16 @@ function ServiceEditor({ manifest, onSave, saving, isCreate }: { manifest: any;
<div className="flex-1 min-h-0 overflow-y-auto mt-3 pr-1 space-y-3">
<div>
<div className="flex items-center justify-between mb-2">
<Label className="text-[var(--dg-text-secondary)] text-sm">端口映射</Label>
<Button variant="outline" size="sm" className="h-7 text-xs" onClick={addPort}><Plus className="h-3 w-3 mr-1" />添加端口</Button>
<Label className="text-[var(--dg-text-secondary)] text-sm">{t('kubernetes.resourcevisualeditor.s736788')}</Label>
<Button variant="outline" size="sm" className="h-7 text-xs" onClick={addPort}><Plus className="h-3 w-3 mr-1" />{t('agent.addPort')}</Button>
</div>
<div className="space-y-2 border border-[var(--dg-border)] rounded-lg p-2 bg-[var(--dg-bg-secondary)]">
{ports.map((p, i) => (
<div key={i} className="overflow-x-auto">
<div className="grid grid-cols-[minmax(80px,1fr)_80px_80px_80px_80px_32px] gap-2 items-center min-w-[480px]">
<Input value={p.name} onChange={e => updatePort(i, 'name', e.target.value)} placeholder="名称" className="font-mono text-xs h-7 bg-[var(--dg-bg-tertiary)] border-[var(--dg-border)] text-[var(--dg-text-primary)]" />
<Input value={p.port} onChange={e => updatePort(i, 'port', e.target.value)} placeholder="端口" type="number" className="font-mono text-xs h-7 bg-[var(--dg-bg-tertiary)] border-[var(--dg-border)] text-[var(--dg-text-primary)]" />
<Input value={p.targetPort} onChange={e => updatePort(i, 'targetPort', e.target.value)} placeholder="目标" type="number" className="font-mono text-xs h-7 bg-[var(--dg-bg-tertiary)] border-[var(--dg-border)] text-[var(--dg-text-primary)]" />
<Input value={p.name} onChange={e => updatePort(i, 'name', e.target.value)} placeholder=t('common.name') className="font-mono text-xs h-7 bg-[var(--dg-bg-tertiary)] border-[var(--dg-border)] text-[var(--dg-text-primary)]" />
<Input value={p.port} onChange={e => updatePort(i, 'port', e.target.value)} placeholder=t('server.csv.port') type="number" className="font-mono text-xs h-7 bg-[var(--dg-bg-tertiary)] border-[var(--dg-border)] text-[var(--dg-text-primary)]" />
<Input value={p.targetPort} onChange={e => updatePort(i, 'targetPort', e.target.value)} placeholder=t('common.target') type="number" className="font-mono text-xs h-7 bg-[var(--dg-bg-tertiary)] border-[var(--dg-border)] text-[var(--dg-text-primary)]" />
<Select value={p.protocol} onValueChange={v => updatePort(i, 'protocol', v)}>
<SelectTrigger className="h-7 text-xs bg-[var(--dg-bg-tertiary)] border-[var(--dg-border)] text-[var(--dg-text-primary)]"><SelectValue /></SelectTrigger>
<SelectContent><SelectItem value="TCP">TCP</SelectItem><SelectItem value="UDP">UDP</SelectItem></SelectContent>
@@ -568,26 +573,26 @@ function ServiceEditor({ manifest, onSave, saving, isCreate }: { manifest: any;
</div>
</div>
))}
{ports.length === 0 && <div className="text-center py-4 text-[var(--dg-text-muted)] text-xs">暂无端口,点击「添加端口」</div>}
{ports.length === 0 && <div className="text-center py-4 text-[var(--dg-text-muted)] text-xs">{t('kubernetes.resourcevisualeditor.sf3ba5e')}</div>}
</div>
</div>
{/* Selector */}
<div>
<div className="flex items-center justify-between mb-2">
<Label className="text-[var(--dg-text-secondary)] text-sm">选择器 (Selector)</Label>
<Button variant="outline" size="sm" className="h-7 text-xs" onClick={addSelector}><Plus className="h-3 w-3 mr-1" />添加标签</Button>
<Label className="text-[var(--dg-text-secondary)] text-sm">{t('kubernetes.resourcevisualeditor.scecdd7')}</Label>
<Button variant="outline" size="sm" className="h-7 text-xs" onClick={addSelector}><Plus className="h-3 w-3 mr-1" />{t('kubernetes.resourcevisualeditor.s736eaa')}</Button>
</div>
<div className="space-y-2">
{selector.map((s, i) => (
<div key={i} className="flex items-center gap-2 min-w-0">
<Input value={s.key} onChange={e => updateSelector(i, 'key', e.target.value)} placeholder="键 (如 app)" className="flex-1 min-w-0 font-mono text-xs h-7 bg-[var(--dg-bg-tertiary)] border-[var(--dg-border)] text-[var(--dg-text-primary)]" />
<Input value={s.key} onChange={e => updateSelector(i, 'key', e.target.value)} placeholder=t('kubernetes.resourcevisualeditor.s450c99') className="flex-1 min-w-0 font-mono text-xs h-7 bg-[var(--dg-bg-tertiary)] border-[var(--dg-border)] text-[var(--dg-text-primary)]" />
<span className="text-[var(--dg-text-muted)] text-xs shrink-0">=</span>
<Input value={s.value} onChange={e => updateSelector(i, 'value', e.target.value)} placeholder="值 (如 nginx)" className="flex-1 min-w-0 font-mono text-xs h-7 bg-[var(--dg-bg-tertiary)] border-[var(--dg-border)] text-[var(--dg-text-primary)]" />
<Input value={s.value} onChange={e => updateSelector(i, 'value', e.target.value)} placeholder=t('kubernetes.resourcevisualeditor.sb873e4') className="flex-1 min-w-0 font-mono text-xs h-7 bg-[var(--dg-bg-tertiary)] border-[var(--dg-border)] text-[var(--dg-text-primary)]" />
<Button variant="ghost" size="icon" className="h-7 w-7 shrink-0 dg-text-red hover:dg-text-red" onClick={() => removeSelector(i)}><Trash2 className="h-3 w-3" /></Button>
</div>
))}
{selector.length === 0 && <div className="text-center py-4 text-[var(--dg-text-muted)] text-xs">暂无选择器</div>}
{selector.length === 0 && <div className="text-center py-4 text-[var(--dg-text-muted)] text-xs">{t('k8s.resource.noSelectors')}</div>}
</div>
</div>
</div>
@@ -606,6 +611,7 @@ function ServiceEditor({ manifest, onSave, saving, isCreate }: { manifest: any;
// Ingress 编辑器 — Host/Path 路由规则
// ══════════════════════════════════════════════
function IngressEditor({ manifest, clusterCode, onSave, saving, isCreate }: { manifest: any; clusterCode: string; onSave: (m: any) => void; saving: boolean; isCreate?: boolean }) {
const { t } = useTranslation();
const spec = manifest?.spec || {};
const [resName, setResName] = useState(manifest?.metadata?.name || '');
const [ingressClass, setIngressClass] = useState(spec.ingressClassName || 'nginx');
@@ -689,13 +695,13 @@ function IngressEditor({ manifest, clusterCode, onSave, saving, isCreate }: { ma
<div className="flex flex-col h-full min-h-0">
<div className="shrink-0 grid grid-cols-1 sm:grid-cols-2 gap-4">
<div className="min-w-0">
<Label className="text-[var(--dg-text-secondary)] text-xs">名称</Label>
<Label className="text-[var(--dg-text-secondary)] text-xs">{t('common.name')}</Label>
<Input value={resName} onChange={(e) => setResName(e.target.value)} readOnly={!isCreate} className="mt-1 font-mono text-xs bg-[var(--dg-bg-tertiary)]" />
</div>
<div className="min-w-0">
<Label className="text-[var(--dg-text-secondary)] text-xs flex items-center gap-1">
Ingress Class
<span className="text-[10px] text-[var(--dg-text-muted)]">(可选)</span>
<span className="text-[10px] text-[var(--dg-text-muted)]">{t('kubernetes.resourcevisualeditor.s6c9a78')}</span>
</Label>
{/* IngressClass 下拉 + 手工输入支持 // Logan.Li */}
<div className="space-y-1 mt-1">
@@ -708,7 +714,7 @@ function IngressEditor({ manifest, clusterCode, onSave, saving, isCreate }: { ma
}}
>
<SelectTrigger className="h-8 text-xs bg-[var(--dg-bg-tertiary)] border-[var(--dg-border)] text-[var(--dg-text-primary)]">
<SelectValue placeholder={loadingClasses ? '加载中...' : '选择或输入 IngressClass'} />
<SelectValue placeholder={loadingClasses ? t('common.loading') : t('kubernetes.resourcevisualeditor.s25a87d')} />
</SelectTrigger>
<SelectContent>
{ingressClasses.length > 0 ? (
@@ -718,13 +724,13 @@ function IngressEditor({ manifest, clusterCode, onSave, saving, isCreate }: { ma
</SelectItem>
))
) : (
!loadingClasses && <div className="px-2 py-1.5 text-xs text-[var(--dg-text-muted)]">未发现 IngressClass,请手动输入</div>
!loadingClasses && <div className="px-2 py-1.5 text-xs text-[var(--dg-text-muted)]">{t('kubernetes.resourcevisualeditor.s619a36')}</div>
)}
{/* 当前自定义值作为选项,确保选中态 */}
{ingressClass && !ingressClasses.some((ic) => ic.name === ingressClass) && (
<SelectItem value={ingressClass}>{ingressClass} (手动输入)</SelectItem>
)}
<SelectItem value="__manual__">—— 继续手动输入 ——</SelectItem>
<SelectItem value="__manual__">{t('kubernetes.resourcevisualeditor.se83eb1')}</SelectItem>
</SelectContent>
</Select>
@@ -755,8 +761,8 @@ function IngressEditor({ manifest, clusterCode, onSave, saving, isCreate }: { ma
</div>
<div className="flex-1 min-h-0 flex flex-col mt-3">
<div className="flex items-center justify-between mb-2 shrink-0">
<Label className="text-[var(--dg-text-secondary)] text-sm">路由规则</Label>
<Button variant="outline" size="sm" className="h-7 text-xs" onClick={addRule}><Plus className="h-3 w-3 mr-1" />添加 Host</Button>
<Label className="text-[var(--dg-text-secondary)] text-sm">{t('k8s.resource.routeRules')}</Label>
<Button variant="outline" size="sm" className="h-7 text-xs" onClick={addRule}><Plus className="h-3 w-3 mr-1" />{t('kubernetes.resourcevisualeditor.s4f0a38')}</Button>
</div>
<div className="flex-1 min-h-0 overflow-y-auto pr-1 space-y-3 border border-[var(--dg-border)] rounded-lg p-2 bg-[var(--dg-bg-secondary)]">
{rules.map((rule, ri) => (
@@ -765,7 +771,7 @@ function IngressEditor({ manifest, clusterCode, onSave, saving, isCreate }: { ma
<Input
value={rule.host}
onChange={e => updateRule(ri, e.target.value)}
placeholder="域名 (如 api.example.com)"
placeholder=t('kubernetes.resourcevisualeditor.s33cde9')
className="flex-1 min-w-0 font-mono text-xs h-7 bg-[var(--dg-bg-tertiary)] border-[var(--dg-border)] text-[var(--dg-text-primary)]"
title={rule.host}
/>
@@ -774,21 +780,21 @@ function IngressEditor({ manifest, clusterCode, onSave, saving, isCreate }: { ma
{rule.paths.map((p, pi) => (
<div key={pi} className="overflow-x-auto pl-4">
<div className="grid grid-cols-[minmax(80px,1fr)_100px_minmax(80px,1fr)_60px_28px] gap-1.5 items-center min-w-[420px]">
<Input value={p.path} onChange={e => updatePath(ri, pi, 'path', e.target.value)} placeholder="路径 /" className="font-mono text-xs h-7 min-w-0 bg-[var(--dg-bg-tertiary)] border-[var(--dg-border)] text-[var(--dg-text-primary)]" />
<Input value={p.path} onChange={e => updatePath(ri, pi, 'path', e.target.value)} placeholder=t('kubernetes.resourcevisualeditor.sdfd5eb') className="font-mono text-xs h-7 min-w-0 bg-[var(--dg-bg-tertiary)] border-[var(--dg-border)] text-[var(--dg-text-primary)]" />
<Select value={p.pathType} onValueChange={v => updatePath(ri, pi, 'pathType', v)}>
<SelectTrigger className="h-7 text-xs bg-[var(--dg-bg-tertiary)] border-[var(--dg-border)] text-[var(--dg-text-primary)]"><SelectValue /></SelectTrigger>
<SelectContent><SelectItem value="Prefix">Prefix</SelectItem><SelectItem value="Exact">Exact</SelectItem></SelectContent>
</Select>
<Input value={p.serviceName} onChange={e => updatePath(ri, pi, 'serviceName', e.target.value)} placeholder="Service" className="font-mono text-xs h-7 min-w-0 bg-[var(--dg-bg-tertiary)] border-[var(--dg-border)] text-[var(--dg-text-primary)]" />
<Input value={p.servicePort} onChange={e => updatePath(ri, pi, 'servicePort', e.target.value)} placeholder="端口" type="number" className="font-mono text-xs h-7 bg-[var(--dg-bg-tertiary)] border-[var(--dg-border)] text-[var(--dg-text-primary)]" />
<Input value={p.servicePort} onChange={e => updatePath(ri, pi, 'servicePort', e.target.value)} placeholder=t('server.csv.port') type="number" className="font-mono text-xs h-7 bg-[var(--dg-bg-tertiary)] border-[var(--dg-border)] text-[var(--dg-text-primary)]" />
<Button variant="ghost" size="icon" className="h-7 w-7 dg-text-red hover:dg-text-red" onClick={() => removePath(ri, pi)}><Trash2 className="h-3 w-3" /></Button>
</div>
</div>
))}
<Button variant="ghost" size="sm" className="h-6 text-xs text-[var(--dg-text-muted)]" onClick={() => addPath(ri)}><Plus className="h-3 w-3 mr-1" />添加路径</Button>
<Button variant="ghost" size="sm" className="h-6 text-xs text-[var(--dg-text-muted)]" onClick={() => addPath(ri)}><Plus className="h-3 w-3 mr-1" />{t('kubernetes.ingress.addPath')}</Button>
</div>
))}
{rules.length === 0 && <div className="text-center py-4 text-[var(--dg-text-muted)] text-xs">暂无路由规则,点击「添加 Host」</div>}
{rules.length === 0 && <div className="text-center py-4 text-[var(--dg-text-muted)] text-xs">{t('kubernetes.resourcevisualeditor.s0b0794')}</div>}
</div>
</div>
<div className="shrink-0 flex justify-end gap-2 pt-3 mt-2 border-t border-[var(--dg-border)]">
@@ -805,6 +811,7 @@ function IngressEditor({ manifest, clusterCode, onSave, saving, isCreate }: { ma
// PVC 编辑器 — 存储大小/访问模式/StorageClass
// ══════════════════════════════════════════════
function PvcEditor({ manifest, onSave, saving, isCreate }: { manifest: any; onSave: (m: any) => void; saving: boolean; isCreate?: boolean }) {
const { t } = useTranslation();
const spec = manifest?.spec || {};
const resources = spec.resources?.requests || {};
const [resName, setResName] = useState(manifest?.metadata?.name || '');
@@ -828,30 +835,30 @@ function PvcEditor({ manifest, onSave, saving, isCreate }: { manifest: any; onSa
return (
<div className="flex flex-col h-full">
<div className="shrink-0">
<Label className="text-[var(--dg-text-secondary)] text-xs">名称</Label>
<Label className="text-[var(--dg-text-secondary)] text-xs">{t('common.name')}</Label>
<Input value={resName} onChange={(e) => setResName(e.target.value)} readOnly={!isCreate} className="mt-1 font-mono text-xs bg-[var(--dg-bg-tertiary)]" />
</div>
<div className="grid grid-cols-2 gap-4 mt-3 shrink-0">
<div>
<Label className="text-[var(--dg-text-secondary)] text-xs">存储大小</Label>
<Label className="text-[var(--dg-text-secondary)] text-xs">{t('kubernetes.resourcevisualeditor.s61aa82')}</Label>
<Input
value={size}
onChange={e => setSize(e.target.value)}
placeholder="如 10Gi"
placeholder=t('kubernetes.resourcevisualeditor.s1b915a')
className="mt-1 font-mono text-xs h-8 bg-[var(--dg-bg-tertiary)] border-[var(--dg-border)] text-[var(--dg-text-primary)]"
/>
<p className="text-[10px] text-[var(--dg-text-muted)] mt-1">单位:Gi (GiB), Mi (MiB), Ti (TiB)</p>
<p className="text-[10px] text-[var(--dg-text-muted)] mt-1">{t('kubernetes.resourcevisualeditor.s6a1c7a')}</p>
</div>
<div>
<Label className="text-[var(--dg-text-secondary)] text-xs">访问模式</Label>
<Label className="text-[var(--dg-text-secondary)] text-xs">{t('k8s.resource.accessMode')}</Label>
<Select value={accessMode} onValueChange={setAccessMode}>
<SelectTrigger className="mt-1 h-8 bg-[var(--dg-bg-tertiary)] border-[var(--dg-border)] text-[var(--dg-text-primary)] text-xs">
<SelectValue />
</SelectTrigger>
<SelectContent>
<SelectItem value="ReadWriteOnce">ReadWriteOnce (单节点读写)</SelectItem>
<SelectItem value="ReadOnlyMany">ReadOnlyMany (多节点只读)</SelectItem>
<SelectItem value="ReadWriteMany">ReadWriteMany (多节点读写)</SelectItem>
<SelectItem value="ReadWriteOnce">{t('kubernetes.resourcevisualeditor.se1444f')}</SelectItem>
<SelectItem value="ReadOnlyMany">{t('kubernetes.resourcevisualeditor.s9d4ea0')}</SelectItem>
<SelectItem value="ReadWriteMany">{t('kubernetes.resourcevisualeditor.s093227')}</SelectItem>
</SelectContent>
</Select>
</div>
@@ -861,7 +868,7 @@ function PvcEditor({ manifest, onSave, saving, isCreate }: { manifest: any; onSa
<Input
value={storageClass}
onChange={e => setStorageClass(e.target.value)}
placeholder="留空使用默认 StorageClass"
placeholder=i18n.t('kubernetes.resourcevisualeditor.s06195f')
className="mt-1 font-mono text-xs h-8 bg-[var(--dg-bg-tertiary)] border-[var(--dg-border)] text-[var(--dg-text-primary)]"
/>
</div>
@@ -22,11 +22,13 @@ import { PodFileBrowser } from './PodFileBrowser';
import { formatK8sTime, statusColor, STATUS_COLORS } from './k8s-yaml-utils';
import { PageShell } from '@/components/layout/PageShell';
import type { JsonData } from '@/types/common';
import { useTranslation } from 'react-i18next';
type WorkloadKind = 'StatefulSet' | 'DaemonSet';
type ViewMode = 'view' | 'yaml';
function StatCard({ label, value, sub, color }: { label: string; value: React.ReactNode; sub?: string; color?: string }) {
const { t } = useTranslation();
return (
<Card className="bg-[var(--dg-bg-secondary)] border-[var(--dg-border)]">
<CardContent className="p-3">
@@ -40,8 +42,9 @@ function StatCard({ label, value, sub, color }: { label: string; value: React.Re
// Helper: render key-value pairs as badges
function LabelBadges({ labels }: { labels: Record<string, string> | undefined }) {
const { t } = useTranslation();
const entries = Object.entries(labels || {});
if (entries.length === 0) return <span className="text-xs text-[var(--dg-text-muted)]">无</span>;
if (entries.length === 0) return <span className="text-xs text-[var(--dg-text-muted)]">{t('common.none')}</span>;
return (
<div className="flex flex-wrap gap-1.5">
{entries.map(([k, v]) => (
@@ -54,6 +57,7 @@ function LabelBadges({ labels }: { labels: Record<string, string> | undefined })
}
export default function WorkloadViewPage() {
const { t } = useTranslation();
const params = useParams<{ clusterCode: string; namespace: string; name: string; mode?: string }>();
const navigate = useNavigate();
const location = useLocation();
@@ -119,9 +123,9 @@ export default function WorkloadViewPage() {
const handleRestart = async () => {
const ok = await confirm({
title: '滚动重启',
description: `确认重启 ${kind} ${name}?将触发滚动重启。`,
confirmText: '重启',
title: t('kubernetes.deployment.restart'),
description: t('kubernetes.workloadviewpage.s6139f5', { kind: kind, name: name }),
confirmText: t('common.reboot'),
});
if (!ok) return;
setActionLoading(true);
@@ -131,10 +135,10 @@ export default function WorkloadViewPage() {
} else {
await kubernetesApi.restartDaemonSet(clusterCode, namespace, name);
}
toast({ title: '重启指令已下发', description: `${kind} 滚动重启已触发` });
toast({ title: t('kubernetes.workloadviewpage.s68a700'), description: t('kubernetes.workloadviewpage.sb0614d', { kind: kind }) });
setTimeout(loadData, 1000);
} catch (e) {
toast({ title: '重启失败', description: e?.message || String(e), variant: 'destructive' });
toast({ title: t('kubernetes.deployment.restartFailed'), description: e?.message || String(e), variant: 'destructive' });
} finally { setActionLoading(false); }
};
@@ -142,11 +146,11 @@ export default function WorkloadViewPage() {
setActionLoading(true);
try {
await kubernetesApi.scaleStatefulSet(clusterCode, namespace, name, scaleValue);
toast({ title: '扩缩容成功', description: `StatefulSet 副本数已更新为 ${scaleValue}` });
toast({ title: t('kubernetes.workloadviewpage.s0b3ea1'), description: t('kubernetes.workloadviewpage.s27c3cf', { scaleValue: scaleValue }) });
setScaleModal(false);
setTimeout(loadData, 1000);
} catch (e) {
toast({ title: '扩缩容失败', description: e?.message || String(e), variant: 'destructive' });
toast({ title: t('kubernetes.workloadviewpage.s0b329f'), description: e?.message || String(e), variant: 'destructive' });
} finally { setActionLoading(false); }
};
@@ -190,7 +194,7 @@ export default function WorkloadViewPage() {
const modeTabs = (
<div className="flex items-center gap-1 bg-[var(--dg-bg-secondary)] border border-[var(--dg-border)] rounded-lg p-0.5">
<button className={`px-3 py-1 text-xs rounded transition-colors ${mode === 'view' ? 'bg-[var(--dg-blue)]/20 text-[var(--dg-blue)]' : 'text-[var(--dg-text-secondary)] hover:text-[var(--dg-text-primary)]'}`} onClick={() => handleModeChange('view')}>查看</button>
<button className={`px-3 py-1 text-xs rounded transition-colors ${mode === 'view' ? 'bg-[var(--dg-blue)]/20 text-[var(--dg-blue)]' : 'text-[var(--dg-text-secondary)] hover:text-[var(--dg-text-primary)]'}`} onClick={() => handleModeChange('view')}>{t('common.view')}</button>
<button className={`px-3 py-1 text-xs rounded transition-colors ${mode === 'yaml' ? 'bg-[var(--dg-blue)]/20 text-[var(--dg-blue)]' : 'text-[var(--dg-text-secondary)] hover:text-[var(--dg-text-primary)]'}`} onClick={() => handleModeChange('yaml')}>YAML</button>
</div>
);
@@ -202,7 +206,7 @@ export default function WorkloadViewPage() {
subtitle={`${clusterCode} / ${namespace} · ${kind}`}
icon={<Boxes className="h-5 w-5" />}
loading={loading}
loadingLabel="加载工作负载..."
loadingLabel=t('kubernetes.workloadviewpage.s4eb429')
actions={(
<>
<Button variant="outline" size="sm" className="dg-btn-secondary" onClick={() => navigate(-1)}>
@@ -215,7 +219,7 @@ export default function WorkloadViewPage() {
</Button>
)}
<Button variant="outline" size="sm" className="dg-btn-secondary" disabled={actionLoading} onClick={handleRestart}>
<RotateCcw className="h-3.5 w-3.5 mr-1" />{actionLoading ? '重启中...' : '重启'}
<RotateCcw className="h-3.5 w-3.5 mr-1" />{actionLoading ? t('kubernetes.workloadviewpage.s9ac104') : t('common.reboot')}
</Button>
<Button variant="outline" size="sm" className="dg-btn-secondary" onClick={() => setYamlModal(true)}>
<FileCode className="h-3.5 w-3.5 mr-1" />YAML
@@ -227,8 +231,8 @@ export default function WorkloadViewPage() {
<Badge variant="outline" className="border-[var(--dg-border)] text-[var(--dg-text-secondary)]">{kind}</Badge>
<Badge variant="outline" className="border-[var(--dg-border)] text-[var(--dg-text-secondary)]">{namespace}</Badge>
{isHealthy
? <Badge className="bg-[var(--dg-green)]/20 text-[var(--dg-green)] border-[var(--dg-green)]/30">健康</Badge>
: <Badge className="bg-[var(--dg-orange)]/20 text-[var(--dg-orange)] border-[var(--dg-orange)]/30">更新中</Badge>}
? <Badge className="bg-[var(--dg-green)]/20 text-[var(--dg-green)] border-[var(--dg-green)]/30">{t('common.healthy')}</Badge>
: <Badge className="bg-[var(--dg-orange)]/20 text-[var(--dg-orange)] border-[var(--dg-orange)]/30">{t('kubernetes.workloadviewpage.sf339d4')}</Badge>}
</div>
{!loading && (mode === 'yaml' ? (
@@ -251,21 +255,21 @@ export default function WorkloadViewPage() {
<div className="grid grid-cols-2 md:grid-cols-4 lg:grid-cols-6 gap-3">
{isSts ? (
<>
<StatCard label="副本就绪" value={`${readyReplicas}/${replicas}`} color={isHealthy ? STATUS_COLORS.green : STATUS_COLORS.orange} sub={isHealthy ? '全部就绪' : '部分未就绪'} />
<StatCard label="当前副本" value={currentReplicas} color={STATUS_COLORS.blue} />
<StatCard label="已更新副本" value={updatedReplicas} color={STATUS_COLORS.green} />
<StatCard label="服务名" value={spec.serviceName || '-'} color="var(--dg-text-secondary)" />
<StatCard label="Pod 数量" value={pods.length} color="var(--dg-text-secondary)" />
<StatCard label="创建时间" value={<span className="text-xs">{formatK8sTime(manifest?.metadata?.creationTimestamp)}</span>} color="var(--dg-text-secondary)" />
<StatCard label=t('kubernetes.workloadviewpage.sea6396') value={`${readyReplicas}/${replicas}`} color={isHealthy ? STATUS_COLORS.green : STATUS_COLORS.orange} sub={isHealthy ? t('kubernetes.workloadviewpage.s23c944') : t('kubernetes.workloadviewpage.sac1002')} />
<StatCard label=t('kubernetes.hpa.currentReplicas') value={currentReplicas} color={STATUS_COLORS.blue} />
<StatCard label=t('kubernetes.deployment.updatedReplicas') value={updatedReplicas} color={STATUS_COLORS.green} />
<StatCard label=t('kubernetes.workloadviewpage.sf592ef') value={spec.serviceName || '-'} color="var(--dg-text-secondary)" />
<StatCard label=t('kubernetes.workloadviewpage.s55edf2') value={pods.length} color="var(--dg-text-secondary)" />
<StatCard label=t('common.createdAt') value={<span className="text-xs">{formatK8sTime(manifest?.metadata?.creationTimestamp)}</span>} color="var(--dg-text-secondary)" />
</>
) : (
<>
<StatCard label="期望调度" value={desiredScheduled} color={STATUS_COLORS.blue} />
<StatCard label="当前调度" value={currentScheduled} color="var(--dg-text-secondary)" />
<StatCard label="就绪数量" value={numberReady} color={isHealthy ? STATUS_COLORS.green : STATUS_COLORS.orange} />
<StatCard label="可用数量" value={numberAvailable} color={STATUS_COLORS.green} />
<StatCard label="已更新" value={numberUpdated} color="var(--dg-text-secondary)" />
<StatCard label="创建时间" value={<span className="text-xs">{formatK8sTime(manifest?.metadata?.creationTimestamp)}</span>} color="var(--dg-text-secondary)" />
<StatCard label=t('kubernetes.workloadviewpage.sd78bc8') value={desiredScheduled} color={STATUS_COLORS.blue} />
<StatCard label=t('kubernetes.workloadviewpage.sb76164') value={currentScheduled} color="var(--dg-text-secondary)" />
<StatCard label=t('kubernetes.daemonset.numberReady') value={numberReady} color={isHealthy ? STATUS_COLORS.green : STATUS_COLORS.orange} />
<StatCard label=t('kubernetes.daemonset.numberAvailable') value={numberAvailable} color={STATUS_COLORS.green} />
<StatCard label=t('deploy.toast.updated') value={numberUpdated} color="var(--dg-text-secondary)" />
<StatCard label=t('common.createdAt') value={<span className="text-xs">{formatK8sTime(manifest?.metadata?.creationTimestamp)}</span>} color="var(--dg-text-secondary)" />
</>
)}
</div>
@@ -280,18 +284,18 @@ export default function WorkloadViewPage() {
</CardHeader>
<CardContent className="pt-0 space-y-2 text-xs">
<div className="flex justify-between">
<span className="text-[var(--dg-text-muted)]">策略类型</span>
<span className="text-[var(--dg-text-muted)]">{t('kubernetes.workloadviewpage.s0511a2')}</span>
<Badge variant="outline" className="border-[var(--dg-border)] text-[var(--dg-text-secondary)]">{strategyType}</Badge>
</div>
{strategyType === 'RollingUpdate' && isSts && updateStrategy.rollingUpdate && (
<>
<div className="flex justify-between">
<span className="text-[var(--dg-text-muted)]">分区 (partition)</span>
<span className="text-[var(--dg-text-muted)]">{t('kubernetes.workloadviewpage.s45cb9d')}</span>
<span className="text-[var(--dg-text-secondary)] font-mono">{updateStrategy.rollingUpdate.partition ?? 0}</span>
</div>
{updateStrategy.rollingUpdate.maxUnavailable && (
<div className="flex justify-between">
<span className="text-[var(--dg-text-muted)]">最大不可用</span>
<span className="text-[var(--dg-text-muted)]">{t('kubernetes.daemonset.maxUnavailable')}</span>
<span className="text-[var(--dg-text-secondary)] font-mono">{typeof updateStrategy.rollingUpdate.maxUnavailable === 'object' ? JSON.stringify(updateStrategy.rollingUpdate.maxUnavailable) : updateStrategy.rollingUpdate.maxUnavailable}</span>
</div>
)}
@@ -301,13 +305,13 @@ export default function WorkloadViewPage() {
<>
{updateStrategy.rollingUpdate.maxUnavailable && (
<div className="flex justify-between">
<span className="text-[var(--dg-text-muted)]">最大不可用</span>
<span className="text-[var(--dg-text-muted)]">{t('kubernetes.daemonset.maxUnavailable')}</span>
<span className="text-[var(--dg-text-secondary)] font-mono">{typeof updateStrategy.rollingUpdate.maxUnavailable === 'object' ? JSON.stringify(updateStrategy.rollingUpdate.maxUnavailable) : updateStrategy.rollingUpdate.maxUnavailable}</span>
</div>
)}
{updateStrategy.rollingUpdate.maxSurge && (
<div className="flex justify-between">
<span className="text-[var(--dg-text-muted)]">最大 surge</span>
<span className="text-[var(--dg-text-muted)]">{t('kubernetes.workloadviewpage.sfed4ce')}</span>
<span className="text-[var(--dg-text-secondary)] font-mono">{typeof updateStrategy.rollingUpdate.maxSurge === 'object' ? JSON.stringify(updateStrategy.rollingUpdate.maxSurge) : updateStrategy.rollingUpdate.maxSurge}</span>
</div>
)}
@@ -315,12 +319,12 @@ export default function WorkloadViewPage() {
)}
{isSts && (
<div className="flex justify-between">
<span className="text-[var(--dg-text-muted)]">Pod 管理策略</span>
<span className="text-[var(--dg-text-muted)]">{t('kubernetes.statefulset.podManagementPolicy')}</span>
<span className="text-[var(--dg-text-secondary)] font-mono">{spec.podManagementPolicy || 'OrderedReady'}</span>
</div>
)}
<div className="flex justify-between">
<span className="text-[var(--dg-text-muted)]">修订历史限制</span>
<span className="text-[var(--dg-text-muted)]">{t('kubernetes.workloadviewpage.s450a4e')}</span>
<span className="text-[var(--dg-text-secondary)] font-mono">{spec.revisionHistoryLimit ?? 10}</span>
</div>
</CardContent>
@@ -369,10 +373,10 @@ export default function WorkloadViewPage() {
<Table>
<TableHeader>
<TableRow className="border-[var(--dg-border)] hover:bg-transparent">
<TableHead className="text-[var(--dg-text-secondary)]">名称</TableHead>
<TableHead className="text-[var(--dg-text-secondary)]">访问模式</TableHead>
<TableHead className="text-[var(--dg-text-secondary)]">存储类</TableHead>
<TableHead className="text-[var(--dg-text-secondary)]">大小</TableHead>
<TableHead className="text-[var(--dg-text-secondary)]">{t('common.name')}</TableHead>
<TableHead className="text-[var(--dg-text-secondary)]">{t('k8s.resource.accessMode')}</TableHead>
<TableHead className="text-[var(--dg-text-secondary)]">{t('k8s.resource.storageClass')}</TableHead>
<TableHead className="text-[var(--dg-text-secondary)]">{t('deploy.table.size')}</TableHead>
</TableRow>
</TableHeader>
<TableBody>
@@ -414,7 +418,7 @@ export default function WorkloadViewPage() {
</div>
)}
{containers.length === 0 ? (
<p className="text-xs text-[var(--dg-text-muted)] py-3">暂无容器数据,请查看 YAML</p>
<p className="text-xs text-[var(--dg-text-muted)] py-3">{t('kubernetes.workloadviewpage.se4b610')}</p>
) : (
<div className="space-y-3">
<p className="text-[11px] text-[var(--dg-text-muted)] mb-1 uppercase tracking-wide">Containers</p>
@@ -437,17 +441,17 @@ export default function WorkloadViewPage() {
<Table>
<TableHeader>
<TableRow className="border-[var(--dg-border)] hover:bg-transparent">
<TableHead className="text-[var(--dg-text-secondary)]">Pod 名称</TableHead>
<TableHead className="text-[var(--dg-text-secondary)]">状态</TableHead>
<TableHead className="text-[var(--dg-text-secondary)]">所在节点</TableHead>
<TableHead className="text-[var(--dg-text-secondary)]">{t('kubernetes.pod.podName')}</TableHead>
<TableHead className="text-[var(--dg-text-secondary)]">{t('common.status')}</TableHead>
<TableHead className="text-[var(--dg-text-secondary)]">{t('kubernetes.pod.nodeName')}</TableHead>
<TableHead className="text-[var(--dg-text-secondary)]">Pod IP</TableHead>
<TableHead className="text-[var(--dg-text-secondary)]">重启</TableHead>
<TableHead className="text-[var(--dg-text-secondary)]">操作</TableHead>
<TableHead className="text-[var(--dg-text-secondary)]">{t('common.reboot')}</TableHead>
<TableHead className="text-[var(--dg-text-secondary)]">{t('common.actions')}</TableHead>
</TableRow>
</TableHeader>
<TableBody>
{pods.length === 0 ? (
<TableRow><TableCell colSpan={6} className="text-center text-[var(--dg-text-muted)] py-8">暂无 Pod</TableCell></TableRow>
<TableRow><TableCell colSpan={6} className="text-center text-[var(--dg-text-muted)] py-8">{t('k8s.deploymentDetail.noPod')}</TableCell></TableRow>
) : pods.map((pod: JsonData) => (
<TableRow key={pod.name} className="border-[var(--dg-border)] hover:bg-[var(--dg-bg-tertiary)]/30">
<TableCell className="font-medium text-[var(--dg-text-primary)]">{pod.name}</TableCell>
@@ -484,7 +488,7 @@ export default function WorkloadViewPage() {
{scaleModal && (
<div className="fixed inset-0 bg-black/60 z-50 flex items-center justify-center" onClick={() => setScaleModal(false)}>
<div className="bg-[var(--dg-bg-secondary)] border border-[var(--dg-border)] rounded-lg p-6 w-80" onClick={e => e.stopPropagation()}>
<h3 className="text-sm font-semibold text-[var(--dg-text-primary)] mb-4">伸缩 StatefulSet</h3>
<h3 className="text-sm font-semibold text-[var(--dg-text-primary)] mb-4">{t('kubernetes.workloadviewpage.s7f541e')}</h3>
<div className="flex items-center justify-center gap-4 mb-4">
<Button variant="outline" size="icon" className="h-9 w-9" onClick={() => setScaleValue(Math.max(0, scaleValue - 1))}>
<Minus className="h-4 w-4" />
@@ -495,9 +499,9 @@ export default function WorkloadViewPage() {
</Button>
</div>
<div className="flex gap-2">
<Button variant="outline" size="sm" className="flex-1 border-[var(--dg-border)] text-[var(--dg-text-secondary)]" onClick={() => setScaleModal(false)}>取消</Button>
<Button variant="outline" size="sm" className="flex-1 border-[var(--dg-border)] text-[var(--dg-text-secondary)]" onClick={() => setScaleModal(false)}>{t('common.cancel')}</Button>
<Button size="sm" className="flex-1 bg-[var(--dg-blue)] hover:opacity-90" disabled={actionLoading} onClick={handleScale}>
{actionLoading ? '执行中...' : '确认'}
{actionLoading ? t('pipeline.executing') : t('common.confirm')}
</Button>
</div>
</div>
@@ -544,6 +548,7 @@ export default function WorkloadViewPage() {
// Container info sub-component
function ContainerInfo({ c }: { c: JsonData}) {
const { t } = useTranslation();
return (
<div className="border border-[var(--dg-border)] rounded-lg p-3 bg-[var(--dg-bg-primary)]/30">
<div className="flex items-center justify-between mb-2">
@@ -7,6 +7,7 @@ import { useToast } from '@/hooks/use-toast';
import { kubernetesApi } from '@/api';
import { YamlCodeMirror } from './YamlCodeMirror';
import type { JsonData } from '@/types/common';
import { useTranslation } from 'react-i18next';
interface YamlImportDialogProps {
clusterCode: string;
@@ -15,23 +16,24 @@ interface YamlImportDialogProps {
}
export function YamlImportDialog({ clusterCode, onClose, onApplied }: YamlImportDialogProps) {
const { t } = useTranslation();
const { toast } = useToast();
const [content, setContent] = useState('');
const [applying, setApplying] = useState(false);
const apply = async () => {
if (!content.trim()) {
toast({ title: '请输入 YAML', variant: 'destructive' });
toast({ title: t('kubernetes.yamlimportdialog.s81d637'), variant: 'destructive' });
return;
}
setApplying(true);
try {
await kubernetesApi.applyYAML(clusterCode, content);
toast({ title: '导入成功', description: 'YAML 已应用到集群' });
toast({ title: t('system.importSuccess'), description: t('kubernetes.yamlimportdialog.sb66e8e') });
onApplied?.();
onClose();
} catch (e) {
toast({ title: '导入失败', description: (e as JsonData).message, variant: 'destructive' });
toast({ title: t('common.importFailed'), description: (e as JsonData).message, variant: 'destructive' });
} finally { setApplying(false); }
};
@@ -45,8 +47,8 @@ export function YamlImportDialog({ clusterCode, onClose, onApplied }: YamlImport
<div className="flex items-center gap-2">
<Upload className="h-5 w-5 text-[var(--dg-text-muted)]" />
<div>
<h2 className="text-lg font-bold text-[var(--dg-text-primary)]">导入 YAML</h2>
<p className="text-xs text-[var(--dg-text-muted)]">支持多文档(--- 分隔),适用于新建或更新资源</p>
<h2 className="text-lg font-bold text-[var(--dg-text-primary)]">{t('kubernetes.yaml.importYaml')}</h2>
<p className="text-xs text-[var(--dg-text-muted)]">{t('kubernetes.yamlimportdialog.s92b733')}</p>
</div>
</div>
<Button variant="ghost" size="icon" className="h-8 w-8" onClick={onClose}><X className="h-4 w-4" /></Button>
@@ -60,7 +62,7 @@ export function YamlImportDialog({ clusterCode, onClose, onApplied }: YamlImport
/>
</div>
<div className="flex justify-end gap-2 p-4 border-t border-[var(--dg-border)] shrink-0">
<Button variant="outline" onClick={onClose}>取消</Button>
<Button variant="outline" onClick={onClose}>{t('common.cancel')}</Button>
<Button className="bg-blue-600 hover:bg-blue-700" onClick={apply} disabled={applying}>
{applying ? <Loader2 className="h-4 w-4 animate-spin mr-1" /> : <Upload className="h-4 w-4 mr-1" />}
应用
@@ -11,6 +11,7 @@ import { YamlEditorToolbar } from './YamlEditorToolbar';
import { YamlCodeMirror } from './YamlCodeMirror';
import { downloadYamlFile } from '@/utils/export';
import type { JsonData } from '@/types/common';
import { useTranslation } from 'react-i18next';
interface YamlViewerProps {
clusterCode: string;
@@ -37,6 +38,7 @@ export function YamlViewer({
autoEdit = false, inline = false, initialYaml, readOnly: readOnlyProp,
loadYamlFn, saveYamlFn, resourceHint,
}: YamlViewerProps) {
const { t } = useTranslation();
const { toast } = useToast();
const resCfg = getYamlResourceConfig(resource);
const readOnly = readOnlyProp ?? resCfg.readOnly;
@@ -73,7 +75,7 @@ export function YamlViewer({
setRawYaml(text);
await applyStripped(text);
} catch (e) {
toast({ title: '获取YAML失败', description: (e as JsonData).message, variant: 'destructive' });
toast({ title: t('kubernetes.yamlviewer.s1a72e3'), description: (e as JsonData).message, variant: 'destructive' });
const err = `# Error: ${(e as Error).message}`;
setRawYaml(err);
setDisplayYaml(err);
@@ -103,14 +105,14 @@ export function YamlViewer({
} else {
await kubernetesApi.updateResourceYaml(clusterCode, namespace, resource, name, yamlStr);
}
toast({ title: '保存成功', description: saveYamlFn ? '多文档 YAML 已应用' : `${resource}/${name} 已更新` });
toast({ title: t('common.savedSuccessfully'), description: saveYamlFn ? t('kubernetes.yamlviewer.s68f258') : t('kubernetes.yamlviewer.se7e1ac', { resource: resource, name: name }) });
setEditing(false);
setRawYaml(yamlStr);
setDisplayYaml(yamlStr);
setEditYaml(yamlStr);
onSaved?.();
} catch (e) {
toast({ title: '保存失败', description: (e as Error)?.message || String(e), variant: 'destructive' });
toast({ title: t('common.saveFailed'), description: (e as Error)?.message || String(e), variant: 'destructive' });
} finally { setSaving(false); }
};
@@ -124,7 +126,7 @@ export function YamlViewer({
const downloadYaml = () => {
downloadYamlFile(yamlDownloadFilename(resource, namespace, name), currentYaml());
toast({ title: '已下载', description: yamlDownloadFilename(resource, namespace, name) });
toast({ title: t('kubernetes.yamlviewer.s9719fe'), description: yamlDownloadFilename(resource, namespace, name) });
};
const display = editing ? editYaml : (showRaw ? rawYaml : displayYaml);
@@ -186,7 +188,7 @@ export function YamlViewer({
<div className="min-w-0 flex-1">
<h2 className="text-lg font-bold text-[var(--dg-text-primary)] truncate" title={`${resCfg.label} YAML — ${name}`}>
{resCfg.label} YAML — {name}
{readOnly && <span className="ml-2 text-xs font-normal dg-text-muted">只读</span>}
{readOnly && <span className="ml-2 text-xs font-normal dg-text-muted">{t('common.readonly')}</span>}
</h2>
<p className="text-xs dg-text-muted truncate" title={`${namespace} · ${clusterCode}`}>{namespace} · {clusterCode}</p>
</div>
@@ -2,6 +2,7 @@
// Deployment 多文档 YAML(Deployment + 关联 Service)加载与保存 // Logan.Li
import { kubernetesApi } from '@/api';
import {
import i18n from '@/i18n';
manifestToEditableYaml,
parseEditableManifest,
parseEditableManifests,
@@ -80,12 +81,12 @@ export async function saveDeploymentBundleYaml(
yamlText: string,
): Promise<void> {
const { manifests } = await parseEditableManifests(yamlText);
if (manifests.length === 0) throw new Error('YAML 内容为空或解析失败');
if (manifests.length === 0) throw new Error(i18n.t('kubernetes.deploymentBundleYaml.s47161e'));
for (const manifest of manifests) {
const kind = String(manifest.kind || '').toLowerCase();
const name = String(manifest.metadata?.name || '').trim();
if (!kind || !name) throw new Error('每个 YAML 文档必须包含 kind 和 metadata.name');
if (!kind || !name) throw new Error(i18n.t('kubernetes.deploymentBundleYaml.s659c1b'));
const docYaml = await prepareManifestForSave(manifest);
if (kind === 'deployment') {
@@ -96,6 +97,6 @@ export async function saveDeploymentBundleYaml(
await kubernetesApi.applyYAML(clusterCode, docYaml);
continue;
}
throw new Error(`不支持的资源类型: ${manifest.kind}(仅支持 Deployment / Service)`);
throw new Error(i18n.t('kubernetes.deploymentBundleYaml.s94a65d', { manifest.kind: manifest.kind }));
}
}
@@ -6,6 +6,7 @@ import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { kubernetesApi } from '@/api';
import { useToast } from '@/hooks/use-toast';
import { useTranslation } from 'react-i18next';
export interface CreateHPADialogProps {
clusterCode: string;
@@ -15,6 +16,7 @@ export interface CreateHPADialogProps {
}
export function CreateHPADialog({ clusterCode, namespace, deploymentName, onCreated }: CreateHPADialogProps) {
const { t } = useTranslation();
const { toast } = useToast();
const [open, setOpen] = useState(false);
const [loading, setLoading] = useState(false);
@@ -28,7 +30,7 @@ export function CreateHPADialog({ clusterCode, namespace, deploymentName, onCrea
const handleCreate = async () => {
if (!form.name.trim()) {
toast({ title: '名称不能为空', variant: 'destructive' });
toast({ title: t('kubernetes.createhpadialog.sdf09ff'), variant: 'destructive' });
return;
}
setLoading(true);
@@ -43,12 +45,12 @@ export function CreateHPADialog({ clusterCode, namespace, deploymentName, onCrea
cpuPercent: form.cpuPercent,
memPercent: form.memPercent,
});
toast({ title: 'HPA 创建成功' });
toast({ title: t('kubernetes.createhpadialog.s74b0b0') });
setOpen(false);
onCreated();
setForm({ name: '', minReplicas: 1, maxReplicas: 10, cpuPercent: 80, memPercent: 0 });
} catch (e: any) {
toast({ title: '创建失败', description: e?.message || String(e), variant: 'destructive' });
toast({ title: t('monitor.quickSetupFailed'), description: e?.message || String(e), variant: 'destructive' });
} finally { setLoading(false); }
};
@@ -60,29 +62,29 @@ export function CreateHPADialog({ clusterCode, namespace, deploymentName, onCrea
{open && (
<div className="fixed inset-0 z-50 flex items-center justify-center bg-black/60 p-4" onClick={() => setOpen(false)}>
<div className="bg-[var(--dg-bg-secondary)] border border-[var(--dg-border)] rounded-xl w-[480px] max-w-[92vw] max-h-[85vh] flex flex-col" onClick={(e) => e.stopPropagation()}>
<h2 className="text-lg font-bold text-[var(--dg-text-primary)] px-6 pt-6 pb-4 shrink-0">创建 HPA</h2>
<h2 className="text-lg font-bold text-[var(--dg-text-primary)] px-6 pt-6 pb-4 shrink-0">{t('k8s.hpaCronHpa.createHpa')}</h2>
<div className="flex-1 min-h-0 overflow-y-auto px-6 space-y-3">
<div>
<Label className="dg-text-secondary text-sm">名称</Label>
<Label className="dg-text-secondary text-sm">{t('common.name')}</Label>
<Input value={form.name} onChange={(e) => setForm({ ...form, name: e.target.value })}
placeholder={`hpa-${deploymentName}`}
className="dg-input mt-1" />
</div>
<div>
<Label className="dg-text-secondary text-sm">目标</Label>
<p className="text-[var(--dg-text-secondary)] text-sm mt-1 bg-[var(--dg-bg-tertiary)] rounded px-3 py-2 truncate" title={`Deployment: ${deploymentName} · 命名空间: ${namespace}`}>
<Label className="dg-text-secondary text-sm">{t('common.target')}</Label>
<p className="text-[var(--dg-text-secondary)] text-sm mt-1 bg-[var(--dg-bg-tertiary)] rounded px-3 py-2 truncate" title={t('kubernetes.createhpadialog.s7aa398', { deploymentName: deploymentName, namespace: namespace })}>
Deployment: {deploymentName} · 命名空间: {namespace}
</p>
</div>
<div className="grid grid-cols-2 gap-3">
<div>
<Label className="dg-text-secondary text-sm">最小副本数</Label>
<Label className="dg-text-secondary text-sm">{t('kubernetes.createhpadialog.s6a5bed')}</Label>
<Input type="number" value={form.minReplicas} min={1}
onChange={(e) => setForm({ ...form, minReplicas: Number(e.target.value) })}
className="dg-input mt-1" />
</div>
<div>
<Label className="dg-text-secondary text-sm">最大副本数</Label>
<Label className="dg-text-secondary text-sm">{t('kubernetes.createhpadialog.sc3f2cf')}</Label>
<Input type="number" value={form.maxReplicas} min={1}
onChange={(e) => setForm({ ...form, maxReplicas: Number(e.target.value) })}
className="dg-input mt-1" />
@@ -90,13 +92,13 @@ export function CreateHPADialog({ clusterCode, namespace, deploymentName, onCrea
</div>
<div className="grid grid-cols-2 gap-3">
<div>
<Label className="dg-text-secondary text-sm">CPU 目标 (%)</Label>
<Label className="dg-text-secondary text-sm">{t('kubernetes.createhpadialog.s94bfd4')}</Label>
<Input type="number" value={form.cpuPercent} min={0} max={100}
onChange={(e) => setForm({ ...form, cpuPercent: Number(e.target.value) })}
className="dg-input mt-1" />
</div>
<div>
<Label className="dg-text-secondary text-sm">内存目标 (%) <span className="dg-text-muted">可选</span></Label>
<Label className="dg-text-secondary text-sm">{t('kubernetes.createhpadialog.s82f202')} <span className="dg-text-muted">{t('common.optional')}</span></Label>
<Input type="number" value={form.memPercent} min={0} max={100}
onChange={(e) => setForm({ ...form, memPercent: Number(e.target.value) })}
className="dg-input mt-1" />
@@ -104,9 +106,9 @@ export function CreateHPADialog({ clusterCode, namespace, deploymentName, onCrea
</div>
</div>
<div className="flex justify-end gap-2 px-6 py-4 border-t border-[var(--dg-border)] shrink-0">
<Button variant="outline" className="border-[var(--dg-border)] dg-text-secondary" onClick={() => setOpen(false)}>取消</Button>
<Button variant="outline" className="border-[var(--dg-border)] dg-text-secondary" onClick={() => setOpen(false)}>{t('common.cancel')}</Button>
<Button className="bg-blue-600 hover:bg-blue-700" disabled={loading} onClick={handleCreate}>
{loading ? <Loader2 className="h-4 w-4 animate-spin" /> : '创建'}
{loading ? <Loader2 className="h-4 w-4 animate-spin" /> : i18n.t('common.create')}
</Button>
</div>
</div>
@@ -8,6 +8,7 @@ import { Input } from '@/components/ui/input';
import { Badge } from '@/components/ui/badge';
import { CreateHPADialog } from './CreateHPADialog';
import type { JsonData } from '@/types/common';
import { useTranslation } from 'react-i18next';
export interface DeploymentOverviewProps {
deploymentName: string;
@@ -37,6 +38,7 @@ export function DeploymentOverview({
newImage, showImageUpdate, onBack, onRefresh, onScale, onRestart,
onNewImageChange, onToggleImageUpdate, onUpdateImage,
}: DeploymentOverviewProps) {
const { t } = useTranslation();
return (
<>
<div className="flex items-center justify-between">
@@ -60,7 +62,7 @@ export function DeploymentOverview({
<div className="grid grid-cols-2 md:grid-cols-4 gap-3">
<Card className="dg-card">
<CardContent className="p-3">
<p className="text-xs dg-text-muted">副本状态</p>
<p className="text-xs dg-text-muted">{t('kubernetes.deploymentoverview.sb4cac1')}</p>
<p className={`text-lg font-bold ${isHealthy ? 'dg-text-green' : 'dg-text-yellow'}`}>
{ready}/{total}
</p>
@@ -68,13 +70,13 @@ export function DeploymentOverview({
</Card>
<Card className="dg-card">
<CardContent className="p-3">
<p className="text-xs dg-text-muted">可用副本</p>
<p className="text-xs dg-text-muted">{t('k8s.column.availableReplicas')}</p>
<p className="text-lg font-bold dg-text-blue">{available}</p>
</CardContent>
</Card>
<Card className="dg-card">
<CardContent className="p-3">
<p className="text-xs dg-text-muted">镜像</p>
<p className="text-xs dg-text-muted">{t('k8s.column.image')}</p>
<p className="text-sm font-mono text-[var(--dg-text-secondary)] truncate max-w-[200px]" title={deployment.image}>
{deployment.image?.split('/').pop() || '-'}
</p>
@@ -84,10 +86,10 @@ export function DeploymentOverview({
<CardContent className="p-3">
<p className="text-xs dg-text-muted">HPA</p>
{hpas.length > 0 ? (
<p className="text-lg font-bold dg-text-purple">已启用</p>
<p className="text-lg font-bold dg-text-purple">{t('alert.enabled')}</p>
) : (
<div className="flex items-center justify-between">
<p className="text-lg font-bold dg-text-muted">未配置</p>
<p className="text-lg font-bold dg-text-muted">{t('k8s.dnsHost.notConfigured')}</p>
<CreateHPADialog
clusterCode={clusterCode}
namespace={namespace}
@@ -102,7 +104,7 @@ export function DeploymentOverview({
<Card className="dg-card">
<CardHeader className="pb-3">
<CardTitle className="text-base text-[var(--dg-text-primary)]">操作</CardTitle>
<CardTitle className="text-base text-[var(--dg-text-primary)]">{t('common.actions')}</CardTitle>
</CardHeader>
<CardContent>
<div className="flex flex-wrap items-center gap-3">
@@ -146,16 +148,16 @@ export function DeploymentOverview({
<Input
value={newImage}
onChange={(e) => onNewImageChange(e.target.value)}
placeholder="输入新镜像地址,如 harbor.example.com/app:v2.0"
placeholder=t('kubernetes.deploymentoverview.s416d7e')
className="flex-1 h-9 dg-input text-[var(--dg-text-primary)] text-sm font-mono"
/>
<Button size="sm" className="bg-blue-600 hover:bg-blue-700"
disabled={actionLoading === 'image' || !newImage.trim()}
onClick={onUpdateImage}
>
{actionLoading === 'image' ? <Loader2 className="h-4 w-4 animate-spin" /> : '更新'}
{actionLoading === 'image' ? <Loader2 className="h-4 w-4 animate-spin" /> : t('common.update')}
</Button>
<Button variant="ghost" size="sm" className="dg-text-secondary" onClick={onToggleImageUpdate}>取消</Button>
<Button variant="ghost" size="sm" className="dg-text-secondary" onClick={onToggleImageUpdate}>{t('common.cancel')}</Button>
</div>
)}
</CardContent>
@@ -22,11 +22,13 @@ import {
import { arrToText, textToArr } from './container-utils';
import type {
import { useTranslation } from 'react-i18next';
ContainerEditorProps, ProbeEditorProps, LifecycleHandlerEditorProps,
BoolToggleProps, ProbeDef, LifecycleHandler,
} from './types';
export function ContainerEditor({ container, onUpdate }: ContainerEditorProps) {
const { t } = useTranslation();
const c = container;
const sectionBtn = "flex items-center gap-1.5 text-xs font-semibold text-[var(--dg-text-secondary)] mb-2";
@@ -35,25 +37,25 @@ export function ContainerEditor({ container, onUpdate }: ContainerEditorProps) {
{/* ---- 基本设置 ---- */}
<div className="grid grid-cols-1 md:grid-cols-2 gap-3">
<div>
<Label className="dg-text-secondary text-xs">容器名称</Label>
<Label className="dg-text-secondary text-xs">{t('kubernetes.containereditor.sa51cd0')}</Label>
<Input value={c.name} onChange={e => onUpdate({ name: e.target.value })}
placeholder="my-app"
className="mt-1 dg-input font-mono text-xs h-8" />
</div>
<div>
<Label className="dg-text-secondary text-xs">容器镜像</Label>
<Label className="dg-text-secondary text-xs">{t('kubernetes.containereditor.s332ca5')}</Label>
<Input value={c.image} onChange={e => onUpdate({ image: e.target.value })}
placeholder="nginx:1.25"
className="mt-1 dg-input font-mono text-xs h-8" />
</div>
<div>
<Label className="dg-text-secondary text-xs">镜像拉取策略</Label>
<Label className="dg-text-secondary text-xs">{t('kubernetes.deployment.imagePullPolicy')}</Label>
<Select value={c.imagePullPolicy || '__none'} onValueChange={v => onUpdate({ imagePullPolicy: v === '__none' ? '' : v })}>
<SelectTrigger className="mt-1 dg-input text-xs h-8">
<SelectValue />
</SelectTrigger>
<SelectContent className="dg-input">
<SelectItem value="__none" className="dg-text-secondary">不设置(默认 IfNotPresent)</SelectItem>
<SelectItem value="__none" className="dg-text-secondary">{t('kubernetes.containereditor.sd2f3ee')}</SelectItem>
<SelectItem value="Always" className="text-[var(--dg-text-primary)]">Always</SelectItem>
<SelectItem value="IfNotPresent" className="text-[var(--dg-text-primary)]">IfNotPresent</SelectItem>
<SelectItem value="Never" className="text-[var(--dg-text-primary)]">Never</SelectItem>
@@ -61,7 +63,7 @@ export function ContainerEditor({ container, onUpdate }: ContainerEditorProps) {
</Select>
</div>
<div>
<Label className="dg-text-secondary text-xs">工作目录 (workingDir)</Label>
<Label className="dg-text-secondary text-xs">{t('kubernetes.containereditor.s4867b9')}</Label>
<Input value={c.workingDir || ''} onChange={e => onUpdate({ workingDir: e.target.value })}
placeholder="/app"
className="mt-1 dg-input font-mono text-xs h-8" />
@@ -71,13 +73,13 @@ export function ContainerEditor({ container, onUpdate }: ContainerEditorProps) {
{/* ---- 命令与参数 ---- */}
<div className="grid grid-cols-1 md:grid-cols-2 gap-3">
<div>
<Label className="dg-text-secondary text-xs">启动命令 (command) — 每行一个</Label>
<Label className="dg-text-secondary text-xs">{t('kubernetes.containereditor.s34ab0f')}</Label>
<Textarea value={arrToText(c.command)} placeholder={"/bin/sh\n-c"}
onChange={e => onUpdate({ command: textToArr(e.target.value) })}
className="mt-1 dg-input font-mono text-xs min-h-[60px]" />
</div>
<div>
<Label className="dg-text-secondary text-xs">启动参数 (args) — 每行一个</Label>
<Label className="dg-text-secondary text-xs">{t('kubernetes.containereditor.s6dd286')}</Label>
<Textarea value={arrToText(c.args)} placeholder={"--config=/etc/app.yaml\n--debug"}
onChange={e => onUpdate({ args: textToArr(e.target.value) })}
className="mt-1 dg-input font-mono text-xs min-h-[60px]" />
@@ -87,7 +89,7 @@ export function ContainerEditor({ container, onUpdate }: ContainerEditorProps) {
{/* ---- 环境变量 ---- */}
<div>
<div className="flex items-center justify-between mb-2">
<div className={sectionBtn}><Terminal className="h-3.5 w-3.5 dg-text-cyan" /> 环境变量</div>
<div className={sectionBtn}><Terminal className="h-3.5 w-3.5 dg-text-cyan" /> {t('pipeline.envVar')}</div>
<Button size="sm" variant="outline" className="h-6 border-[var(--dg-border)] text-[var(--dg-text-secondary)] text-[11px]"
onClick={() => onUpdate({ env: [...c.env, { name: '', value: '' }] })}>
<Plus className="h-3 w-3 mr-1" />新增
@@ -108,14 +110,14 @@ export function ContainerEditor({ container, onUpdate }: ContainerEditorProps) {
</Button>
</div>
))}
{c.env.length === 0 && <p className="text-[11px] dg-text-muted">无环境变量</p>}
{c.env.length === 0 && <p className="text-[11px] dg-text-muted">{t('kubernetes.containereditor.s9f809d')}</p>}
</div>
</div>
{/* ---- 端口 ---- */}
<div>
<div className="flex items-center justify-between mb-2">
<div className={sectionBtn}><Network className="h-3.5 w-3.5 text-indigo-400" /> 端口</div>
<div className={sectionBtn}><Network className="h-3.5 w-3.5 text-indigo-400" /> {t('server.csv.port')}</div>
<Button size="sm" variant="outline" className="h-6 border-[var(--dg-border)] text-[var(--dg-text-secondary)] text-[11px]"
onClick={() => onUpdate({ ports: [...c.ports, { name: '', containerPort: '', protocol: 'TCP' }] })}>
<Plus className="h-3 w-3 mr-1" />新增
@@ -146,34 +148,34 @@ export function ContainerEditor({ container, onUpdate }: ContainerEditorProps) {
</Button>
</div>
))}
{c.ports.length === 0 && <p className="text-[11px] dg-text-muted">无端口暴露</p>}
{c.ports.length === 0 && <p className="text-[11px] dg-text-muted">{t('kubernetes.containereditor.sbc8b87')}</p>}
</div>
</div>
{/* ---- 资源 requests/limits ---- */}
<div>
<div className={sectionBtn}><Cpu className="h-3.5 w-3.5 dg-text-yellow" /> 资源 (requests / limits)</div>
<div className={sectionBtn}><Cpu className="h-3.5 w-3.5 dg-text-yellow" /> {t('kubernetes.containereditor.s0b1499')}</div>
<div className="grid grid-cols-2 md:grid-cols-4 gap-2">
<div>
<Label className="text-[11px] dg-text-muted">CPU 请求</Label>
<Label className="text-[11px] dg-text-muted">{t('kubernetes.node.cpuRequests')}</Label>
<Input value={c.resources.requests?.cpu || ''} placeholder="100m"
onChange={e => onUpdate({ resources: { ...c.resources, requests: { ...c.resources.requests, cpu: e.target.value } } })}
className="dg-input font-mono text-xs h-8" />
</div>
<div>
<Label className="text-[11px] dg-text-muted">CPU 上限</Label>
<Label className="text-[11px] dg-text-muted">{t('kubernetes.containereditor.s96ac88')}</Label>
<Input value={c.resources.limits?.cpu || ''} placeholder="500m"
onChange={e => onUpdate({ resources: { ...c.resources, limits: { ...c.resources.limits, cpu: e.target.value } } })}
className="dg-input font-mono text-xs h-8" />
</div>
<div>
<Label className="text-[11px] dg-text-muted">内存请求</Label>
<Label className="text-[11px] dg-text-muted">{t('kubernetes.node.memoryRequests')}</Label>
<Input value={c.resources.requests?.memory || ''} placeholder="128Mi"
onChange={e => onUpdate({ resources: { ...c.resources, requests: { ...c.resources.requests, memory: e.target.value } } })}
className="dg-input font-mono text-xs h-8" />
</div>
<div>
<Label className="text-[11px] dg-text-muted">内存上限</Label>
<Label className="text-[11px] dg-text-muted">{t('kubernetes.containereditor.sa0a98f')}</Label>
<Input value={c.resources.limits?.memory || ''} placeholder="512Mi"
onChange={e => onUpdate({ resources: { ...c.resources, limits: { ...c.resources.limits, memory: e.target.value } } })}
className="dg-input font-mono text-xs h-8" />
@@ -183,11 +185,11 @@ export function ContainerEditor({ container, onUpdate }: ContainerEditorProps) {
{/* ---- 健康检查 ---- */}
<div>
<div className={sectionBtn}><Heart className="h-3.5 w-3.5 text-rose-400" /> 健康检查 (Probes)</div>
<div className={sectionBtn}><Heart className="h-3.5 w-3.5 text-rose-400" /> {t('kubernetes.containereditor.s6779ab')}</div>
<div className="space-y-2">
{(['livenessProbe', 'readinessProbe', 'startupProbe'] as const).map(pt => (
<ProbeEditor key={pt}
label={{ livenessProbe: '存活探针 (liveness)', readinessProbe: '就绪探针 (readiness)', startupProbe: '启动探针 (startup)' }[pt]}
label={{ livenessProbe: t('kubernetes.containereditor.sff49b1'), readinessProbe: t('kubernetes.containereditor.s176e68'), startupProbe: t('kubernetes.containereditor.sc5a531') }[pt]}
probe={c[pt]}
onChange={(p) => onUpdate({ [pt]: p } as Record<string, unknown>)}
/>
@@ -197,11 +199,11 @@ export function ContainerEditor({ container, onUpdate }: ContainerEditorProps) {
{/* ---- 生命周期 ---- */}
<div>
<div className={sectionBtn}><Zap className="h-3.5 w-3.5 dg-text-yellow" /> 生命周期回调 (Lifecycle)</div>
<div className={sectionBtn}><Zap className="h-3.5 w-3.5 dg-text-yellow" /> {t('kubernetes.containereditor.s12d037')}</div>
<div className="grid grid-cols-1 md:grid-cols-2 gap-3">
<LifecycleHandlerEditor label="启动后 (postStart)" handler={c.lifecycle?.postStart}
<LifecycleHandlerEditor label=t('kubernetes.containereditor.s650280') handler={c.lifecycle?.postStart}
onChange={h => onUpdate({ lifecycle: { ...c.lifecycle, postStart: h } })} />
<LifecycleHandlerEditor label="终止前 (preStop)" handler={c.lifecycle?.preStop}
<LifecycleHandlerEditor label=t('kubernetes.containereditor.s5b7228') handler={c.lifecycle?.preStop}
onChange={h => onUpdate({ lifecycle: { ...c.lifecycle, preStop: h } })} />
</div>
{!c.lifecycle && (
@@ -214,7 +216,7 @@ export function ContainerEditor({ container, onUpdate }: ContainerEditorProps) {
{/* ---- 安全上下文 ---- */}
<div>
<div className={sectionBtn}><Shield className="h-3.5 w-3.5 dg-text-green" /> 安全上下文 (SecurityContext)</div>
<div className={sectionBtn}><Shield className="h-3.5 w-3.5 dg-text-green" /> {t('kubernetes.containereditor.s195d42')}</div>
{c.securityContext ? (
<div className="space-y-2 border border-[var(--dg-border)] rounded-md p-3 bg-[var(--dg-bg-primary)]/30">
<div className="grid grid-cols-2 md:grid-cols-3 gap-2">
@@ -231,13 +233,13 @@ export function ContainerEditor({ container, onUpdate }: ContainerEditorProps) {
className="dg-input font-mono text-xs h-8" />
</div>
<div>
<Label className="text-[11px] dg-text-muted">Capabilities Add (逗号分隔)</Label>
<Label className="text-[11px] dg-text-muted">{t('kubernetes.containereditor.s3142a7')}</Label>
<Input value={(c.securityContext.capabilitiesAdd || []).join(',')} placeholder="NET_ADMIN"
onChange={e => onUpdate({ securityContext: { ...c.securityContext!, capabilitiesAdd: e.target.value.split(',').map(s => s.trim()).filter(Boolean) } })}
className="dg-input font-mono text-xs h-8" />
</div>
<div>
<Label className="text-[11px] dg-text-muted">Capabilities Drop (逗号分隔)</Label>
<Label className="text-[11px] dg-text-muted">{t('kubernetes.containereditor.sd705f3')}</Label>
<Input value={(c.securityContext.capabilitiesDrop || []).join(',')} placeholder="ALL"
onChange={e => onUpdate({ securityContext: { ...c.securityContext!, capabilitiesDrop: e.target.value.split(',').map(s => s.trim()).filter(Boolean) } })}
className="dg-input font-mono text-xs h-8" />
@@ -269,7 +271,7 @@ export function ContainerEditor({ container, onUpdate }: ContainerEditorProps) {
{/* ---- 卷挂载 ---- */}
<div>
<div className="flex items-center justify-between mb-2">
<div className={sectionBtn}><FolderOpen className="h-3.5 w-3.5 text-teal-400" /> 卷挂载 (VolumeMounts)</div>
<div className={sectionBtn}><FolderOpen className="h-3.5 w-3.5 text-teal-400" /> {t('kubernetes.containereditor.s778eec')}</div>
<Button size="sm" variant="outline" className="h-6 border-[var(--dg-border)] text-[var(--dg-text-secondary)] text-[11px]"
onClick={() => onUpdate({ volumeMounts: [...c.volumeMounts, { name: '', mountPath: '', subPath: '', readOnly: false }] })}>
<Plus className="h-3 w-3 mr-1" />新增
@@ -278,13 +280,13 @@ export function ContainerEditor({ container, onUpdate }: ContainerEditorProps) {
<div className="space-y-1.5">
{c.volumeMounts.map((m, mi) => (
<div key={mi} className="grid grid-cols-[1fr_1fr_1fr_60px_auto] gap-2 items-center">
<Input value={m.name} placeholder="volume 名称"
<Input value={m.name} placeholder=t('kubernetes.containereditor.sb19f3d')
onChange={e => { const n = [...c.volumeMounts]; n[mi] = { ...m, name: e.target.value }; onUpdate({ volumeMounts: n }); }}
className="dg-input font-mono text-xs h-8" />
<Input value={m.mountPath} placeholder="/data"
onChange={e => { const n = [...c.volumeMounts]; n[mi] = { ...m, mountPath: e.target.value }; onUpdate({ volumeMounts: n }); }}
className="dg-input font-mono text-xs h-8" />
<Input value={m.subPath || ''} placeholder="subPath (可选)"
<Input value={m.subPath || ''} placeholder=t('kubernetes.containereditor.s4f4937')
onChange={e => { const n = [...c.volumeMounts]; n[mi] = { ...m, subPath: e.target.value }; onUpdate({ volumeMounts: n }); }}
className="dg-input font-mono text-xs h-8" />
<label className="flex items-center gap-1 text-[10px] dg-text-muted cursor-pointer">
@@ -298,7 +300,7 @@ export function ContainerEditor({ container, onUpdate }: ContainerEditorProps) {
</Button>
</div>
))}
{c.volumeMounts.length === 0 && <p className="text-[11px] dg-text-muted">无卷挂载</p>}
{c.volumeMounts.length === 0 && <p className="text-[11px] dg-text-muted">{t('kubernetes.containereditor.s9b6826')}</p>}
</div>
</div>
</>
@@ -306,6 +308,7 @@ export function ContainerEditor({ container, onUpdate }: ContainerEditorProps) {
}
function ProbeEditor({ label, probe, onChange }: ProbeEditorProps) {
const { t } = useTranslation();
const enabled = !!probe;
const p = probe || { type: 'httpGet' as const };
@@ -321,7 +324,7 @@ function ProbeEditor({ label, probe, onChange }: ProbeEditorProps) {
{enabled && (
<>
<div className="flex items-center gap-2 mb-2">
<span className="text-[10px] dg-text-muted w-8">类型</span>
<span className="text-[10px] dg-text-muted w-8">{t('common.type')}</span>
<Select value={p.type || 'httpGet'} onValueChange={v => setField({ type: v as ProbeDef['type'] })}>
<SelectTrigger className="dg-input text-xs h-7 flex-1">
<SelectValue />
@@ -329,7 +332,7 @@ function ProbeEditor({ label, probe, onChange }: ProbeEditorProps) {
<SelectContent className="dg-input">
<SelectItem value="httpGet" className="text-[var(--dg-text-primary)]">HTTP GET</SelectItem>
<SelectItem value="tcpSocket" className="text-[var(--dg-text-primary)]">TCP Socket</SelectItem>
<SelectItem value="exec" className="text-[var(--dg-text-primary)]">Exec 命令</SelectItem>
<SelectItem value="exec" className="text-[var(--dg-text-primary)]">{t('kubernetes.containereditor.s16d93f')}</SelectItem>
</SelectContent>
</Select>
</div>
@@ -341,52 +344,52 @@ function ProbeEditor({ label, probe, onChange }: ProbeEditorProps) {
<Input type="number" value={p.httpPort ?? ''} placeholder="8080"
onChange={e => setField({ httpPort: e.target.value === '' ? undefined : Number(e.target.value) })}
className="dg-input font-mono text-xs h-7" />
<Input value={p.httpHost || ''} placeholder="host (可选)"
<Input value={p.httpHost || ''} placeholder=t('kubernetes.containereditor.s3cf87c')
onChange={e => setField({ httpHost: e.target.value })}
className="dg-input font-mono text-xs h-7" />
</div>
)}
{p.type === 'tcpSocket' && (
<div className="mb-2">
<Input type="number" value={p.tcpPort ?? ''} placeholder="端口"
<Input type="number" value={p.tcpPort ?? ''} placeholder=t('server.csv.port')
onChange={e => setField({ tcpPort: e.target.value === '' ? undefined : Number(e.target.value) })}
className="dg-input font-mono text-xs h-7" />
</div>
)}
{p.type === 'exec' && (
<div className="mb-2">
<Textarea value={p.execCommand || ''} placeholder="每行一个命令片段,如:\ncat\n/tmp/healthy"
<Textarea value={p.execCommand || ''} placeholder=t('kubernetes.containereditor.s743f00')
onChange={e => setField({ execCommand: e.target.value })}
className="dg-input font-mono text-xs min-h-[50px]" />
</div>
)}
<div className="grid grid-cols-5 gap-2">
<div>
<Label className="text-[10px] dg-text-muted">延迟(s)</Label>
<Label className="text-[10px] dg-text-muted">{t('kubernetes.containereditor.s39b4e6')}</Label>
<Input type="number" value={p.initialDelaySeconds ?? ''} placeholder="10"
onChange={e => setField({ initialDelaySeconds: e.target.value === '' ? undefined : Number(e.target.value) })}
className="dg-input font-mono text-xs h-7" />
</div>
<div>
<Label className="text-[10px] dg-text-muted">间隔(s)</Label>
<Label className="text-[10px] dg-text-muted">{t('kubernetes.containereditor.sbbf419')}</Label>
<Input type="number" value={p.periodSeconds ?? ''} placeholder="10"
onChange={e => setField({ periodSeconds: e.target.value === '' ? undefined : Number(e.target.value) })}
className="dg-input font-mono text-xs h-7" />
</div>
<div>
<Label className="text-[10px] dg-text-muted">超时(s)</Label>
<Label className="text-[10px] dg-text-muted">{t('kubernetes.containereditor.sde332f')}</Label>
<Input type="number" value={p.timeoutSeconds ?? ''} placeholder="1"
onChange={e => setField({ timeoutSeconds: e.target.value === '' ? undefined : Number(e.target.value) })}
className="dg-input font-mono text-xs h-7" />
</div>
<div>
<Label className="text-[10px] dg-text-muted">成功</Label>
<Label className="text-[10px] dg-text-muted">{t('common.success')}</Label>
<Input type="number" value={p.successThreshold ?? ''} placeholder="1"
onChange={e => setField({ successThreshold: e.target.value === '' ? undefined : Number(e.target.value) })}
className="dg-input font-mono text-xs h-7" />
</div>
<div>
<Label className="text-[10px] dg-text-muted">失败</Label>
<Label className="text-[10px] dg-text-muted">{t('common.failed')}</Label>
<Input type="number" value={p.failureThreshold ?? ''} placeholder="3"
onChange={e => setField({ failureThreshold: e.target.value === '' ? undefined : Number(e.target.value) })}
className="dg-input font-mono text-xs h-7" />
@@ -399,6 +402,7 @@ function ProbeEditor({ label, probe, onChange }: ProbeEditorProps) {
}
function LifecycleHandlerEditor({ label, handler, onChange }: LifecycleHandlerEditorProps) {
const { t } = useTranslation();
const h = handler || { type: 'none' as const };
const selVal = (!h.type || h.type === 'none') ? '__none' : h.type;
@@ -406,21 +410,21 @@ function LifecycleHandlerEditor({ label, handler, onChange }: LifecycleHandlerEd
<div className="border border-[var(--dg-border)] rounded-md p-2.5 bg-[var(--dg-bg-primary)]/30">
<span className="text-xs text-[var(--dg-text-secondary)] font-medium block mb-2">{label}</span>
<div className="flex items-center gap-2 mb-2">
<span className="text-[10px] dg-text-muted w-8">类型</span>
<span className="text-[10px] dg-text-muted w-8">{t('common.type')}</span>
<Select value={selVal} onValueChange={v => onChange({ ...h, type: (v === '__none' ? 'none' : v) as LifecycleHandler['type'] })}>
<SelectTrigger className="dg-input text-xs h-7 flex-1">
<SelectValue />
</SelectTrigger>
<SelectContent className="dg-input">
<SelectItem value="__none" className="dg-text-secondary">不设置</SelectItem>
<SelectItem value="exec" className="text-[var(--dg-text-primary)]">Exec 命令</SelectItem>
<SelectItem value="__none" className="dg-text-secondary">{t('kubernetes.containereditor.s2e3432')}</SelectItem>
<SelectItem value="exec" className="text-[var(--dg-text-primary)]">{t('kubernetes.containereditor.s16d93f')}</SelectItem>
<SelectItem value="httpGet" className="text-[var(--dg-text-primary)]">HTTP GET</SelectItem>
<SelectItem value="tcpSocket" className="text-[var(--dg-text-primary)]">TCP Socket</SelectItem>
</SelectContent>
</Select>
</div>
{h.type === 'exec' && (
<Textarea value={h.execCommand || ''} placeholder="每行一个命令片段"
<Textarea value={h.execCommand || ''} placeholder=t('kubernetes.containereditor.s7970e5')
onChange={e => onChange({ ...h, execCommand: e.target.value })}
className="dg-input font-mono text-xs min-h-[50px]" />
)}
@@ -435,7 +439,7 @@ function LifecycleHandlerEditor({ label, handler, onChange }: LifecycleHandlerEd
</div>
)}
{h.type === 'tcpSocket' && (
<Input type="number" value={h.tcpPort ?? ''} placeholder="端口"
<Input type="number" value={h.tcpPort ?? ''} placeholder=i18n.t('server.csv.port')
onChange={e => onChange({ ...h, tcpPort: e.target.value === '' ? undefined : Number(e.target.value) })}
className="dg-input font-mono text-xs h-7" />
)}
@@ -444,6 +448,7 @@ function LifecycleHandlerEditor({ label, handler, onChange }: LifecycleHandlerEd
}
function BoolToggle({ label, value, onChange }: BoolToggleProps) {
const { t } = useTranslation();
return (
<label className="flex items-center gap-1.5 cursor-pointer">
<Switch checked={value} onCheckedChange={onChange} />
@@ -16,11 +16,13 @@ import {
import { ContainerEditor } from './ContainerEditor';
import type { ContainerGroupSectionProps } from './types';
import { useConfirm } from '@/components/ui/confirm-dialog';
import { useTranslation } from 'react-i18next';
export function ContainerGroupSection({
title, description, icon, containers, accentColor,
onAdd, onRemove, onUpdate, onDuplicate,
}: ContainerGroupSectionProps) {
const { t } = useTranslation();
const confirm = useConfirm();
const [openIndices, setOpenIndices] = useState<Set<number>>(new Set([0]));
const toggleOpen = (idx: number) => {
@@ -50,7 +52,7 @@ export function ContainerGroupSection({
</CardHeader>
<CardContent className="pt-0 space-y-3">
{containers.length === 0 && (
<div className="text-center py-6 dg-text-muted text-xs">暂无容器,点击「新增容器」添加</div>
<div className="text-center py-6 dg-text-muted text-xs">{t('kubernetes.containergroupsection.s79ed70')}</div>
)}
{containers.map((c, idx) => {
const isOpen = openIndices.has(idx) || containers.length === 1;
@@ -61,22 +63,22 @@ export function ContainerGroupSection({
<div className="flex items-center gap-2">
{isOpen ? <ChevronDown className="h-4 w-4 dg-text-muted" /> : <ChevronRight className="h-4 w-4 dg-text-muted" />}
<Container className={`h-4 w-4 ${accentColor === 'blue' ? 'dg-text-blue' : 'dg-text-purple'}`} />
<span className="text-sm font-mono text-[var(--dg-text-primary)] font-semibold">{c.name || '(未命名)'}</span>
<span className="text-sm font-mono text-[var(--dg-text-primary)] font-semibold">{c.name || t('kubernetes.containergroupsection.sac52a9')}</span>
{c.image && <code className="text-[10px] dg-text-muted font-mono truncate max-w-[300px]">{c.image}</code>}
</div>
<div className="flex items-center gap-1" onClick={e => e.stopPropagation()}>
{onDuplicate && (
<Button variant="ghost" size="icon" className="h-7 w-7 dg-text-muted hover:text-[var(--dg-text-secondary)]" title="复制"
<Button variant="ghost" size="icon" className="h-7 w-7 dg-text-muted hover:text-[var(--dg-text-secondary)]" title=t('common.copy')
onClick={() => onDuplicate(idx)}>
<RotateCw className="h-3.5 w-3.5" />
</Button>
)}
<Button variant="ghost" size="icon" className="h-7 w-7 dg-text-red hover:dg-text-red" title="删除"
<Button variant="ghost" size="icon" className="h-7 w-7 dg-text-red hover:dg-text-red" title=t('common.delete')
onClick={async () => {
const ok = await confirm({
title: '删除容器',
description: `确认删除容器「${c.name}」?`,
confirmText: '删除',
title: t('kubernetes.containergroupsection.s860aaf'),
description: t('kubernetes.containergroupsection.s04ce19', { c.name: c.name }),
confirmText: t('common.delete'),
variant: 'destructive',
});
if (ok) onRemove(idx);
@@ -2,6 +2,7 @@
import { kubernetesApi } from '@/api';
import { prepareManifestForSave } from './k8s-manifest-utils';
import { isCreateDeployment } from './deployment-constants';
import i18n from '@/i18n';
export async function saveDeploymentManifest(
clusterCode: string,
@@ -10,7 +11,7 @@ export async function saveDeploymentManifest(
manifest: Record<string, any>,
): Promise<string> {
const resName = String(manifest?.metadata?.name || '').trim();
if (!resName) throw new Error('Deployment 名称不能为空');
if (!resName) throw new Error(i18n.t('kubernetes.deploymentManifestSave.scb497f'));
const yaml = await prepareManifestForSave(manifest);
if (isCreateDeployment(deploymentName)) {
await kubernetesApi.applyYAML(clusterCode, yaml);
@@ -3,6 +3,7 @@ import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { RefreshCw, Plus, Loader2 } from 'lucide-react';
import type { VolumeForm } from './deployment-volume-utils';
import { useTranslation } from 'react-i18next';
export interface NamespaceResourceLists {
configMaps: string[];
@@ -31,6 +32,7 @@ interface ResourcePickerProps {
export function NamespaceResourcePicker({
label, value, options, loading, onChange, onRefresh, onCreate,
}: ResourcePickerProps) {
const { t } = useTranslation();
const orphan = value && !options.includes(value);
return (
<div className="flex items-center gap-2 flex-wrap flex-1 min-w-0">
@@ -41,7 +43,7 @@ export function NamespaceResourcePicker({
disabled={loading}
className="h-7 flex-1 min-w-[160px] max-w-xs bg-[var(--dg-bg-tertiary)] border border-[var(--dg-border)] rounded text-xs text-[var(--dg-text-secondary)] px-2 font-mono"
>
<option value="" disabled>{options.length === 0 ? '暂无资源' : '请选择'}</option>
<option value="" disabled>{options.length === 0 ? t('kubernetes.deploymentStorageFields.s21ff31') : t('common.selectPlaceholder')}</option>
{orphan && <option value={value}>{value}(未在集群中找到)</option>}
{options.map((n) => <option key={n} value={n}>{n}</option>)}
</select>
@@ -70,11 +72,12 @@ interface VolumeTypeFieldsProps {
export function VolumeTypeFields({
vol, resources, resourcesLoading, onChange, onRefreshResources, onCreateResource,
}: VolumeTypeFieldsProps) {
const { t } = useTranslation();
if (vol.type === 'persistentVolumeClaim') {
return (
<div className="space-y-2">
<NamespaceResourcePicker
label="PVC 关联"
label=t('kubernetes.deploymentStorageFields.s9f74c4')
value={vol.pvcName || ''}
options={resources.pvcs}
loading={resourcesLoading}
@@ -92,28 +95,28 @@ export function VolumeTypeFields({
if (vol.type === 'emptyDir') {
return (
<div className="flex items-center gap-2 flex-wrap">
<span className="text-[10px] dg-text-muted w-20 shrink-0">介质</span>
<span className="text-[10px] dg-text-muted w-20 shrink-0">{t('kubernetes.deploymentStorageFields.sfac9d2')}</span>
<select value={vol.medium || ''} onChange={(e) => onChange({ medium: e.target.value })}
className="h-7 w-28 bg-[var(--dg-bg-tertiary)] border border-[var(--dg-border)] rounded text-xs text-[var(--dg-text-secondary)] px-1.5">
<option value="">默认磁盘</option>
<option value="">{t('kubernetes.deploymentStorageFields.s83f939')}</option>
<option value="Memory">Memory</option>
</select>
<Input value={vol.sizeLimit || ''} onChange={(e) => onChange({ sizeLimit: e.target.value })}
placeholder="sizeLimit 如 512Mi" className="h-7 flex-1 min-w-[120px] dg-input text-[var(--dg-text-secondary)] text-xs font-mono" />
placeholder=t('kubernetes.deploymentStorageFields.s503cb1') className="h-7 flex-1 min-w-[120px] dg-input text-[var(--dg-text-secondary)] text-xs font-mono" />
</div>
);
}
if (vol.type === 'hostPath') {
return (
<div className="flex items-center gap-2 flex-wrap">
<span className="text-[10px] dg-text-muted w-20 shrink-0">主机路径</span>
<span className="text-[10px] dg-text-muted w-20 shrink-0">{t('kubernetes.workload.hostPath')}</span>
<Input value={vol.path || ''} onChange={(e) => onChange({ path: e.target.value })}
placeholder="/data/app" className="h-7 flex-1 min-w-[160px] dg-input text-[var(--dg-text-secondary)] text-xs font-mono" />
<select value={vol.pathType || 'Directory'} onChange={(e) => onChange({ pathType: e.target.value })}
className="h-7 w-28 bg-[var(--dg-bg-tertiary)] border border-[var(--dg-border)] rounded text-xs text-[var(--dg-text-secondary)] px-1.5">
<option value="Directory">Directory</option>
<option value="File">File</option>
<option value="">默认</option>
<option value="">{t('approval.status.default')}</option>
</select>
</div>
);
@@ -142,9 +145,9 @@ export function VolumeTypeFields({
onCreate={() => onCreateResource('configmaps')}
/>
<div className="flex items-center gap-2 pl-[88px]">
<span className="text-[10px] dg-text-muted shrink-0">键映射</span>
<span className="text-[10px] dg-text-muted shrink-0">{t('kubernetes.deploymentStorageFields.sca72ee')}</span>
<Input value={vol.cmItems || ''} onChange={(e) => onChange({ cmItems: e.target.value })}
placeholder="key:path(可选,挂载子项)" className="h-7 flex-1 max-w-md dg-input text-[var(--dg-text-secondary)] text-xs font-mono" />
placeholder=t('kubernetes.deploymentStorageFields.s6f0d57') className="h-7 flex-1 max-w-md dg-input text-[var(--dg-text-secondary)] text-xs font-mono" />
</div>
</div>
);
@@ -162,15 +165,15 @@ export function VolumeTypeFields({
onCreate={() => onCreateResource('secrets')}
/>
<div className="flex items-center gap-2 pl-[88px]">
<span className="text-[10px] dg-text-muted shrink-0">键映射</span>
<span className="text-[10px] dg-text-muted shrink-0">{t('kubernetes.deploymentStorageFields.sca72ee')}</span>
<Input value={vol.secItems || ''} onChange={(e) => onChange({ secItems: e.target.value })}
placeholder="key:path(可选,挂载子项)" className="h-7 flex-1 max-w-md dg-input text-[var(--dg-text-secondary)] text-xs font-mono" />
placeholder=t('kubernetes.deploymentStorageFields.s6f0d57') className="h-7 flex-1 max-w-md dg-input text-[var(--dg-text-secondary)] text-xs font-mono" />
</div>
</div>
);
}
if (vol.type === 'custom') {
return <p className="text-[11px] dg-text-yellow/80">未识别卷类型,保存时将保留原始 YAML 结构</p>;
return <p className="text-[11px] dg-text-yellow/80">{t('kubernetes.deploymentStorageFields.s98d353')}</p>;
}
return null;
}
@@ -5,6 +5,8 @@ import {
} from '../k8s-yaml-utils';
import type { PodItem } from './types';
import type { JsonData } from '@/types/common';
import { useTranslation } from 'react-i18next';
import i18n from '@/i18n';
export interface PodStage {
label: string;
@@ -30,15 +32,16 @@ export function getPodTimeline(pod: PodItem) {
export function getPodStages(pod: PodItem): PodStage[] {
const tl = getPodTimeline(pod);
return [
{ label: '已调度', ts: tl.scheduled, color: STATUS_COLORS.blue },
{ label: '已初始化', ts: tl.initialized, color: STATUS_COLORS.orange },
{ label: '容器已就绪', ts: tl.containersReady, color: STATUS_COLORS.green },
{ label: '容器组已就绪', ts: tl.ready, color: STATUS_COLORS.green },
{ label: i18n.t('kubernetes.event.scheduled'), ts: tl.scheduled, color: STATUS_COLORS.blue },
{ label: i18n.t('kubernetes.helpers.scee76a'), ts: tl.initialized, color: STATUS_COLORS.orange },
{ label: i18n.t('kubernetes.helpers.s712b04'), ts: tl.containersReady, color: STATUS_COLORS.green },
{ label: i18n.t('kubernetes.helpers.s504965'), ts: tl.ready, color: STATUS_COLORS.green },
];
}
// 信息面板单项 // Logan.Li
export function InfoItem({ label, value }: { label: string; value: React.ReactNode }) {
const { t } = useTranslation();
return (
<div>
<p className="text-xs text-[var(--dg-text-muted)] mb-1">{label}</p>
@@ -49,6 +52,7 @@ export function InfoItem({ label, value }: { label: string; value: React.ReactNo
// 列表行紧凑就绪指示(无时间戳,避免视觉疲劳) // Logan.Li
export function PodStatusCompact({ pod }: { pod: PodItem }) {
const { t } = useTranslation();
const stages = getPodStages(pod);
const done = stages.filter(s => s.ts).length;
const allReady = done === stages.length;
@@ -56,7 +60,7 @@ export function PodStatusCompact({ pod }: { pod: PodItem }) {
return (
<div className="flex items-center gap-2 min-w-[88px]">
<div className="flex items-center gap-0.5" aria-label="启动进度">
<div className="flex items-center gap-0.5" aria-label=t('kubernetes.helpers.sfc9c68')>
{stages.map((s, i) => (
<Fragment key={s.label}>
<span
@@ -77,7 +81,7 @@ export function PodStatusCompact({ pod }: { pod: PodItem }) {
className="text-[11px] whitespace-nowrap"
style={{ color: allReady ? STATUS_COLORS.green : 'var(--dg-text-muted)' }}
>
{allReady ? '就绪' : pending?.label || `${done}/${stages.length}`}
{allReady ? t('common.ready') : pending?.label || `${done}/${stages.length}`}
</span>
</div>
);
@@ -85,13 +89,14 @@ export function PodStatusCompact({ pod }: { pod: PodItem }) {
// 详情区完整启动时间线(仅展开或概览面板使用) // Logan.Li
export function PodConditionsRow({ pod }: { pod: PodItem }) {
const { t } = useTranslation();
const stages = getPodStages(pod);
const totalBoot = elapsedSeconds(stages[0]?.ts, stages[stages.length - 1]?.ts);
return (
<div className="rounded-lg bg-[var(--dg-bg-tertiary)]/60 px-4 py-3">
<div className="flex items-center justify-between mb-3">
<span className="text-xs text-[var(--dg-text-muted)]">启动时间线</span>
<span className="text-xs text-[var(--dg-text-muted)]">{t('kubernetes.helpers.s684494')}</span>
{totalBoot != null && (
<span className="text-[11px] text-[var(--dg-text-muted)]">
总耗时 <span className="font-mono text-[var(--dg-text-secondary)]">{formatDuration(totalBoot)}</span>
@@ -6,6 +6,7 @@ import { CodeSnippetBlock } from '@/components/ui/code-snippet-block';
import { authApi } from '@/api';
import { getPublicApiBase } from '@/utils/request';
import { getSessionApiAccessKey } from '@/utils/storage';
import { useTranslation } from 'react-i18next';
export interface CICDWebhookContentProps {
clusterCode: string;
@@ -24,6 +25,7 @@ export function CICDWebhookContent({
image = '',
containerName = '',
}: CICDWebhookContentProps) {
const { t } = useTranslation();
const apiBase = getPublicApiBase();
const [keyLoading, setKeyLoading] = useState(true);
const [hasKey, setHasKey] = useState(false);
@@ -55,7 +57,7 @@ export function CICDWebhookContent({
const restartUrl = `${apiBase}/kubernetes/${clusterCode}/namespace/${namespace}/deployments/${deploymentName}/restart`;
const updateBody = useMemo(() => {
const body: Record<string, string> = { image: image || '<新镜像地址>' };
const body: Record<string, string> = { image: image || t('kubernetes.cicdwebhookcontent.sc4be9c') };
if (containerName) body.container_name = containerName;
return JSON.stringify(body);
}, [image, containerName]);
@@ -65,16 +67,12 @@ export function CICDWebhookContent({
-H 'X-AIOps-Access-Key: ${accessKey}' \\
-H 'Content-Type: application/json' \\
-d '${updateBody}'`
: `curl -X POST '${updateUrl}' \\
-H 'X-AIOps-Access-Key: <个人中心生成的访问密钥>' \\
-H 'Content-Type: application/json' \\
-d '${updateBody}'`;
: t('kubernetes.cicdwebhookcontent.s1976d2', { updateUrl: updateUrl, updateBody: updateBody });
const restartCurl = accessKey
? `curl -X POST '${restartUrl}' \\
-H 'X-AIOps-Access-Key: ${accessKey}'`
: `curl -X POST '${restartUrl}' \\
-H 'X-AIOps-Access-Key: <个人中心生成的访问密钥>'`;
: t('kubernetes.cicdwebhookcontent.s0e3668', { restartUrl: restartUrl });
const canCopy = !!accessKey && !keyExpired;
@@ -88,48 +86,48 @@ export function CICDWebhookContent({
) : keyExpired ? (
<>
访问凭证已过期,请前往
<Link to="/profile" className="text-[var(--dg-blue)] hover:underline mx-1">个人中心</Link>
<Link to="/profile" className="text-[var(--dg-blue)] hover:underline mx-1">{t('header.profile')}</Link>
调整有效期或轮换凭证后再复制 curl。
</>
) : accessKey ? (
<>已填入本机保存的访问凭证,复制 curl 后可直接在终端执行触发更新。</>
<>{t('kubernetes.cicdwebhookcontent.scd2b7d')}</>
) : hasKey ? (
<>
已检测到访问凭证,但本机未缓存明文。请前往
<Link to="/profile" className="text-[var(--dg-blue)] hover:underline mx-1">个人中心</Link>
<Link to="/profile" className="text-[var(--dg-blue)] hover:underline mx-1">{t('header.profile')}</Link>
轮换凭证一次,之后 curl 将自动填入。
</>
) : (
<>
请先在
<Link to="/profile" className="text-[var(--dg-blue)] hover:underline mx-1">个人中心</Link>
<Link to="/profile" className="text-[var(--dg-blue)] hover:underline mx-1">{t('header.profile')}</Link>
签发 CI/CD 访问凭证,curl 将自动填入。
</>
)}
</div>
<CodeSnippetBlock
label="更新镜像"
label=t('kubernetes.deployment.updateImage')
code={updateCurl}
copyLabel="curl 已复制,可直接粘贴到终端执行"
copyLabel=t('kubernetes.cicdwebhookcontent.s25a990')
copyDisabled={!canCopy}
copyDisabledTitle="请先在个人中心签发访问凭证"
copyDisabledTitle=t('kubernetes.cicdwebhookcontent.sc3bc41')
/>
<CodeSnippetBlock
label="滚动重启"
label=t('kubernetes.deployment.restart')
code={restartCurl}
copyLabel="curl 已复制,可直接粘贴到终端执行"
copyLabel=t('kubernetes.cicdwebhookcontent.s25a990')
copyDisabled={!canCopy}
copyDisabledTitle="请先在个人中心签发访问凭证"
copyDisabledTitle=t('kubernetes.cicdwebhookcontent.sc3bc41')
/>
<div className="text-xs text-[var(--dg-text-muted)] space-y-1">
<p>• 示例镜像:<code className="text-[var(--dg-text-secondary)]">{image || '—'}</code>
{containerName ? <> · 容器 <code className="text-[var(--dg-text-secondary)]">{containerName}</code></> : null}
<p>{t('kubernetes.cicdwebhookcontent.s1bdaf4')}<code className="text-[var(--dg-text-secondary)]">{image || '—'}</code>
{containerName ? <> {t('kubernetes.cicdwebhookcontent.s9b07e8')} <code className="text-[var(--dg-text-secondary)]">{containerName}</code></> : null}
</p>
<p>• 使用长期 API 密钥,不会随登录 JWT 过期</p>
<p>• 修改 <code className="text-[var(--dg-text-secondary)]">image</code> 字段后执行 curl 即可触发滚动更新</p>
<p>• 也可用 <code className="text-[var(--dg-text-secondary)]">Authorization: Bearer &lt;密钥&gt;</code></p>
<p>{t('kubernetes.cicdwebhookcontent.se067d1')}</p>
<p>{t('kubernetes.cicdwebhookcontent.s311998')} <code className="text-[var(--dg-text-secondary)]">image</code> {t('kubernetes.cicdwebhookcontent.s55260c')}</p>
<p>{t('kubernetes.cicdwebhookcontent.s4e20ba')} <code className="text-[var(--dg-text-secondary)]">{t('kubernetes.cicdwebhookcontent.s67cc60')}</code></p>
</div>
</div>
);
@@ -7,6 +7,7 @@ import { DeploymentEditContainers } from '../DeploymentEditContainers';
import { DeploymentEditStorage } from '../DeploymentEditStorage';
import { DeploymentEditAdvanced } from '../DeploymentEditAdvanced';
import { DeploymentEditService } from '../DeploymentEditService';
import { useTranslation } from 'react-i18next';
export interface EditModeContainerProps {
clusterCode: string;
@@ -20,6 +21,7 @@ export interface EditModeContainerProps {
}
export function EditModeContainer({ clusterCode, namespace, deploymentName, manifest, onSaved, onCancel, isCreate = false }: EditModeContainerProps) {
const { t } = useTranslation();
type EditTab = 'basic' | 'containers' | 'storage' | 'advanced' | 'service';
const [activeTab, setActiveTab] = useState<EditTab>('basic');
const [editManifest, setEditManifest] = useState<any>(manifest);
@@ -34,11 +36,11 @@ export function EditModeContainer({ clusterCode, namespace, deploymentName, mani
};
const tabs: Array<{ key: EditTab; label: string; icon: typeof Settings }> = [
{ key: 'basic', label: '基本信息', icon: Settings },
{ key: 'containers', label: '容器信息', icon: Container },
{ key: 'storage', label: '存储挂载', icon: Database },
{ key: 'advanced', label: '高级设置', icon: Settings },
{ key: 'service', label: '服务/应用路由', icon: Network },
{ key: 'basic', label: t('deploy.label.basicInfo'), icon: Settings },
{ key: 'containers', label: t('kubernetes.editmodecontainer.sd58c2e'), icon: Container },
{ key: 'storage', label: t('kubernetes.editmodecontainer.s9ffdac'), icon: Database },
{ key: 'advanced', label: t('kubernetes.editmodecontainer.se37075'), icon: Settings },
{ key: 'service', label: t('kubernetes.editmodecontainer.s8bdc2d'), icon: Network },
];
const commonProps = {
@@ -9,6 +9,7 @@ import { kubernetesApi } from '@/api';
import { useToast } from '@/hooks/use-toast';
import { useUserStore } from '@/store';
import type { JsonData } from '@/types/common';
import { useTranslation } from 'react-i18next';
export interface PodLogsModalProps {
clusterCode: string;
@@ -19,6 +20,7 @@ export interface PodLogsModalProps {
}
export function PodLogsModal({ clusterCode, namespace, podName, containers, onClose }: PodLogsModalProps) {
const { t } = useTranslation();
const { toast } = useToast();
const [logs, setLogs] = useState('');
const [tail, setTail] = useState(200);
@@ -30,9 +32,9 @@ export function PodLogsModal({ clusterCode, namespace, podName, containers, onCl
setLoading(true);
try {
const res: JsonData = await kubernetesApi.getPodLogs(clusterCode, namespace, podName, tail, container || undefined);
setLogs(res?.data?.logs || res?.logs || res || '无日志');
setLogs(res?.data?.logs || res?.logs || res || t('kubernetes.podlogsmodal.s4ff3b4'));
} catch {
setLogs('获取日志失败');
setLogs(t('kubernetes.podlogsmodal.sc93f33'));
} finally { setLoading(false); }
};
@@ -57,7 +59,7 @@ export function PodLogsModal({ clusterCode, namespace, podName, containers, onCl
setLogs(buf);
}
} catch {
toast({ title: '流式日志连接中断', variant: 'destructive' });
toast({ title: t('kubernetes.podlogsmodal.s6273c9'), variant: 'destructive' });
} finally { setStreaming(false); }
};
@@ -77,22 +79,22 @@ export function PodLogsModal({ clusterCode, namespace, podName, containers, onCl
{containers.map(c => <option key={c} value={c}>{c}</option>)}
</select>
)}
<span className="text-[11px] dg-text-muted">最近</span>
<span className="text-[11px] dg-text-muted">{t('k8s.deploymentDetail.recent')}</span>
<Input type="number" value={tail} onChange={e => setTail(Number(e.target.value) || 200)}
className="w-16 h-7 dg-input text-xs" />
<span className="text-[11px] dg-text-muted">行</span>
<span className="text-[11px] dg-text-muted">{t('k8s.deploymentDetail.lines')}</span>
<Button size="sm" variant="outline" className="h-7 border-[var(--dg-border)] text-[var(--dg-text-secondary)] text-xs" onClick={loadLogs} disabled={loading}>
{loading ? <Loader2 className="h-3 w-3 animate-spin" /> : <RefreshCw className="h-3 w-3" />}
</Button>
<Button size="sm" variant="outline" className="h-7 border-[var(--dg-border)] dg-text-green text-xs" onClick={startStream} disabled={streaming}>
{streaming ? '流中...' : '实时流'}
{streaming ? t('kubernetes.podlogsmodal.s2d4fb3') : t('monitor.logStreaming')}
</Button>
<Button variant="ghost" size="icon" className="h-7 w-7 dg-text-secondary" onClick={onClose}><X className="h-4 w-4" /></Button>
</div>
</div>
<div className="flex-1 overflow-auto p-3">
<pre className="bg-[var(--dg-bg-primary)] rounded p-3 text-xs text-[var(--dg-text-secondary)] font-mono whitespace-pre-wrap max-h-[60vh] overflow-auto">
{logs || '无日志内容'}
{logs || t('kubernetes.podlogsmodal.s99eac0')}
</pre>
</div>
</div>
@@ -6,6 +6,7 @@ import { Label } from '@/components/ui/label';
import { ArrowRight, Loader2 } from 'lucide-react';
import { joinImageRef, parseImageRef } from '../image-ref-utils';
import { ModalShell } from './ModalShell';
import { useTranslation } from 'react-i18next';
export interface UpdateImageModalProps {
deployment: any;
@@ -24,6 +25,7 @@ export function UpdateImageModal({
onClose,
onUpdateImage,
}: UpdateImageModalProps) {
const { t } = useTranslation();
const currentImage = deployment?.image || '';
const current = useMemo(() => parseImageRef(currentImage), [currentImage]);
@@ -46,14 +48,14 @@ export function UpdateImageModal({
};
return (
<ModalShell title="调整镜像版本" onClose={onClose} size="xl">
<ModalShell title=t('kubernetes.updateimagemodal.s22a2ed') onClose={onClose} size="xl">
<div className="space-y-5">
{/* 当前镜像:只读展示完整地址与 Tag // Logan.Li */}
<div className="rounded-lg border border-[var(--dg-border)]/80 bg-[var(--dg-bg-tertiary)]/40 p-4 space-y-3">
<p className="text-xs font-medium dg-text-secondary">当前镜像</p>
<p className="text-xs font-medium dg-text-secondary">{t('kubernetes.deployment.currentImage')}</p>
<div className="grid grid-cols-[1fr_180px] gap-3">
<div>
<Label className="dg-text-muted text-xs">镜像地址</Label>
<Label className="dg-text-muted text-xs">{t('kubernetes.updateimagemodal.sdbe6a6')}</Label>
<p
className="mt-1.5 text-sm text-[var(--dg-text-primary)] font-mono break-all leading-relaxed bg-[var(--dg-bg-secondary)]/60 rounded-md px-3 py-2.5 min-h-[42px]"
title={current.repository || '-'}
@@ -62,7 +64,7 @@ export function UpdateImageModal({
</p>
</div>
<div>
<Label className="dg-text-muted text-xs">当前 Tag</Label>
<Label className="dg-text-muted text-xs">{t('kubernetes.updateimagemodal.sf08c71')}</Label>
<p
className="mt-1.5 text-sm text-cyan-300 font-mono break-all leading-relaxed bg-[var(--dg-bg-secondary)]/60 rounded-md px-3 py-2.5 min-h-[42px]"
title={current.tag || '-'}
@@ -82,10 +84,10 @@ export function UpdateImageModal({
{/* 新镜像:地址与 Tag 分栏编辑 // Logan.Li */}
<div className="rounded-lg border border-blue-500/30 bg-blue-500/5 p-4 space-y-3">
<p className="text-xs font-medium text-blue-300/90">新镜像</p>
<p className="text-xs font-medium text-blue-300/90">{t('kubernetes.deployment.newImage')}</p>
<div className="grid grid-cols-[1fr_180px] gap-3">
<div>
<Label className="dg-text-secondary text-xs">镜像地址</Label>
<Label className="dg-text-secondary text-xs">{t('kubernetes.updateimagemodal.sdbe6a6')}</Label>
<Input
value={newRepo}
onChange={e => {
@@ -98,7 +100,7 @@ export function UpdateImageModal({
/>
</div>
<div>
<Label className="dg-text-secondary text-xs">新版本 Tag</Label>
<Label className="dg-text-secondary text-xs">{t('kubernetes.updateimagemodal.s6a38a8')}</Label>
<Input
value={newTag}
onChange={e => {
@@ -113,7 +115,7 @@ export function UpdateImageModal({
</div>
<div className="flex flex-wrap items-center gap-2 text-xs">
<span className="dg-text-muted">Tag 变更:</span>
<span className="dg-text-muted">{t('kubernetes.updateimagemodal.sec74e0')}</span>
<code className="px-2 py-0.5 rounded bg-[var(--dg-bg-tertiary)] dg-text-secondary font-mono">{current.tag}</code>
<ArrowRight className="h-3 w-3 dg-text-muted" />
<code
@@ -124,10 +126,10 @@ export function UpdateImageModal({
{newTag.trim() || '-'}
</code>
{!tagChanged && !repoChanged && (
<span className="dg-text-muted">(未修改)</span>
<span className="dg-text-muted">{t('kubernetes.updateimagemodal.s47c8cf')}</span>
)}
{repoChanged && !tagChanged && (
<span className="dg-text-yellow/80">地址已变更</span>
<span className="dg-text-yellow/80">{t('kubernetes.updateimagemodal.sdb3122')}</span>
)}
</div>
@@ -145,7 +147,7 @@ export function UpdateImageModal({
disabled={actionLoading === 'image' || !previewImage.trim() || !hasChanges}
onClick={onUpdateImage}
>
{actionLoading === 'image' ? <Loader2 className="h-4 w-4 animate-spin" /> : '更新镜像'}
{actionLoading === 'image' ? <Loader2 className="h-4 w-4 animate-spin" /> : i18n.t('kubernetes.deployment.updateImage')}
</Button>
</div>
</div>
@@ -1,6 +1,7 @@
// k8s-event-utils — K8s Event 字段归一化与展示 // Logan.Li
import { elapsedSeconds, formatDuration, formatK8sTime } from './k8s-yaml-utils';
import type { JsonData } from '@/types/common';
import i18n from '@/i18n';
export interface NormalizedEvent {
name: string;
@@ -59,11 +60,11 @@ export function formatEventRelative(ts: string): string {
const diff = Date.now() - new Date(ts).getTime();
if (diff < 0) return '';
const mins = Math.floor(diff / 60000);
if (mins < 1) return '刚刚';
if (mins < 60) return `${mins}分钟前`;
if (mins < 1) return i18n.t('task.cronJob.time.justNow');
if (mins < 60) return i18n.t('kubernetes.k8sEventUtils.s9dc098', { mins: mins });
const hrs = Math.floor(mins / 60);
if (hrs < 24) return `${hrs}小时前`;
return `${Math.floor(hrs / 24)}天前`;
if (hrs < 24) return i18n.t('kubernetes.k8sEventUtils.sc71bd7', { hrs: hrs });
return i18n.t('kubernetes.k8sEventUtils.s02f1ca', { Math.floor(hrs / 24): Math.floor(hrs / 24) });
}
/** 重复跨度:首次 → 最后 // Logan.Li */
@@ -3,25 +3,26 @@ import {
Network, Server, Globe, Cloud, Boxes, Database, Zap, Box,
} from 'lucide-react';
import type { TopologyNode, TopologyEdge } from '@/types';
import i18n from '@/i18n';
// K8s 资源类型 → 拓扑节点类型标签 // Logan.Li
export const NODE_TYPE_LABELS: Record<string, string> = {
cluster: '集群',
cluster: i18n.t('kubernetes.topologyHelpers.s85fe50'),
loadbalancer: 'Ingress',
service: 'Service',
app: 'Deployment',
pod: 'Pod',
server: 'Node',
database: '数据库',
external: '外部服务',
custom: '自定义',
database: i18n.t('kubernetes.topologyHelpers.s68051b'),
external: i18n.t('kubernetes.topologyHelpers.s47921e'),
custom: i18n.t('common.custom'),
};
// 自定义节点类型选项(编辑模式用)
export const CUSTOM_NODE_TYPES = [
{ value: 'database', label: '数据库', desc: 'MySQL / Redis / PostgreSQL 等' },
{ value: 'external', label: '外部服务', desc: '外部 API / CDN / DNS 等' },
{ value: 'custom', label: '自定义', desc: '其他自定义节点' },
{ value: 'database', label: i18n.t('kubernetes.topologyHelpers.s68051b'), desc: i18n.t('kubernetes.topologyHelpers.sf6a891') },
{ value: 'external', label: i18n.t('kubernetes.topologyHelpers.s47921e'), desc: i18n.t('kubernetes.topologyHelpers.s39b435') },
{ value: 'custom', label: i18n.t('common.custom'), desc: i18n.t('kubernetes.topologyHelpers.sfb5d27') },
];
// 判断是否为自定义节点(非 K8s 原生资源)
@@ -85,7 +86,7 @@ export function buildTopology( cluster: any, ingresses: any[], services: any[],
// Layer 0: Cluster
const clusterId = `cluster-${cluster.id}`;
tNodes.push({
id: clusterId, name: cluster.name || '集群', type: 'cluster',
id: clusterId, name: cluster.name || i18n.t('kubernetes.topologyHelpers.s85fe50'), type: 'cluster',
x: canvasW / 2, y: layerY[0],
data: { kind: 'cluster', version: cluster.version, status: cluster.status, api_server: cluster.api_server, node_count: cluster.node_count, pod_count: cluster.pod_count },
});