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

+23 -21
View File
@@ -28,8 +28,10 @@ import {
} from './agentAlertHelper'; } from './agentAlertHelper';
import { AgentRuleDialog } from './AgentRuleDialog'; import { AgentRuleDialog } from './AgentRuleDialog';
import type { JsonData } from '@/types/common'; import type { JsonData } from '@/types/common';
import { useTranslation } from 'react-i18next';
export function AgentAlerts() { export function AgentAlerts() {
const { t } = useTranslation();
const confirm = useConfirm(); const confirm = useConfirm();
const [activeTab, setActiveTab] = useState('events'); const [activeTab, setActiveTab] = useState('events');
const [alerts, setAlerts] = useState<JsonData[]>([]); const [alerts, setAlerts] = useState<JsonData[]>([]);
@@ -52,7 +54,7 @@ export function AgentAlerts() {
setRules(asList(rulesRes)); setRules(asList(rulesRes));
} catch (err) { } catch (err) {
console.error(err); console.error(err);
toast.error('加载告警数据失败'); toast.error(t('agent.agentalerts.s7ffaa4'));
} finally { } finally {
setLoading(false); setLoading(false);
} }
@@ -64,14 +66,14 @@ export function AgentAlerts() {
// ============ 告警事件 ============ // ============ 告警事件 ============
const handleResolve = async (id: number) => { const handleResolve = async (id: number) => {
const ok = await confirm({ title: '恢复告警', description: '确定将此告警标记为已恢复?', confirmText: '恢复' }); const ok = await confirm({ title: t('agent.agentalerts.sd56d01'), description: t('agent.agentalerts.s99f0fb'), confirmText: t('common.resume') });
if (!ok) return; if (!ok) return;
try { try {
await agentApi.resolveAlert(id); await agentApi.resolveAlert(id);
toast.success('告警已恢复'); toast.success(t('agent.agentalerts.s0e2352'));
loadData(); loadData();
} catch (err) { } catch (err) {
toast.error(err?.message || '操作失败'); toast.error(err?.message || t('common.operationFailed'));
} }
}; };
@@ -87,14 +89,14 @@ export function AgentAlerts() {
}; };
const handleDeleteRule = async (id: number) => { const handleDeleteRule = async (id: number) => {
const ok = await confirm({ title: '删除规则', description: '确定删除此告警规则?', confirmText: '删除', variant: 'destructive' }); const ok = await confirm({ title: t('alert.deleteRule'), description: t('agent.agentalerts.sd30155'), confirmText: t('common.delete'), variant: 'destructive' });
if (!ok) return; if (!ok) return;
try { try {
await agentApi.deleteRule(id); await agentApi.deleteRule(id);
toast.success('规则已删除'); toast.success(t('agent.agentalerts.s8b2798'));
loadData(); loadData();
} catch (err) { } catch (err) {
toast.error(err?.message || '删除失败'); toast.error(err?.message || t('common.deleteFailed'));
} }
}; };
@@ -103,7 +105,7 @@ export function AgentAlerts() {
await agentApi.updateRule(rule.id, { ...rule, enabled: !rule.enabled }); await agentApi.updateRule(rule.id, { ...rule, enabled: !rule.enabled });
loadData(); loadData();
} catch (err) { } catch (err) {
toast.error(err?.message || '操作失败'); toast.error(err?.message || t('common.operationFailed'));
} }
}; };
@@ -112,8 +114,8 @@ export function AgentAlerts() {
{/* 页头 */} {/* 页头 */}
<div className="flex items-center justify-between"> <div className="flex items-center justify-between">
<div> <div>
<h2 className="text-xl font-semibold text-[var(--dg-text-primary)]">Agent 告警</h2> <h2 className="text-xl font-semibold text-[var(--dg-text-primary)]">{t('agent.agentalerts.s87efbd')}</h2>
<p className="text-sm dg-text-secondary mt-0.5">基于 Agent 上报指标的告警规则与事件</p> <p className="text-sm dg-text-secondary mt-0.5">{t('agent.agentalerts.s03a08c')}</p>
</div> </div>
<Button variant="outline" size="sm" onClick={loadData} disabled={loading} className="dg-input text-[var(--dg-text-secondary)] hover:bg-[var(--dg-bg-hover)]"> <Button variant="outline" size="sm" onClick={loadData} disabled={loading} className="dg-input text-[var(--dg-text-secondary)] hover:bg-[var(--dg-bg-hover)]">
<RefreshCw className={`h-4 w-4 mr-1.5 ${loading ? 'animate-spin' : ''}`} /> <RefreshCw className={`h-4 w-4 mr-1.5 ${loading ? 'animate-spin' : ''}`} />
@@ -123,8 +125,8 @@ export function AgentAlerts() {
<Tabs value={activeTab} onValueChange={setActiveTab} className="w-full"> <Tabs value={activeTab} onValueChange={setActiveTab} className="w-full">
<TabsList className="bg-[var(--dg-bg-tertiary)] border border-[var(--dg-border)]"> <TabsList className="bg-[var(--dg-bg-tertiary)] border border-[var(--dg-border)]">
<TabsTrigger value="events" className="data-[state=active]:bg-[var(--dg-bg-active)]">告警事件</TabsTrigger> <TabsTrigger value="events" className="data-[state=active]:bg-[var(--dg-bg-active)]">{t('agent.agentalerts.s0e5b83')}</TabsTrigger>
<TabsTrigger value="rules" className="data-[state=active]:bg-[var(--dg-bg-active)]">告警规则</TabsTrigger> <TabsTrigger value="rules" className="data-[state=active]:bg-[var(--dg-bg-active)]">{t('alert.tab.rules')}</TabsTrigger>
</TabsList> </TabsList>
{/* ========== 告警事件 ========== */} {/* ========== 告警事件 ========== */}
@@ -152,14 +154,14 @@ export function AgentAlerts() {
<Card className="dg-card"> <Card className="dg-card">
<CardContent className="flex items-center justify-center py-16"> <CardContent className="flex items-center justify-center py-16">
<Loader2 className="h-5 w-5 animate-spin dg-text-muted" /> <Loader2 className="h-5 w-5 animate-spin dg-text-muted" />
<span className="ml-2 dg-text-secondary">加载中...</span> <span className="ml-2 dg-text-secondary">{t('common.loading')}</span>
</CardContent> </CardContent>
</Card> </Card>
) : alerts.length === 0 ? ( ) : alerts.length === 0 ? (
<Card className="dg-card"> <Card className="dg-card">
<CardContent className="flex flex-col items-center justify-center py-16"> <CardContent className="flex flex-col items-center justify-center py-16">
<CheckCircle className="h-10 w-10 text-emerald-500 mb-3" /> <CheckCircle className="h-10 w-10 text-emerald-500 mb-3" />
<p className="dg-text-secondary">{resolvedView ? '暂无已恢复的告警' : '当前无活动告警,一切正常'}</p> <p className="dg-text-secondary">{resolvedView ? t('agent.agentalerts.se459f4') : t('agent.agentalerts.s778455')}</p>
</CardContent> </CardContent>
</Card> </Card>
) : ( ) : (
@@ -175,20 +177,20 @@ export function AgentAlerts() {
<div className="min-w-0"> <div className="min-w-0">
<div className="flex items-center gap-2 flex-wrap"> <div className="flex items-center gap-2 flex-wrap">
{severityBadge(alert.severity)} {severityBadge(alert.severity)}
<span className="font-medium text-[var(--dg-text-primary)]">{alert.rule_name || alert.name || alert.title || '告警'}</span> <span className="font-medium text-[var(--dg-text-primary)]">{alert.rule_name || alert.name || alert.title || t('dashboard.stat.alerts')}</span>
</div> </div>
<p className="text-sm dg-text-secondary mt-1">{alert.message || alert.description || '触发告警阈值'}</p> <p className="text-sm dg-text-secondary mt-1">{alert.message || alert.description || t('agent.agentalerts.sddab4a')}</p>
<div className="flex items-center gap-4 mt-2 text-xs dg-text-muted flex-wrap"> <div className="flex items-center gap-4 mt-2 text-xs dg-text-muted flex-wrap">
<span className="inline-flex items-center gap-1"> <span className="inline-flex items-center gap-1">
<Cpu className="h-3 w-3" /> <Cpu className="h-3 w-3" />
{alert.hostname || '--'} {alert.hostname || '--'}
</span> </span>
<span className="inline-flex items-center gap-1"> <span className="inline-flex items-center gap-1">
<span className="dg-text-secondary">指标:</span> {getMetricLabel(alert.metric)} <span className="dg-text-secondary">{t('agent.agentalerts.sbfdcf2')}</span> {getMetricLabel(alert.metric)}
</span> </span>
{alert.value != null && ( {alert.value != null && (
<span className="inline-flex items-center gap-1"> <span className="inline-flex items-center gap-1">
<span className="dg-text-secondary">当前值:</span> {alert.value} <span className="dg-text-secondary">{t('agent.agentalerts.s2d1376')}</span> {alert.value}
</span> </span>
)} )}
<span className="inline-flex items-center gap-1"> <span className="inline-flex items-center gap-1">
@@ -230,14 +232,14 @@ export function AgentAlerts() {
<Card className="dg-card"> <Card className="dg-card">
<CardContent className="flex items-center justify-center py-16"> <CardContent className="flex items-center justify-center py-16">
<Loader2 className="h-5 w-5 animate-spin dg-text-muted" /> <Loader2 className="h-5 w-5 animate-spin dg-text-muted" />
<span className="ml-2 dg-text-secondary">加载中...</span> <span className="ml-2 dg-text-secondary">{t('common.loading')}</span>
</CardContent> </CardContent>
</Card> </Card>
) : rules.length === 0 ? ( ) : rules.length === 0 ? (
<Card className="dg-card"> <Card className="dg-card">
<CardContent className="flex flex-col items-center justify-center py-16"> <CardContent className="flex flex-col items-center justify-center py-16">
<Bell className="h-10 w-10 dg-text-muted mb-3" /> <Bell className="h-10 w-10 dg-text-muted mb-3" />
<p className="dg-text-secondary">暂无告警规则</p> <p className="dg-text-secondary">{t('alert.noRules')}</p>
<Button size="sm" onClick={openCreateRule} className="mt-4 bg-blue-600 hover:bg-blue-700 text-white"> <Button size="sm" onClick={openCreateRule} className="mt-4 bg-blue-600 hover:bg-blue-700 text-white">
<Plus className="h-4 w-4 mr-1.5" /> <Plus className="h-4 w-4 mr-1.5" />
创建第一条规则 创建第一条规则
@@ -261,7 +263,7 @@ export function AgentAlerts() {
<span className="font-medium text-[var(--dg-text-primary)]">{rule.name}</span> <span className="font-medium text-[var(--dg-text-primary)]">{rule.name}</span>
{severityBadge(rule.severity)} {severityBadge(rule.severity)}
{rule.enabled === false && ( {rule.enabled === false && (
<Badge className="bg-[var(--dg-bg-active)] dg-text-secondary border border-[var(--dg-border-hover)]">已禁用</Badge> <Badge className="bg-[var(--dg-bg-active)] dg-text-secondary border border-[var(--dg-border-hover)]">{t('alert.disabled')}</Badge>
)} )}
</div> </div>
<div className="flex items-center gap-3 mt-1.5 text-xs dg-text-muted flex-wrap"> <div className="flex items-center gap-3 mt-1.5 text-xs dg-text-muted flex-wrap">
+24 -21
View File
@@ -23,6 +23,7 @@ import {
} from '@/components/ui/dialog'; } from '@/components/ui/dialog';
import { import {
import { useTranslation } from 'react-i18next';
Cpu, Cpu,
MemoryStick, MemoryStick,
HardDrive, HardDrive,
@@ -41,6 +42,7 @@ import {
// ============ 组件 ============ // ============ 组件 ============
export function AgentMonitor() { export function AgentMonitor() {
const { t } = useTranslation();
const [hosts, setHosts] = useState<AgentHostRecord[]>([]); const [hosts, setHosts] = useState<AgentHostRecord[]>([]);
const [loading, setLoading] = useState(true); const [loading, setLoading] = useState(true);
const [refreshing, setRefreshing] = useState(false); const [refreshing, setRefreshing] = useState(false);
@@ -68,7 +70,7 @@ export function AgentMonitor() {
if (fresh) setSelectedHost(fresh); if (fresh) setSelectedHost(fresh);
} }
} catch (err) { } catch (err) {
if (!silent) toast.error('加载主机列表失败'); if (!silent) toast.error(t('agent.agentmonitor.s5760f6'));
console.error(err); console.error(err);
} finally { } finally {
setLoading(false); setLoading(false);
@@ -97,7 +99,7 @@ export function AgentMonitor() {
// 提交远程命令(直连 SSH 即时返回) // 提交远程命令(直连 SSH 即时返回)
const submitCommand = async () => { const submitCommand = async () => {
if (!cmdCommand.trim()) { if (!cmdCommand.trim()) {
toast.error('请输入要执行的命令'); toast.error(t('agent.agentmonitor.s9358aa'));
return; return;
} }
setCmdSubmitting(true); setCmdSubmitting(true);
@@ -111,11 +113,11 @@ export function AgentMonitor() {
const resData = (res?.data ?? {}) as Record<string, unknown>; const resData = (res?.data ?? {}) as Record<string, unknown>;
setCmdResult({ setCmdResult({
status: res?.code === 200 ? 'completed' : 'failed', status: res?.code === 200 ? 'completed' : 'failed',
result: (resData.output as string) || (res?.message as string) || '无输出', result: (resData.output as string) || (res?.message as string) || t('agent.agentmonitor.s26d45b'),
error: resData.error as string | undefined, error: resData.error as string | undefined,
}); });
} catch (err) { } catch (err) {
setCmdResult({ status: 'failed', result: err?.message || '执行失败' }); setCmdResult({ status: 'failed', result: err?.message || t('automation.scriptFailed') });
} finally { } finally {
setCmdSubmitting(false); setCmdSubmitting(false);
loadLatest(true); loadLatest(true);
@@ -129,9 +131,9 @@ export function AgentMonitor() {
const onlineCount = hosts.filter((h) => isOnline(h.last_report || h.last_reported_at || h.updated_at)).length; const onlineCount = hosts.filter((h) => isOnline(h.last_report || h.last_reported_at || h.updated_at)).length;
const stats = [ const stats = [
{ label: '主机总数', value: hosts.length, icon: Server, color: 'dg-text-blue' }, { label: t('agent.agentmonitor.sd94cd2'), value: hosts.length, icon: Server, color: 'dg-text-blue' },
{ label: '在线', value: onlineCount, icon: Wifi, color: 'dg-text-green' }, { label: t('common.online'), value: onlineCount, icon: Wifi, color: 'dg-text-green' },
{ label: '离线', value: hosts.length - onlineCount, icon: WifiOff, color: 'dg-text-red' }, { label: t('common.offline'), value: hosts.length - onlineCount, icon: WifiOff, color: 'dg-text-red' },
]; ];
return ( return (
@@ -139,8 +141,8 @@ export function AgentMonitor() {
{/* 页头 */} {/* 页头 */}
<div className="flex items-center justify-between"> <div className="flex items-center justify-between">
<div> <div>
<h2 className="text-xl font-semibold text-[var(--dg-text-primary)]">Agent 监控</h2> <h2 className="text-xl font-semibold text-[var(--dg-text-primary)]">{t('agent.agentMonitor')}</h2>
<p className="text-sm dg-text-secondary mt-0.5">实时监控 Agent 上报的主机指标</p> <p className="text-sm dg-text-secondary mt-0.5">{t('agent.agentmonitor.sa75d75')}</p>
</div> </div>
<div className="flex items-center gap-2"> <div className="flex items-center gap-2">
<Button <Button
@@ -186,14 +188,14 @@ export function AgentMonitor() {
<Card className="dg-card"> <Card className="dg-card">
<CardContent className="flex items-center justify-center py-16"> <CardContent className="flex items-center justify-center py-16">
<Loader2 className="h-6 w-6 animate-spin dg-text-muted" /> <Loader2 className="h-6 w-6 animate-spin dg-text-muted" />
<span className="ml-2 dg-text-secondary">加载中...</span> <span className="ml-2 dg-text-secondary">{t('common.loading')}</span>
</CardContent> </CardContent>
</Card> </Card>
) : hosts.length === 0 ? ( ) : hosts.length === 0 ? (
<Card className="dg-card"> <Card className="dg-card">
<CardContent className="flex flex-col items-center justify-center py-16"> <CardContent className="flex flex-col items-center justify-center py-16">
<Server className="h-10 w-10 dg-text-muted mb-3" /> <Server className="h-10 w-10 dg-text-muted mb-3" />
<p className="dg-text-secondary">暂无 Agent 上报数据</p> <p className="dg-text-secondary">{t('agent.noAgentData')}</p>
<Button <Button
size="sm" size="sm"
onClick={() => setWizardOpen(true)} onClick={() => setWizardOpen(true)}
@@ -240,8 +242,8 @@ export function AgentMonitor() {
{/* 指标条 */} {/* 指标条 */}
<div className="space-y-2"> <div className="space-y-2">
<MetricBar icon={Cpu} label="CPU" value={cpu} /> <MetricBar icon={Cpu} label="CPU" value={cpu} />
<MetricBar icon={MemoryStick} label="内存" value={mem} /> <MetricBar icon={MemoryStick} label=t('k8s.pods.memory') value={mem} />
<MetricBar icon={HardDrive} label="磁盘" value={disk} /> <MetricBar icon={HardDrive} label=t('dashboard.topUsage.disk') value={disk} />
</div> </div>
{/* 端口 & 时间 */} {/* 端口 & 时间 */}
@@ -307,7 +309,7 @@ export function AgentMonitor() {
<div className="space-y-3"> <div className="space-y-3">
<div className="grid grid-cols-2 gap-3"> <div className="grid grid-cols-2 gap-3">
<div className="space-y-1.5"> <div className="space-y-1.5">
<Label className="text-[var(--dg-text-secondary)] text-xs">目标主机</Label> <Label className="text-[var(--dg-text-secondary)] text-xs">{t('agent.installTarget')}</Label>
<Input <Input
value={cmdHost} value={cmdHost}
onChange={(e) => setCmdHost(e.target.value)} onChange={(e) => setCmdHost(e.target.value)}
@@ -318,18 +320,18 @@ export function AgentMonitor() {
</div> </div>
<div className="space-y-1.5"> <div className="space-y-1.5">
<Label className="text-[var(--dg-text-secondary)] text-xs">命令</Label> <Label className="text-[var(--dg-text-secondary)] text-xs">{t('system.terminalCommand')}</Label>
<Textarea <Textarea
value={cmdCommand} value={cmdCommand}
onChange={(e) => setCmdCommand(e.target.value)} onChange={(e) => setCmdCommand(e.target.value)}
placeholder="例如:free -m && df -h" placeholder=t('agent.agentmonitor.s6e62a5')
rows={3} rows={3}
className="bg-[var(--dg-bg-primary)] border-[var(--dg-border)] text-[var(--dg-text-primary)] font-mono text-sm resize-none" className="bg-[var(--dg-bg-primary)] border-[var(--dg-border)] text-[var(--dg-text-primary)] font-mono text-sm resize-none"
/> />
</div> </div>
<div className="w-40 space-y-1.5"> <div className="w-40 space-y-1.5">
<Label className="text-[var(--dg-text-secondary)] text-xs">超时(秒)</Label> <Label className="text-[var(--dg-text-secondary)] text-xs">{t('monitor.probeTimeout')}</Label>
<Input <Input
type="number" type="number"
value={cmdTimeout} value={cmdTimeout}
@@ -342,7 +344,7 @@ export function AgentMonitor() {
{cmdResult && ( {cmdResult && (
<div className="space-y-1.5"> <div className="space-y-1.5">
<div className="flex items-center gap-2"> <div className="flex items-center gap-2">
<Label className="text-[var(--dg-text-secondary)] text-xs">执行结果</Label> <Label className="text-[var(--dg-text-secondary)] text-xs">{t('automation.execResult')}</Label>
<Badge <Badge
className={ className={
cmdResult.status === 'success' || cmdResult.status === 'done' || cmdResult.status === 'completed' cmdResult.status === 'success' || cmdResult.status === 'done' || cmdResult.status === 'completed'
@@ -356,7 +358,7 @@ export function AgentMonitor() {
</Badge> </Badge>
</div> </div>
<pre className="text-xs text-[var(--dg-text-secondary)] font-mono whitespace-pre-wrap break-all bg-[var(--dg-bg-primary)] border border-[var(--dg-border)] rounded-lg p-3 max-h-48 overflow-auto"> <pre className="text-xs text-[var(--dg-text-secondary)] font-mono whitespace-pre-wrap break-all bg-[var(--dg-bg-primary)] border border-[var(--dg-border)] rounded-lg p-3 max-h-48 overflow-auto">
{cmdResult.result || cmdResult.output || cmdResult.error || '无输出'} {cmdResult.result || cmdResult.output || cmdResult.error || t('agent.agentmonitor.s26d45b')}
</pre> </pre>
</div> </div>
)} )}
@@ -372,9 +374,9 @@ export function AgentMonitor() {
className="bg-blue-600 hover:bg-blue-700 text-white" className="bg-blue-600 hover:bg-blue-700 text-white"
> >
{cmdSubmitting ? ( {cmdSubmitting ? (
<><Loader2 className="h-4 w-4 mr-1.5 animate-spin" />执行中</> <><Loader2 className="h-4 w-4 mr-1.5 animate-spin" />{t('common.executing')}</>
) : ( ) : (
<><Terminal className="h-4 w-4 mr-1.5" />执行</> <><Terminal className="h-4 w-4 mr-1.5" />{t('common.execute')}</>
)} )}
</Button> </Button>
</DialogFooter> </DialogFooter>
@@ -389,6 +391,7 @@ export function AgentMonitor() {
// ============ 指标条子组件 ============ // ============ 指标条子组件 ============
function MetricBar({ icon: Icon, label, value }: { icon: ComponentType<{ className?: string }>; label: string; value: number }) { function MetricBar({ icon: Icon, label, value }: { icon: ComponentType<{ className?: string }>; label: string; value: number }) {
const { t } = useTranslation();
return ( return (
<div className="flex items-center gap-2"> <div className="flex items-center gap-2">
<Icon className="h-3.5 w-3.5 dg-text-muted shrink-0" /> <Icon className="h-3.5 w-3.5 dg-text-muted shrink-0" />
@@ -24,6 +24,7 @@ import {
import { Loader2 } from 'lucide-react'; import { Loader2 } from 'lucide-react';
import { METRIC_OPTIONS, OPERATOR_OPTIONS, SEVERITY_OPTIONS } from './agentAlertHelper'; import { METRIC_OPTIONS, OPERATOR_OPTIONS, SEVERITY_OPTIONS } from './agentAlertHelper';
import type { JsonData } from '@/types/common'; import type { JsonData } from '@/types/common';
import { useTranslation } from 'react-i18next';
interface Props { interface Props {
open: boolean; open: boolean;
@@ -45,6 +46,7 @@ const DEFAULT_FORM = {
}; };
export function AgentRuleDialog({ open, onOpenChange, editingRule, onSuccess }: Props) { export function AgentRuleDialog({ open, onOpenChange, editingRule, onSuccess }: Props) {
const { t } = useTranslation();
const [ruleForm, setRuleForm] = useState({ ...DEFAULT_FORM }); const [ruleForm, setRuleForm] = useState({ ...DEFAULT_FORM });
const [saving, setSaving] = useState(false); const [saving, setSaving] = useState(false);
@@ -69,7 +71,7 @@ export function AgentRuleDialog({ open, onOpenChange, editingRule, onSuccess }:
const handleSave = async () => { const handleSave = async () => {
if (!ruleForm.name.trim()) { if (!ruleForm.name.trim()) {
toast.error('请输入规则名称'); toast.error(t('agent.agentruledialog.s40f3f1'));
return; return;
} }
setSaving(true); setSaving(true);
@@ -88,15 +90,15 @@ export function AgentRuleDialog({ open, onOpenChange, editingRule, onSuccess }:
} }
if (editingRule) { if (editingRule) {
await agentApi.updateRule(editingRule.id, payload); await agentApi.updateRule(editingRule.id, payload);
toast.success('规则已更新'); toast.success(t('agent.agentruledialog.sa716ef'));
} else { } else {
await agentApi.createRule(payload); await agentApi.createRule(payload);
toast.success('规则已创建'); toast.success(t('agent.agentruledialog.s5702a3'));
} }
onOpenChange(false); onOpenChange(false);
onSuccess(); onSuccess();
} catch (err) { } catch (err) {
toast.error(err?.message || '保存失败'); toast.error(err?.message || t('common.saveFailed'));
} finally { } finally {
setSaving(false); setSaving(false);
} }
@@ -106,24 +108,24 @@ export function AgentRuleDialog({ open, onOpenChange, editingRule, onSuccess }:
<Dialog open={open} onOpenChange={(v) => { if (!v) onOpenChange(false); }}> <Dialog open={open} onOpenChange={(v) => { if (!v) onOpenChange(false); }}>
<DialogContent className="max-w-md dg-card text-[var(--dg-text-primary)]"> <DialogContent className="max-w-md dg-card text-[var(--dg-text-primary)]">
<DialogHeader> <DialogHeader>
<DialogTitle className="text-[var(--dg-text-primary)]">{editingRule ? '编辑规则' : '新建规则'}</DialogTitle> <DialogTitle className="text-[var(--dg-text-primary)]">{editingRule ? t('monitor.editRule') : t('agent.agentruledialog.sf10ed4')}</DialogTitle>
<DialogDescription className="dg-text-secondary">配置 Agent 指标告警规则</DialogDescription> <DialogDescription className="dg-text-secondary">{t('agent.agentruledialog.s0cc0f6')}</DialogDescription>
</DialogHeader> </DialogHeader>
<div className="space-y-3"> <div className="space-y-3">
<div className="space-y-1.5"> <div className="space-y-1.5">
<Label className="text-[var(--dg-text-secondary)] text-xs">规则名称</Label> <Label className="text-[var(--dg-text-secondary)] text-xs">{t('monitor.ruleName')}</Label>
<Input <Input
value={ruleForm.name} value={ruleForm.name}
onChange={(e) => setRuleForm({ ...ruleForm, name: e.target.value })} onChange={(e) => setRuleForm({ ...ruleForm, name: e.target.value })}
placeholder="例如:CPU 使用率告警" placeholder=t('agent.agentruledialog.s5a0f7e')
className="h-9 dg-input" className="h-9 dg-input"
/> />
</div> </div>
<div className="grid grid-cols-2 gap-3"> <div className="grid grid-cols-2 gap-3">
<div className="space-y-1.5"> <div className="space-y-1.5">
<Label className="text-[var(--dg-text-secondary)] text-xs">监控指标</Label> <Label className="text-[var(--dg-text-secondary)] text-xs">{t('agent.agentruledialog.s9a51fb')}</Label>
<Select value={ruleForm.metric} onValueChange={(v) => setRuleForm({ ...ruleForm, metric: v })}> <Select value={ruleForm.metric} onValueChange={(v) => setRuleForm({ ...ruleForm, metric: v })}>
<SelectTrigger className="h-9 dg-input"> <SelectTrigger className="h-9 dg-input">
<SelectValue /> <SelectValue />
@@ -136,7 +138,7 @@ export function AgentRuleDialog({ open, onOpenChange, editingRule, onSuccess }:
</Select> </Select>
</div> </div>
<div className="space-y-1.5"> <div className="space-y-1.5">
<Label className="text-[var(--dg-text-secondary)] text-xs">严重程度</Label> <Label className="text-[var(--dg-text-secondary)] text-xs">{t('monitor.ruleSeverity')}</Label>
<Select value={ruleForm.severity} onValueChange={(v) => setRuleForm({ ...ruleForm, severity: v })}> <Select value={ruleForm.severity} onValueChange={(v) => setRuleForm({ ...ruleForm, severity: v })}>
<SelectTrigger className="h-9 dg-input"> <SelectTrigger className="h-9 dg-input">
<SelectValue /> <SelectValue />
@@ -153,7 +155,7 @@ export function AgentRuleDialog({ open, onOpenChange, editingRule, onSuccess }:
{ruleForm.metric !== 'offline' && ( {ruleForm.metric !== 'offline' && (
<div className="grid grid-cols-2 gap-3"> <div className="grid grid-cols-2 gap-3">
<div className="space-y-1.5"> <div className="space-y-1.5">
<Label className="text-[var(--dg-text-secondary)] text-xs">比较运算符</Label> <Label className="text-[var(--dg-text-secondary)] text-xs">{t('agent.agentruledialog.sd52f2c')}</Label>
<Select value={ruleForm.operator} onValueChange={(v) => setRuleForm({ ...ruleForm, operator: v })}> <Select value={ruleForm.operator} onValueChange={(v) => setRuleForm({ ...ruleForm, operator: v })}>
<SelectTrigger className="h-9 dg-input"> <SelectTrigger className="h-9 dg-input">
<SelectValue /> <SelectValue />
@@ -179,39 +181,39 @@ export function AgentRuleDialog({ open, onOpenChange, editingRule, onSuccess }:
{ruleForm.metric === 'port_down' && ( {ruleForm.metric === 'port_down' && (
<div className="space-y-1.5"> <div className="space-y-1.5">
<Label className="text-[var(--dg-text-secondary)] text-xs">监控端口</Label> <Label className="text-[var(--dg-text-secondary)] text-xs">{t('agent.agentruledialog.s4d1348')}</Label>
<Input <Input
type="number" type="number"
value={ruleForm.port} value={ruleForm.port}
onChange={(e) => setRuleForm({ ...ruleForm, port: e.target.value })} onChange={(e) => setRuleForm({ ...ruleForm, port: e.target.value })}
placeholder="例如:8080" placeholder=t('agent.agentruledialog.s77565e')
className="h-9 dg-input" className="h-9 dg-input"
/> />
</div> </div>
)} )}
<div className="space-y-1.5"> <div className="space-y-1.5">
<Label className="text-[var(--dg-text-secondary)] text-xs">持续时间(秒)</Label> <Label className="text-[var(--dg-text-secondary)] text-xs">{t('agent.agentruledialog.sb1551d')}</Label>
<Input <Input
type="number" type="number"
value={ruleForm.duration} value={ruleForm.duration}
onChange={(e) => setRuleForm({ ...ruleForm, duration: e.target.value })} onChange={(e) => setRuleForm({ ...ruleForm, duration: e.target.value })}
placeholder="指标持续超限多久后告警" placeholder=t('agent.agentruledialog.sd140c7')
className="h-9 dg-input" className="h-9 dg-input"
/> />
</div> </div>
<div className="flex items-center justify-between"> <div className="flex items-center justify-between">
<Label className="text-[var(--dg-text-secondary)] text-xs">启用规则</Label> <Label className="text-[var(--dg-text-secondary)] text-xs">{t('agent.agentruledialog.sfd2ea0')}</Label>
<Switch checked={ruleForm.enabled} onCheckedChange={(v) => setRuleForm({ ...ruleForm, enabled: v })} /> <Switch checked={ruleForm.enabled} onCheckedChange={(v) => setRuleForm({ ...ruleForm, enabled: v })} />
</div> </div>
</div> </div>
<DialogFooter className="gap-2"> <DialogFooter className="gap-2">
<Button variant="outline" onClick={() => onOpenChange(false)} className="border-[var(--dg-border)] text-[var(--dg-text-secondary)]">取消</Button> <Button variant="outline" onClick={() => onOpenChange(false)} className="border-[var(--dg-border)] text-[var(--dg-text-secondary)]">{t('common.cancel')}</Button>
<Button onClick={handleSave} disabled={saving} className="bg-blue-600 hover:bg-blue-700 text-white"> <Button onClick={handleSave} disabled={saving} className="bg-blue-600 hover:bg-blue-700 text-white">
{saving ? <Loader2 className="h-4 w-4 mr-1.5 animate-spin" /> : null} {saving ? <Loader2 className="h-4 w-4 mr-1.5 animate-spin" /> : null}
{editingRule ? '保存' : '创建'} {editingRule ? i18n.t('common.save') : i18n.t('common.create')}
</Button> </Button>
</DialogFooter> </DialogFooter>
</DialogContent> </DialogContent>
+23 -21
View File
@@ -14,6 +14,7 @@ import { Label } from '@/components/ui/label';
import { Copy, Check, Terminal, Download, Settings, Play, Cpu, Zap, Loader2, Server, Shield } from 'lucide-react'; import { Copy, Check, Terminal, Download, Settings, Play, Cpu, Zap, Loader2, Server, Shield } from 'lucide-react';
import { serverApi } from '@/api'; import { serverApi } from '@/api';
import { toast } from 'sonner'; import { toast } from 'sonner';
import { useTranslation } from 'react-i18next';
interface AgentWizardProps { interface AgentWizardProps {
open: boolean; open: boolean;
@@ -40,6 +41,7 @@ function detectServerAddress() {
} }
export function AgentWizard({ open, onOpenChange, server, onStart, onInstalled, onFailed }: AgentWizardProps) { export function AgentWizard({ open, onOpenChange, server, onStart, onInstalled, onFailed }: AgentWizardProps) {
const { t } = useTranslation();
const token = useUserStore((s) => s.token) || '<YOUR_TOKEN>'; const token = useUserStore((s) => s.token) || '<YOUR_TOKEN>';
const origin = detectServerAddress(); const origin = detectServerAddress();
const [copied, setCopied] = useState(false); const [copied, setCopied] = useState(false);
@@ -104,10 +106,10 @@ export function AgentWizard({ open, onOpenChange, server, onStart, onInstalled,
if (success) { if (success) {
setCopied(true); setCopied(true);
toast.success('安装命令已复制到剪贴板,粘贴到目标主机执行'); toast.success(t('agent.agentwizard.s19ee00'));
setTimeout(() => setCopied(false), 3000); setTimeout(() => setCopied(false), 3000);
} else { } else {
toast.error('自动复制失败,请在下方手动全选复制 (Ctrl+A → Ctrl+C)'); toast.error(t('agent.agentwizard.s7ac41b'));
setShowManualInput(true); setShowManualInput(true);
} }
}; };
@@ -117,19 +119,19 @@ export function AgentWizard({ open, onOpenChange, server, onStart, onInstalled,
const manualSteps = [ const manualSteps = [
{ {
icon: Download, icon: Download,
title: '1. 下载二进制', title: t('agent.agentwizard.s8c59e0'),
commands: [ commands: [
`curl -fsSL ${binaryUrl} -o /usr/local/bin/aiops-agent`, `curl -fsSL ${binaryUrl} -o /usr/local/bin/aiops-agent`,
], ],
}, },
{ {
icon: Settings, icon: Settings,
title: '2. 赋予执行权限', title: t('agent.agentwizard.s2f17bf'),
commands: ['chmod +x /usr/local/bin/aiops-agent'], commands: ['chmod +x /usr/local/bin/aiops-agent'],
}, },
{ {
icon: Cpu, icon: Cpu,
title: '3. 创建 systemd 服务', title: t('agent.agentwizard.s03fa00'),
commands: [ commands: [
`cat > /etc/systemd/system/aiops-agent.service << 'EOF'`, `cat > /etc/systemd/system/aiops-agent.service << 'EOF'`,
`[Unit]`, `[Unit]`,
@@ -149,7 +151,7 @@ export function AgentWizard({ open, onOpenChange, server, onStart, onInstalled,
}, },
{ {
icon: Play, icon: Play,
title: '4. 启动并设置开机自启', title: t('agent.agentwizard.s84bd81'),
commands: [ commands: [
'systemctl daemon-reload', 'systemctl daemon-reload',
'systemctl enable --now aiops-agent', 'systemctl enable --now aiops-agent',
@@ -163,7 +165,7 @@ export function AgentWizard({ open, onOpenChange, server, onStart, onInstalled,
const handleSshInstall = async () => { const handleSshInstall = async () => {
if (!server || !token) return; if (!server || !token) return;
if (needsCreds && !sshPassword && !sshKey) { if (needsCreds && !sshPassword && !sshKey) {
toast.error('请填写 SSH 登录凭据(密码或密钥)'); toast.error(t('agent.agentwizard.s6cfe96'));
return; return;
} }
setSshInstalling(true); setSshInstalling(true);
@@ -182,11 +184,11 @@ export function AgentWizard({ open, onOpenChange, server, onStart, onInstalled,
: undefined; : undefined;
// 优先尝试异步批量接口,即使单台也后台执行 // 优先尝试异步批量接口,即使单台也后台执行
await serverApi.batchInstallAgent([server.id], token, credentials); await serverApi.batchInstallAgent([server.id], token, credentials);
toast.success(`${server.hostname}: 已提交 Agent 安装任务,后台执行中…`); toast.success(t('agent.agentwizard.s4c0811', { server.hostname: server.hostname }));
onInstalled?.(server.id); onInstalled?.(server.id);
onOpenChange(false); onOpenChange(false);
} catch (e) { } catch (e) {
const msg = e?.message || '安装失败'; const msg = e?.message || t('agent.installFailed');
toast.error(`${server.hostname} ${msg}`); toast.error(`${server.hostname} ${msg}`);
onFailed?.(server.id, msg); onFailed?.(server.id, msg);
} finally { } finally {
@@ -199,12 +201,12 @@ export function AgentWizard({ open, onOpenChange, server, onStart, onInstalled,
<DialogContent className="max-w-2xl dg-card text-[var(--dg-text-primary)]"> <DialogContent className="max-w-2xl dg-card text-[var(--dg-text-primary)]">
<DialogHeader> <DialogHeader>
<DialogTitle className="text-[var(--dg-text-primary)]"> <DialogTitle className="text-[var(--dg-text-primary)]">
{server ? `部署 Agent → ${server.hostname}` : '部署 Agent'} {server ? t('agent.agentwizard.s78196e', { server.hostname: server.hostname }) : t('agent.agentwizard.s812cc1')}
</DialogTitle> </DialogTitle>
<DialogDescription className="dg-text-secondary"> <DialogDescription className="dg-text-secondary">
{server {server
? `目标主机 ${server.hostname} (${server.ip}),选择安装方式:` ? t('agent.agentwizard.s94a807', { server.hostname: server.hostname, server.ip: server.ip })
: '在目标主机上执行以下命令即可完成 Agent 安装与注册' : t('agent.agentwizard.sed0c1b')
} }
</DialogDescription> </DialogDescription>
</DialogHeader> </DialogHeader>
@@ -246,7 +248,7 @@ export function AgentWizard({ open, onOpenChange, server, onStart, onInstalled,
variant="ghost" variant="ghost"
onClick={handleCopy} onClick={handleCopy}
className="absolute top-2 right-2 h-8 w-8 dg-text-secondary hover:text-[var(--dg-text-primary)] hover:bg-[var(--dg-bg-hover)]" className="absolute top-2 right-2 h-8 w-8 dg-text-secondary hover:text-[var(--dg-text-primary)] hover:bg-[var(--dg-bg-hover)]"
title="复制到剪贴板" title=t('agent.agentwizard.s564be0')
> >
{copied ? <Check className="h-4 w-4 dg-text-green" /> : <Copy className="h-4 w-4" />} {copied ? <Check className="h-4 w-4 dg-text-green" /> : <Copy className="h-4 w-4" />}
</Button> </Button>
@@ -279,8 +281,8 @@ export function AgentWizard({ open, onOpenChange, server, onStart, onInstalled,
{!server ? ( {!server ? (
<div className="text-center py-12 dg-text-secondary"> <div className="text-center py-12 dg-text-secondary">
<Server className="h-10 w-10 mx-auto mb-3 opacity-50" /> <Server className="h-10 w-10 mx-auto mb-3 opacity-50" />
<p className="text-sm font-medium mb-1">未选择目标主机</p> <p className="text-sm font-medium mb-1">{t('agent.agentwizard.sc9b7ee')}</p>
<p className="text-xs">请先在主机列表中勾选一台主机,再点击「安装 Agent」打开此页面</p> <p className="text-xs">{t('agent.agentwizard.s12a111')}</p>
</div> </div>
) : ( ) : (
<> <>
@@ -298,11 +300,11 @@ export function AgentWizard({ open, onOpenChange, server, onStart, onInstalled,
<div className="mb-4 p-3 rounded-lg bg-amber-950/30 border border-amber-800/40 space-y-3"> <div className="mb-4 p-3 rounded-lg bg-amber-950/30 border border-amber-800/40 space-y-3">
<div className="flex items-center gap-2 text-xs text-amber-300/80"> <div className="flex items-center gap-2 text-xs text-amber-300/80">
<Shield className="h-3.5 w-3.5" /> <Shield className="h-3.5 w-3.5" />
<span>该服务器未配置 SSH 凭据,请填写以下信息(首次连接成功后自动保存)</span> <span>{t('agent.agentwizard.seb55df')}</span>
</div> </div>
<div className="grid grid-cols-2 gap-2"> <div className="grid grid-cols-2 gap-2">
<div> <div>
<Label className="text-xs dg-text-secondary">用户名</Label> <Label className="text-xs dg-text-secondary">{t('login.username')}</Label>
<Input <Input
value={sshUsername} value={sshUsername}
onChange={e => setSshUsername(e.target.value)} onChange={e => setSshUsername(e.target.value)}
@@ -312,7 +314,7 @@ export function AgentWizard({ open, onOpenChange, server, onStart, onInstalled,
</div> </div>
<div className="flex items-end gap-1"> <div className="flex items-end gap-1">
<div className="flex-1"> <div className="flex-1">
<Label className="text-xs dg-text-secondary">密码</Label> <Label className="text-xs dg-text-secondary">{t('login.password')}</Label>
<Input <Input
type="password" type="password"
value={sshPassword} value={sshPassword}
@@ -321,7 +323,7 @@ export function AgentWizard({ open, onOpenChange, server, onStart, onInstalled,
className="h-8 text-sm dg-input text-[var(--dg-text-primary)] mt-1" className="h-8 text-sm dg-input text-[var(--dg-text-primary)] mt-1"
/> />
</div> </div>
<span className="text-xs dg-text-muted px-1 pb-1">或</span> <span className="text-xs dg-text-muted px-1 pb-1">{t('common.logicalOr')}</span>
<Button variant="ghost" size="sm" <Button variant="ghost" size="sm"
onClick={() => { setAuthType('key'); setSshPassword(''); }} onClick={() => { setAuthType('key'); setSshPassword(''); }}
className={`text-xs h-7 px-2 ${authType==='key'?'dg-text-blue':'dg-text-muted'}`}> className={`text-xs h-7 px-2 ${authType==='key'?'dg-text-blue':'dg-text-muted'}`}>
@@ -331,7 +333,7 @@ export function AgentWizard({ open, onOpenChange, server, onStart, onInstalled,
</div> </div>
{authType === 'key' && ( {authType === 'key' && (
<div> <div>
<Label className="text-xs dg-text-secondary">SSH 私钥(PEM 格式)</Label> <Label className="text-xs dg-text-secondary">{t('agent.agentwizard.s749be3')}</Label>
<textarea <textarea
value={sshKey} value={sshKey}
onChange={e => setSshKey(e.target.value)} onChange={e => setSshKey(e.target.value)}
@@ -360,7 +362,7 @@ export function AgentWizard({ open, onOpenChange, server, onStart, onInstalled,
) : ( ) : (
<> <>
<Zap className="h-4 w-4 mr-2" /> <Zap className="h-4 w-4 mr-2" />
{needsCreds ? '连接并安装 Agent(凭据将自动保存)' : '一键安装 Agent'} {needsCreds ? t('agent.agentwizard.sce2f53') : t('agent.agentwizard.s9866eb')}
</> </>
)} )}
</Button> </Button>
@@ -30,6 +30,7 @@ import {
ResponsiveContainer, ResponsiveContainer,
} from 'recharts'; } from 'recharts';
import type { JsonData } from '@/types/common'; import type { JsonData } from '@/types/common';
import { useTranslation } from 'react-i18next';
export function HostDetailDialog({ export function HostDetailDialog({
host, host,
@@ -40,6 +41,7 @@ export function HostDetailDialog({
onClose: () => void; onClose: () => void;
onCommand: (hostname: string) => void; onCommand: (hostname: string) => void;
}) { }) {
const { t } = useTranslation();
const [history, setHistory] = useState<JsonData[]>([]); const [history, setHistory] = useState<JsonData[]>([]);
const [loading, setLoading] = useState(false); const [loading, setLoading] = useState(false);
const [hours, setHours] = useState(1); const [hours, setHours] = useState(1);
@@ -78,21 +80,21 @@ export function HostDetailDialog({
<Server className="h-5 w-5 dg-text-blue" /> <Server className="h-5 w-5 dg-text-blue" />
{host.hostname} {host.hostname}
{online ? ( {online ? (
<Badge className="bg-emerald-500/15 dg-text-green border border-emerald-500/30">在线</Badge> <Badge className="bg-emerald-500/15 dg-text-green border border-emerald-500/30">{t('common.online')}</Badge>
) : ( ) : (
<Badge className="bg-red-500/15 dg-text-red border border-red-500/30">离线</Badge> <Badge className="bg-red-500/15 dg-text-red border border-red-500/30">{t('common.offline')}</Badge>
)} )}
</DialogTitle> </DialogTitle>
<DialogDescription className="sr-only">查看主机详情和指标趋势</DialogDescription> <DialogDescription className="sr-only">{t('agent.hostdetaildialog.sffa4f7')}</DialogDescription>
</DialogHeader> </DialogHeader>
<div className="space-y-4"> <div className="space-y-4">
{/* 基本信息 */} {/* 基本信息 */}
<div className="grid grid-cols-2 md:grid-cols-4 gap-3 text-sm"> <div className="grid grid-cols-2 md:grid-cols-4 gap-3 text-sm">
<InfoCell label="IP 地址" value={host.ip || '--'} /> <InfoCell label=t('agent.agentIp') value={host.ip || '--'} />
<InfoCell label="操作系统" value={host.os || host.platform || '--'} /> <InfoCell label=t('server.csv.os') value={host.os || host.platform || '--'} />
<InfoCell label="最后上报" value={timeAgo(host.last_report || host.last_reported_at || host.updated_at)} /> <InfoCell label=t('agent.agentLastSeen') value={timeAgo(host.last_report || host.last_reported_at || host.updated_at)} />
<InfoCell label="端口数" value={String(ports.length)} /> <InfoCell label=t('agent.hostdetaildialog.s6ad4fc') value={String(ports.length)} />
</div> </div>
{/* 趋势图 */} {/* 趋势图 */}
@@ -107,9 +109,9 @@ export function HostDetailDialog({
<SelectValue /> <SelectValue />
</SelectTrigger> </SelectTrigger>
<SelectContent className="dg-input"> <SelectContent className="dg-input">
<SelectItem value="1">最近 1 小时</SelectItem> <SelectItem value="1">{t('agent.hostdetaildialog.s3851af')}</SelectItem>
<SelectItem value="6">最近 6 小时</SelectItem> <SelectItem value="6">{t('agent.hostdetaildialog.s2d59b1')}</SelectItem>
<SelectItem value="24">最近 24 小时</SelectItem> <SelectItem value="24">{t('agent.hostdetaildialog.s768a1b')}</SelectItem>
</SelectContent> </SelectContent>
</Select> </Select>
</div> </div>
@@ -119,7 +121,7 @@ export function HostDetailDialog({
<Loader2 className="h-5 w-5 animate-spin dg-text-muted" /> <Loader2 className="h-5 w-5 animate-spin dg-text-muted" />
</div> </div>
) : chartData.length === 0 ? ( ) : chartData.length === 0 ? (
<div className="h-full flex items-center justify-center text-sm dg-text-muted">暂无历史数据</div> <div className="h-full flex items-center justify-center text-sm dg-text-muted">{t('agent.hostdetaildialog.sdc73db')}</div>
) : ( ) : (
<ResponsiveContainer width="100%" height="100%"> <ResponsiveContainer width="100%" height="100%">
<AreaChart data={chartData} margin={{ top: 5, right: 5, bottom: 0, left: -20 }}> <AreaChart data={chartData} margin={{ top: 5, right: 5, bottom: 0, left: -20 }}>
@@ -144,8 +146,8 @@ export function HostDetailDialog({
contentStyle={{ backgroundColor: '#0f172a', border: '1px solid #1e293b', borderRadius: '6px', color: '#f8fafc', fontSize: '12px' }} contentStyle={{ backgroundColor: '#0f172a', border: '1px solid #1e293b', borderRadius: '6px', color: '#f8fafc', fontSize: '12px' }}
/> />
<Area type="monotone" dataKey="cpu" stroke="#3b82f6" fill="url(#gCpu)" name="CPU" /> <Area type="monotone" dataKey="cpu" stroke="#3b82f6" fill="url(#gCpu)" name="CPU" />
<Area type="monotone" dataKey="mem" stroke="#10b981" fill="url(#gMem)" name="内存" /> <Area type="monotone" dataKey="mem" stroke="#10b981" fill="url(#gMem)" name=t('k8s.pods.memory') />
<Area type="monotone" dataKey="disk" stroke="#f59e0b" fill="url(#gDisk)" name="磁盘" /> <Area type="monotone" dataKey="disk" stroke="#f59e0b" fill="url(#gDisk)" name=t('dashboard.topUsage.disk') />
</AreaChart> </AreaChart>
</ResponsiveContainer> </ResponsiveContainer>
)} )}
@@ -159,7 +161,7 @@ export function HostDetailDialog({
端口发现 ({ports.length}) 端口发现 ({ports.length})
</span> </span>
{ports.length === 0 ? ( {ports.length === 0 ? (
<p className="text-xs dg-text-muted">暂无端口数据</p> <p className="text-xs dg-text-muted">{t('agent.hostdetaildialog.se7887d')}</p>
) : ( ) : (
<div className="flex flex-wrap gap-1.5 max-h-32 overflow-y-auto"> <div className="flex flex-wrap gap-1.5 max-h-32 overflow-y-auto">
{ports.map((p, idx) => ( {ports.map((p, idx) => (
@@ -191,6 +193,7 @@ export function HostDetailDialog({
} }
function InfoCell({ label, value }: { label: string; value: string }) { function InfoCell({ label, value }: { label: string; value: string }) {
const { t } = useTranslation();
return ( return (
<div className="bg-[var(--dg-bg-primary)] border border-[var(--dg-border)] rounded-lg px-3 py-2"> <div className="bg-[var(--dg-bg-primary)] border border-[var(--dg-border)] rounded-lg px-3 py-2">
<div className="text-xs dg-text-muted">{label}</div> <div className="text-xs dg-text-muted">{label}</div>
@@ -5,42 +5,43 @@ import {
Activity, Gauge, Timer, Activity, Gauge, Timer,
} from 'lucide-react'; } from 'lucide-react';
import type { JsonData } from '@/types/common'; import type { JsonData } from '@/types/common';
import i18n from '@/i18n';
// 主机监控指标(与后端 alert_engine 对齐)// Logan.Li // 主机监控指标(与后端 alert_engine 对齐)// Logan.Li
export const METRIC_OPTIONS = [ export const METRIC_OPTIONS = [
{ value: 'cpu', label: 'CPU 使用率', icon: Cpu }, { value: 'cpu', label: i18n.t('monitor.hostCpu'), icon: Cpu },
{ value: 'cpu_iowait', label: 'CPU IO 等待', icon: Cpu }, { value: 'cpu_iowait', label: i18n.t('agent.agentalerthelper.sc1eec3'), icon: Cpu },
{ value: 'mem', label: '内存使用率', icon: MemoryStick }, { value: 'mem', label: i18n.t('monitor.hostMemory'), icon: MemoryStick },
{ value: 'mem_available', label: '可用内存(GB)', icon: MemoryStick }, { value: 'mem_available', label: i18n.t('agent.agentalerthelper.sa23fcd'), icon: MemoryStick },
{ value: 'swap', label: 'Swap 使用率', icon: MemoryStick }, { value: 'swap', label: i18n.t('agent.agentalerthelper.sa2f910'), icon: MemoryStick },
{ value: 'load1', label: '1分钟负载', icon: Gauge }, { value: 'load1', label: i18n.t('agent.agentalerthelper.sf23ce8'), icon: Gauge },
{ value: 'disk', label: '磁盘使用率', icon: HardDrive }, { value: 'disk', label: i18n.t('monitor.hostDisk'), icon: HardDrive },
{ value: 'disk_inode', label: 'Inode 使用率', icon: HardDrive }, { value: 'disk_inode', label: i18n.t('agent.agentalerthelper.sf7eade'), icon: HardDrive },
{ value: 'disk_io_util', label: '磁盘 IO 利用率', icon: HardDrive }, { value: 'disk_io_util', label: i18n.t('agent.agentalerthelper.s565a0e'), icon: HardDrive },
{ value: 'tcp_established', label: 'TCP 已建立', icon: Network }, { value: 'tcp_established', label: i18n.t('agent.agentalerthelper.s6d9639'), icon: Network },
{ value: 'tcp_time_wait', label: 'TCP TIME_WAIT', icon: Network }, { value: 'tcp_time_wait', label: 'TCP TIME_WAIT', icon: Network },
{ value: 'tcp_close_wait', label: 'TCP CLOSE_WAIT', icon: Network }, { value: 'tcp_close_wait', label: 'TCP CLOSE_WAIT', icon: Network },
{ value: 'net_rx_bps', label: '入网带宽', icon: Network }, { value: 'net_rx_bps', label: i18n.t('monitor.hostNetIn'), icon: Network },
{ value: 'net_tx_bps', label: '出网带宽', icon: Network }, { value: 'net_tx_bps', label: i18n.t('monitor.hostNetOut'), icon: Network },
{ value: 'net_rx_errors', label: '入网错误', icon: Network }, { value: 'net_rx_errors', label: i18n.t('agent.agentalerthelper.s8d73bf'), icon: Network },
{ value: 'fd', label: '文件描述符', icon: Activity }, { value: 'fd', label: i18n.t('monitor.hostFileDescriptor'), icon: Activity },
{ value: 'offline', label: '主机离线', icon: WifiOff }, { value: 'offline', label: i18n.t('agent.agentalerthelper.s8ed49a'), icon: WifiOff },
{ value: 'port_down', label: '端口不通', icon: Network }, { value: 'port_down', label: i18n.t('agent.agentalerthelper.sf62ce6'), icon: Network },
{ value: 'health_probe', label: '健康探针', icon: Timer }, { value: 'health_probe', label: i18n.t('kubernetes.container.probes'), icon: Timer },
]; ];
export const OPERATOR_OPTIONS = [ export const OPERATOR_OPTIONS = [
{ value: '>', label: '> 大于' }, { value: '>', label: i18n.t('agent.agentalerthelper.s552612') },
{ value: '<', label: '< 小于' }, { value: '<', label: i18n.t('agent.agentalerthelper.sdd29ed') },
{ value: '>=', label: '≥ 大于等于' }, { value: '>=', label: i18n.t('agent.agentalerthelper.sef2679') },
{ value: '<=', label: '≤ 小于等于' }, { value: '<=', label: i18n.t('agent.agentalerthelper.s847d07') },
{ value: '==', label: '= 等于' }, { value: '==', label: i18n.t('agent.agentalerthelper.s9cd6c2') },
]; ];
export const SEVERITY_OPTIONS = [ export const SEVERITY_OPTIONS = [
{ value: 'critical', label: '严重', color: 'bg-red-500/15 dg-text-red border-red-500/30' }, { value: 'critical', label: i18n.t('monitor.critical'), color: 'bg-red-500/15 dg-text-red border-red-500/30' },
{ value: 'warning', label: '警告', color: 'bg-amber-500/15 dg-text-yellow border-amber-500/30' }, { value: 'warning', label: i18n.t('common.warning'), color: 'bg-amber-500/15 dg-text-yellow border-amber-500/30' },
{ value: 'info', label: '提示', color: 'bg-blue-500/15 dg-text-blue border-blue-500/30' }, { value: 'info', label: i18n.t('common.info'), color: 'bg-blue-500/15 dg-text-blue border-blue-500/30' },
]; ];
export function getMetricLabel(metric: string) { export function getMetricLabel(metric: string) {
@@ -23,6 +23,7 @@ import { toast } from 'sonner';
import { billingApi } from '@/api'; import { billingApi } from '@/api';
import { providerLabels } from './CloudBillingHelpers'; import { providerLabels } from './CloudBillingHelpers';
import type { JsonData } from '@/types/common'; import type { JsonData } from '@/types/common';
import { useTranslation } from 'react-i18next';
const emptyRecord = { const emptyRecord = {
provider: 'aliyun', provider: 'aliyun',
@@ -42,6 +43,7 @@ interface Props {
} }
export function BillingRecordDialog({ open, onOpenChange, editingRecord, onSuccess }: Props) { export function BillingRecordDialog({ open, onOpenChange, editingRecord, onSuccess }: Props) {
const { t } = useTranslation();
const [form, setForm] = useState<JsonData>(emptyRecord); const [form, setForm] = useState<JsonData>(emptyRecord);
const [submitting, setSubmitting] = useState(false); const [submitting, setSubmitting] = useState(false);
@@ -65,7 +67,7 @@ export function BillingRecordDialog({ open, onOpenChange, editingRecord, onSucce
const handleSave = async () => { const handleSave = async () => {
if (!form.provider || !form.billing_date || !form.cost) { if (!form.provider || !form.billing_date || !form.cost) {
toast.error('请填写必填字段'); toast.error(t('cloud.billingrecorddialog.sd8a97c'));
return; return;
} }
setSubmitting(true); setSubmitting(true);
@@ -79,9 +81,9 @@ export function BillingRecordDialog({ open, onOpenChange, editingRecord, onSucce
} }
onOpenChange(false); onOpenChange(false);
onSuccess(); onSuccess();
toast('保存成功'); toast(t('common.savedSuccessfully'));
} catch (e) { } catch (e) {
toast.error('保存失败', { description: (e as JsonData).message }); toast.error(t('common.saveFailed'), { description: (e as JsonData).message });
} finally { } finally {
setSubmitting(false); setSubmitting(false);
} }
@@ -91,13 +93,13 @@ export function BillingRecordDialog({ open, onOpenChange, editingRecord, onSucce
<Dialog open={open} onOpenChange={onOpenChange}> <Dialog open={open} onOpenChange={onOpenChange}>
<DialogContent className="max-w-md"> <DialogContent className="max-w-md">
<DialogHeader> <DialogHeader>
<DialogTitle>{editingRecord ? '编辑成本记录' : '记录成本'}</DialogTitle> <DialogTitle>{editingRecord ? t('cloud.billingrecorddialog.s3c91e4') : t('cloud.recordCost')}</DialogTitle>
<DialogDescription>记录一条每日云资源成本</DialogDescription> <DialogDescription>{t('cloud.billingrecorddialog.s09e541')}</DialogDescription>
</DialogHeader> </DialogHeader>
<div className="space-y-3"> <div className="space-y-3">
<div className="grid grid-cols-2 gap-3"> <div className="grid grid-cols-2 gap-3">
<div> <div>
<Label className="text-sm text-[var(--dg-text-secondary)]">厂商 *</Label> <Label className="text-sm text-[var(--dg-text-secondary)]">{t('cloud.billingrecorddialog.sb11d84')}</Label>
<Select value={form.provider} onValueChange={(v) => setForm({ ...form, provider: v })}> <Select value={form.provider} onValueChange={(v) => setForm({ ...form, provider: v })}>
<SelectTrigger className="mt-1"><SelectValue /></SelectTrigger> <SelectTrigger className="mt-1"><SelectValue /></SelectTrigger>
<SelectContent> <SelectContent>
@@ -108,37 +110,37 @@ export function BillingRecordDialog({ open, onOpenChange, editingRecord, onSucce
</Select> </Select>
</div> </div>
<div> <div>
<Label className="text-sm text-[var(--dg-text-secondary)]">日期 *</Label> <Label className="text-sm text-[var(--dg-text-secondary)]">{t('cloud.billingrecorddialog.s3abdef')}</Label>
<Input type="date" className="mt-1" value={form.billing_date} onChange={(e) => setForm({ ...form, billing_date: e.target.value })} /> <Input type="date" className="mt-1" value={form.billing_date} onChange={(e) => setForm({ ...form, billing_date: e.target.value })} />
</div> </div>
</div> </div>
<div className="grid grid-cols-2 gap-3"> <div className="grid grid-cols-2 gap-3">
<div> <div>
<Label className="text-sm text-[var(--dg-text-secondary)]">费用(元) *</Label> <Label className="text-sm text-[var(--dg-text-secondary)]">{t('cloud.billingrecorddialog.s6f2526')}</Label>
<Input type="number" step="0.01" className="mt-1" placeholder="0.00" value={form.cost} onChange={(e) => setForm({ ...form, cost: e.target.value })} /> <Input type="number" step="0.01" className="mt-1" placeholder="0.00" value={form.cost} onChange={(e) => setForm({ ...form, cost: e.target.value })} />
</div> </div>
<div> <div>
<Label className="text-sm text-[var(--dg-text-secondary)]">服务</Label> <Label className="text-sm text-[var(--dg-text-secondary)]">{t('cloud.colService')}</Label>
<Input className="mt-1" placeholder="ECS, RDS..." value={form.service} onChange={(e) => setForm({ ...form, service: e.target.value })} /> <Input className="mt-1" placeholder="ECS, RDS..." value={form.service} onChange={(e) => setForm({ ...form, service: e.target.value })} />
</div> </div>
</div> </div>
<div className="grid grid-cols-2 gap-3"> <div className="grid grid-cols-2 gap-3">
<div> <div>
<Label className="text-sm text-[var(--dg-text-secondary)]">区域</Label> <Label className="text-sm text-[var(--dg-text-secondary)]">{t('cloud.colRegion')}</Label>
<Input className="mt-1" placeholder="cn-hangzhou" value={form.region} onChange={(e) => setForm({ ...form, region: e.target.value })} /> <Input className="mt-1" placeholder="cn-hangzhou" value={form.region} onChange={(e) => setForm({ ...form, region: e.target.value })} />
</div> </div>
<div> <div>
<Label className="text-sm text-[var(--dg-text-secondary)]">账号名称</Label> <Label className="text-sm text-[var(--dg-text-secondary)]">{t('cloud.accountName')}</Label>
<Input className="mt-1" placeholder="主账号" value={form.account_name} onChange={(e) => setForm({ ...form, account_name: e.target.value })} /> <Input className="mt-1" placeholder=t('cloud.billingrecorddialog.s001079') value={form.account_name} onChange={(e) => setForm({ ...form, account_name: e.target.value })} />
</div> </div>
</div> </div>
<div> <div>
<Label className="text-sm text-[var(--dg-text-secondary)]">备注</Label> <Label className="text-sm text-[var(--dg-text-secondary)]">{t('common.remark')}</Label>
<Input className="mt-1" placeholder="可选" value={form.description} onChange={(e) => setForm({ ...form, description: e.target.value })} /> <Input className="mt-1" placeholder=t('common.optional') value={form.description} onChange={(e) => setForm({ ...form, description: e.target.value })} />
</div> </div>
</div> </div>
<DialogFooter> <DialogFooter>
<Button variant="outline" onClick={() => onOpenChange(false)}>取消</Button> <Button variant="outline" onClick={() => onOpenChange(false)}>{t('common.cancel')}</Button>
<Button onClick={handleSave} disabled={submitting}> <Button onClick={handleSave} disabled={submitting}>
{submitting && <Loader2 className="h-4 w-4 mr-1 animate-spin" />} {submitting && <Loader2 className="h-4 w-4 mr-1 animate-spin" />}
保存 保存
@@ -24,6 +24,7 @@ import { toast } from 'sonner';
import { billingApi } from '@/api'; import { billingApi } from '@/api';
import { providerLabels } from './CloudBillingHelpers'; import { providerLabels } from './CloudBillingHelpers';
import type { JsonData } from '@/types/common'; import type { JsonData } from '@/types/common';
import { useTranslation } from 'react-i18next';
const emptyRule = { name: '', provider: '', metric: 'daily', threshold: '', operator: '>', enabled: true }; const emptyRule = { name: '', provider: '', metric: 'daily', threshold: '', operator: '>', enabled: true };
@@ -35,6 +36,7 @@ interface Props {
} }
export function BillingRuleDialog({ open, onOpenChange, editingRule, onSuccess }: Props) { export function BillingRuleDialog({ open, onOpenChange, editingRule, onSuccess }: Props) {
const { t } = useTranslation();
const [form, setForm] = useState<JsonData>(emptyRule); const [form, setForm] = useState<JsonData>(emptyRule);
const [submitting, setSubmitting] = useState(false); const [submitting, setSubmitting] = useState(false);
@@ -57,7 +59,7 @@ export function BillingRuleDialog({ open, onOpenChange, editingRule, onSuccess }
const handleSave = async () => { const handleSave = async () => {
if (!form.name || !form.threshold) { if (!form.name || !form.threshold) {
toast.error('请填写规则名称和阈值'); toast.error(t('cloud.billingruledialog.sd36855'));
return; return;
} }
setSubmitting(true); setSubmitting(true);
@@ -70,9 +72,9 @@ export function BillingRuleDialog({ open, onOpenChange, editingRule, onSuccess }
} }
onOpenChange(false); onOpenChange(false);
onSuccess(); onSuccess();
toast('保存成功'); toast(t('common.savedSuccessfully'));
} catch (e) { } catch (e) {
toast.error('保存失败', { description: (e as JsonData).message }); toast.error(t('common.saveFailed'), { description: (e as JsonData).message });
} finally { } finally {
setSubmitting(false); setSubmitting(false);
} }
@@ -82,21 +84,21 @@ export function BillingRuleDialog({ open, onOpenChange, editingRule, onSuccess }
<Dialog open={open} onOpenChange={onOpenChange}> <Dialog open={open} onOpenChange={onOpenChange}>
<DialogContent className="max-w-md"> <DialogContent className="max-w-md">
<DialogHeader> <DialogHeader>
<DialogTitle>{editingRule ? '编辑预警规则' : '添加预警规则'}</DialogTitle> <DialogTitle>{editingRule ? t('cloud.billingruledialog.sb8cfa0') : t('cloud.billingruledialog.sd58c54')}</DialogTitle>
<DialogDescription>设置成本阈值,超标时自动预警</DialogDescription> <DialogDescription>{t('cloud.billingruledialog.s75227f')}</DialogDescription>
</DialogHeader> </DialogHeader>
<div className="space-y-3"> <div className="space-y-3">
<div> <div>
<Label className="text-sm text-[var(--dg-text-secondary)]">规则名称 *</Label> <Label className="text-sm text-[var(--dg-text-secondary)]">{t('cloud.billingruledialog.s34fe90')}</Label>
<Input className="mt-1" placeholder="如:日成本超 500 元预警" value={form.name} onChange={(e) => setForm({ ...form, name: e.target.value })} /> <Input className="mt-1" placeholder=t('cloud.billingruledialog.sc147ac') value={form.name} onChange={(e) => setForm({ ...form, name: e.target.value })} />
</div> </div>
<div className="grid grid-cols-2 gap-3"> <div className="grid grid-cols-2 gap-3">
<div> <div>
<Label className="text-sm text-[var(--dg-text-secondary)]">厂商</Label> <Label className="text-sm text-[var(--dg-text-secondary)]">{t('common.vendor')}</Label>
<Select value={form.provider || 'all'} onValueChange={(v) => setForm({ ...form, provider: v === 'all' ? '' : v })}> <Select value={form.provider || 'all'} onValueChange={(v) => setForm({ ...form, provider: v === 'all' ? '' : v })}>
<SelectTrigger className="mt-1"><SelectValue /></SelectTrigger> <SelectTrigger className="mt-1"><SelectValue /></SelectTrigger>
<SelectContent> <SelectContent>
<SelectItem value="all">全部厂商</SelectItem> <SelectItem value="all">{t('cloud.billingruledialog.sc356f1')}</SelectItem>
{Object.entries(providerLabels).map(([k, v]) => ( {Object.entries(providerLabels).map(([k, v]) => (
<SelectItem key={k} value={k}>{v}</SelectItem> <SelectItem key={k} value={k}>{v}</SelectItem>
))} ))}
@@ -104,41 +106,41 @@ export function BillingRuleDialog({ open, onOpenChange, editingRule, onSuccess }
</Select> </Select>
</div> </div>
<div> <div>
<Label className="text-sm text-[var(--dg-text-secondary)]">指标</Label> <Label className="text-sm text-[var(--dg-text-secondary)]">{t('cloud.colMetric')}</Label>
<Select value={form.metric} onValueChange={(v) => setForm({ ...form, metric: v })}> <Select value={form.metric} onValueChange={(v) => setForm({ ...form, metric: v })}>
<SelectTrigger className="mt-1"><SelectValue /></SelectTrigger> <SelectTrigger className="mt-1"><SelectValue /></SelectTrigger>
<SelectContent> <SelectContent>
<SelectItem value="daily">日成本</SelectItem> <SelectItem value="daily">{t('cloud.dailyCost')}</SelectItem>
<SelectItem value="monthly">月累计</SelectItem> <SelectItem value="monthly">{t('cloud.monthlyAccumulated')}</SelectItem>
</SelectContent> </SelectContent>
</Select> </Select>
</div> </div>
</div> </div>
<div className="grid grid-cols-2 gap-3"> <div className="grid grid-cols-2 gap-3">
<div> <div>
<Label className="text-sm text-[var(--dg-text-secondary)]">比较</Label> <Label className="text-sm text-[var(--dg-text-secondary)]">{t('cloud.billingruledialog.sd7650e')}</Label>
<Select value={form.operator} onValueChange={(v) => setForm({ ...form, operator: v })}> <Select value={form.operator} onValueChange={(v) => setForm({ ...form, operator: v })}>
<SelectTrigger className="mt-1"><SelectValue /></SelectTrigger> <SelectTrigger className="mt-1"><SelectValue /></SelectTrigger>
<SelectContent> <SelectContent>
<SelectItem value=">">大于 &gt;</SelectItem> <SelectItem value=">">{t('cloud.billingruledialog.s3dba97')}</SelectItem>
<SelectItem value=">=">大于等于 &ge;</SelectItem> <SelectItem value=">=">{t('cloud.billingruledialog.s8e1e26')}</SelectItem>
<SelectItem value="<">小于 &lt;</SelectItem> <SelectItem value="<">{t('cloud.billingruledialog.s0196c1')}</SelectItem>
<SelectItem value="<=">小于等于 &le;</SelectItem> <SelectItem value="<=">{t('cloud.billingruledialog.s45c301')}</SelectItem>
</SelectContent> </SelectContent>
</Select> </Select>
</div> </div>
<div> <div>
<Label className="text-sm text-[var(--dg-text-secondary)]">阈值(元) *</Label> <Label className="text-sm text-[var(--dg-text-secondary)]">{t('cloud.billingruledialog.s11f9fb')}</Label>
<Input type="number" step="0.01" className="mt-1" placeholder="500.00" value={form.threshold} onChange={(e) => setForm({ ...form, threshold: e.target.value })} /> <Input type="number" step="0.01" className="mt-1" placeholder="500.00" value={form.threshold} onChange={(e) => setForm({ ...form, threshold: e.target.value })} />
</div> </div>
</div> </div>
<div className="flex items-center gap-2"> <div className="flex items-center gap-2">
<Switch checked={form.enabled} onCheckedChange={(v) => setForm({ ...form, enabled: v })} /> <Switch checked={form.enabled} onCheckedChange={(v) => setForm({ ...form, enabled: v })} />
<Label className="text-sm text-[var(--dg-text-secondary)]">启用</Label> <Label className="text-sm text-[var(--dg-text-secondary)]">{t('common.enable')}</Label>
</div> </div>
</div> </div>
<DialogFooter> <DialogFooter>
<Button variant="outline" onClick={() => onOpenChange(false)}>取消</Button> <Button variant="outline" onClick={() => onOpenChange(false)}>{t('common.cancel')}</Button>
<Button onClick={handleSave} disabled={submitting}> <Button onClick={handleSave} disabled={submitting}>
{submitting && <Loader2 className="h-4 w-4 mr-1 animate-spin" />} {submitting && <Loader2 className="h-4 w-4 mr-1 animate-spin" />}
保存 保存
@@ -1,12 +1,14 @@
import { type ReactNode } from 'react'; import { type ReactNode } from 'react';
import { TrendingUp, TrendingDown } from 'lucide-react'; import { TrendingUp, TrendingDown } from 'lucide-react';
import { useTranslation } from 'react-i18next';
import i18n from '@/i18n';
// 云厂商中文标签(主组件 + 弹窗共享) // Logan.Li // 云厂商中文标签(主组件 + 弹窗共享) // Logan.Li
export const providerLabels: Record<string, string> = { export const providerLabels: Record<string, string> = {
aliyun: '阿里云', aliyun: i18n.t('cloud.aliyun'),
tencent: '腾讯云', tencent: i18n.t('cloud.tencent'),
aws: 'AWS', aws: 'AWS',
huawei: '华为云', huawei: i18n.t('cloud.huawei'),
azure: 'Azure', azure: 'Azure',
}; };
@@ -29,6 +31,7 @@ export const providerColors: Record<string, string> = {
}; };
export function ProviderDot({ provider, className = 'w-2 h-2' }: { provider: string; className?: string }) { export function ProviderDot({ provider, className = 'w-2 h-2' }: { provider: string; className?: string }) {
const { t } = useTranslation();
return ( return (
<span <span
className={`rounded-full shrink-0 ${className}`} className={`rounded-full shrink-0 ${className}`}
@@ -49,6 +52,7 @@ export function StatCard({ icon, label, value, trend, trendLabel, alert }: {
trendLabel?: string; trendLabel?: string;
alert?: boolean; alert?: boolean;
}) { }) {
const { t } = useTranslation();
return ( return (
<div className={alert ? 'dg-alert-banner' : 'rounded-lg border border-[var(--border-default)] bg-[var(--surface-raised)]/50 p-4'}> <div className={alert ? 'dg-alert-banner' : 'rounded-lg border border-[var(--border-default)] bg-[var(--surface-raised)]/50 p-4'}>
<div className="flex items-center justify-between mb-2"> <div className="flex items-center justify-between mb-2">
@@ -68,8 +72,9 @@ export function StatCard({ icon, label, value, trend, trendLabel, alert }: {
} }
export function TrendChart({ data }: { data: { date: string; cost: number }[] }) { export function TrendChart({ data }: { data: { date: string; cost: number }[] }) {
const { t } = useTranslation();
if (data.length === 0) { if (data.length === 0) {
return <p className="text-sm dg-text-muted py-8 text-center">暂无数据</p>; return <p className="text-sm dg-text-muted py-8 text-center">{t('common.noData')}</p>;
} }
const max = Math.max(...data.map((d) => d.cost), 1); const max = Math.max(...data.map((d) => d.cost), 1);
const recent = data.slice(-30); const recent = data.slice(-30);
@@ -36,11 +36,13 @@ import { PageLoading } from '@/components/layout/PageLoading';
import { PageEmpty } from '@/components/layout/PageEmpty'; import { PageEmpty } from '@/components/layout/PageEmpty';
import { StatStrip } from '@/components/ui/stat-strip'; import { StatStrip } from '@/components/ui/stat-strip';
import type { JsonData } from '@/types/common'; import type { JsonData } from '@/types/common';
import { useTranslation } from 'react-i18next';
import i18n from '@/i18n';
const typeLabels: Record<string, string> = { const typeLabels: Record<string, string> = {
public: '公有云', public: i18n.t('cloud.platformmanager.s7ef31a'),
private: '私有云', private: i18n.t('cloud.privateCloud'),
hybrid: '混合云', hybrid: i18n.t('cloud.hybridCloud'),
}; };
const typeColors: Record<string, string> = { const typeColors: Record<string, string> = {
@@ -50,6 +52,7 @@ const typeColors: Record<string, string> = {
}; };
export function PlatformManager() { export function PlatformManager() {
const { t } = useTranslation();
const [platforms, setPlatforms] = useState<JsonData[]>([]); const [platforms, setPlatforms] = useState<JsonData[]>([]);
const [loading, setLoading] = useState(true); const [loading, setLoading] = useState(true);
const [searchQuery, setSearchQuery] = useState(''); const [searchQuery, setSearchQuery] = useState('');
@@ -137,7 +140,7 @@ export function PlatformManager() {
<div className="relative w-72"> <div className="relative w-72">
<Search className="absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 dg-text-muted" /> <Search className="absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 dg-text-muted" />
<Input <Input
placeholder="搜索平台名称或编码..." placeholder=t('cloud.platformmanager.s783a51')
value={searchQuery} value={searchQuery}
onChange={(e) => setSearchQuery(e.target.value)} onChange={(e) => setSearchQuery(e.target.value)}
className="pl-9 h-9 dg-input" className="pl-9 h-9 dg-input"
@@ -148,10 +151,10 @@ export function PlatformManager() {
<SelectValue /> <SelectValue />
</SelectTrigger> </SelectTrigger>
<SelectContent> <SelectContent>
<SelectItem value="all">全部类型</SelectItem> <SelectItem value="all">{t('deploy.label.allType')}</SelectItem>
<SelectItem value="public">公有云</SelectItem> <SelectItem value="public">{t('cloud.platformmanager.s7ef31a')}</SelectItem>
<SelectItem value="private">私有云</SelectItem> <SelectItem value="private">{t('cloud.privateCloud')}</SelectItem>
<SelectItem value="hybrid">混合云</SelectItem> <SelectItem value="hybrid">{t('cloud.hybridCloud')}</SelectItem>
</SelectContent> </SelectContent>
</Select> </Select>
</div> </div>
@@ -160,16 +163,16 @@ export function PlatformManager() {
return ( return (
<PageShell <PageShell
variant="list" variant="list"
title="云平台管理" title=t('cloud.title')
subtitle="管理公有云、私有云与混合云平台信息" subtitle=t('cloud.platformmanager.s701204')
icon={<CloudCog className="h-5 w-5" />} icon={<CloudCog className="h-5 w-5" />}
metrics={ metrics={
!loading ? ( !loading ? (
<StatStrip <StatStrip
items={[ items={[
{ label: '总计', value: stats.total, color: 'blue' }, { label: t('common.total'), value: stats.total, color: 'blue' },
{ label: '启用', value: stats.active, color: 'green' }, { label: t('common.enable'), value: stats.active, color: 'green' },
{ label: '公有云', value: stats.public, color: 'cyan' }, { label: t('cloud.platformmanager.s7ef31a'), value: stats.public, color: 'cyan' },
]} ]}
/> />
) : undefined ) : undefined
@@ -193,7 +196,7 @@ export function PlatformManager() {
) : filtered.length === 0 ? ( ) : filtered.length === 0 ? (
<PageEmpty <PageEmpty
icon={<CloudCog className="h-12 w-12" />} icon={<CloudCog className="h-12 w-12" />}
title="暂无云平台数据" title=t('cloud.platformmanager.sb9f478')
action={( action={(
<Button size="sm" className="dg-btn-primary" onClick={openCreate}> <Button size="sm" className="dg-btn-primary" onClick={openCreate}>
<Plus className="h-4 w-4 mr-1" /> <Plus className="h-4 w-4 mr-1" />
@@ -260,26 +263,26 @@ export function PlatformManager() {
<Dialog open={dialogOpen} onOpenChange={setDialogOpen}> <Dialog open={dialogOpen} onOpenChange={setDialogOpen}>
<DialogContent> <DialogContent>
<DialogHeader> <DialogHeader>
<DialogTitle>{editingItem ? '编辑云平台' : '添加云平台'}</DialogTitle> <DialogTitle>{editingItem ? t('cloud.platformmanager.sf83734') : t('cloud.platformmanager.s3f6f0c')}</DialogTitle>
<DialogDescription className="sr-only">描述</DialogDescription> <DialogDescription className="sr-only">{t('common.description')}</DialogDescription>
</DialogHeader> </DialogHeader>
<div className="space-y-4 py-2"> <div className="space-y-4 py-2">
<div className="grid grid-cols-2 gap-4"> <div className="grid grid-cols-2 gap-4">
<div className="space-y-1.5"> <div className="space-y-1.5">
<Label>平台名称 *</Label> <Label>{t('cloud.platformmanager.seac7fc')}</Label>
<Input <Input
value={formData.name} value={formData.name}
onChange={(e) => setFormData({ ...formData, name: e.target.value })} onChange={(e) => setFormData({ ...formData, name: e.target.value })}
placeholder="如:阿里云" placeholder=t('cloud.platformmanager.sa39d96')
className="dg-input" className="dg-input"
/> />
</div> </div>
<div className="space-y-1.5"> <div className="space-y-1.5">
<Label>编码 *</Label> <Label>{t('cloud.platformmanager.se21e27')}</Label>
<Input <Input
value={formData.code} value={formData.code}
onChange={(e) => setFormData({ ...formData, code: e.target.value })} onChange={(e) => setFormData({ ...formData, code: e.target.value })}
placeholder="如:aliyun" placeholder=t('cloud.platformmanager.s7b09b0')
className="dg-input" className="dg-input"
disabled={!!editingItem} disabled={!!editingItem}
/> />
@@ -287,33 +290,33 @@ export function PlatformManager() {
</div> </div>
<div className="grid grid-cols-2 gap-4"> <div className="grid grid-cols-2 gap-4">
<div className="space-y-1.5"> <div className="space-y-1.5">
<Label>类型</Label> <Label>{t('common.type')}</Label>
<Select value={formData.type} onValueChange={(v) => setFormData({ ...formData, type: v })}> <Select value={formData.type} onValueChange={(v) => setFormData({ ...formData, type: v })}>
<SelectTrigger className="dg-input"> <SelectTrigger className="dg-input">
<SelectValue /> <SelectValue />
</SelectTrigger> </SelectTrigger>
<SelectContent> <SelectContent>
<SelectItem value="public">公有云</SelectItem> <SelectItem value="public">{t('cloud.platformmanager.s7ef31a')}</SelectItem>
<SelectItem value="private">私有云</SelectItem> <SelectItem value="private">{t('cloud.privateCloud')}</SelectItem>
<SelectItem value="hybrid">混合云</SelectItem> <SelectItem value="hybrid">{t('cloud.hybridCloud')}</SelectItem>
</SelectContent> </SelectContent>
</Select> </Select>
</div> </div>
<div className="space-y-1.5"> <div className="space-y-1.5">
<Label>状态</Label> <Label>{t('common.status')}</Label>
<Select value={formData.status} onValueChange={(v) => setFormData({ ...formData, status: v })}> <Select value={formData.status} onValueChange={(v) => setFormData({ ...formData, status: v })}>
<SelectTrigger className="dg-input"> <SelectTrigger className="dg-input">
<SelectValue /> <SelectValue />
</SelectTrigger> </SelectTrigger>
<SelectContent> <SelectContent>
<SelectItem value="active">启用</SelectItem> <SelectItem value="active">{t('common.enable')}</SelectItem>
<SelectItem value="inactive">禁用</SelectItem> <SelectItem value="inactive">{t('common.disable')}</SelectItem>
</SelectContent> </SelectContent>
</Select> </Select>
</div> </div>
</div> </div>
<div className="space-y-1.5"> <div className="space-y-1.5">
<Label>官网地址</Label> <Label>{t('cloud.platformmanager.saf587e')}</Label>
<Input <Input
value={formData.website} value={formData.website}
onChange={(e) => setFormData({ ...formData, website: e.target.value })} onChange={(e) => setFormData({ ...formData, website: e.target.value })}
@@ -322,20 +325,20 @@ export function PlatformManager() {
/> />
</div> </div>
<div className="space-y-1.5"> <div className="space-y-1.5">
<Label>描述</Label> <Label>{t('common.description')}</Label>
<Input <Input
value={formData.description} value={formData.description}
onChange={(e) => setFormData({ ...formData, description: e.target.value })} onChange={(e) => setFormData({ ...formData, description: e.target.value })}
placeholder="平台描述..." placeholder=t('cloud.platformmanager.sc44dd4')
className="dg-input" className="dg-input"
/> />
</div> </div>
</div> </div>
<DialogFooter> <DialogFooter>
<Button variant="ghost" onClick={() => setDialogOpen(false)}>取消</Button> <Button variant="ghost" onClick={() => setDialogOpen(false)}>{t('common.cancel')}</Button>
<Button onClick={handleSubmit} disabled={submitting || !formData.name.trim() || !formData.code.trim()}> <Button onClick={handleSubmit} disabled={submitting || !formData.name.trim() || !formData.code.trim()}>
{submitting && <Loader2 className="h-4 w-4 mr-1 animate-spin" />} {submitting && <Loader2 className="h-4 w-4 mr-1 animate-spin" />}
{editingItem ? '保存' : '创建'} {editingItem ? t('common.save') : t('common.create')}
</Button> </Button>
</DialogFooter> </DialogFooter>
</DialogContent> </DialogContent>
@@ -345,13 +348,13 @@ export function PlatformManager() {
<Dialog open={deleteId !== null} onOpenChange={(v) => !v && setDeleteId(null)}> <Dialog open={deleteId !== null} onOpenChange={(v) => !v && setDeleteId(null)}>
<DialogContent className="max-w-sm"> <DialogContent className="max-w-sm">
<DialogHeader> <DialogHeader>
<DialogTitle>确认删除</DialogTitle> <DialogTitle>{t('k8s.actionModal.confirmDelete')}</DialogTitle>
<DialogDescription className="sr-only">描述</DialogDescription> <DialogDescription className="sr-only">{t('common.description')}</DialogDescription>
</DialogHeader> </DialogHeader>
<p className="text-sm dg-text-secondary">确定删除此云平台?此操作不可撤销。</p> <p className="text-sm dg-text-secondary">{t('cloud.platformmanager.s452abb')}</p>
<DialogFooter> <DialogFooter>
<Button variant="ghost" onClick={() => setDeleteId(null)}>取消</Button> <Button variant="ghost" onClick={() => setDeleteId(null)}>{t('common.cancel')}</Button>
<Button variant="destructive" onClick={confirmDelete}>删除</Button> <Button variant="destructive" onClick={confirmDelete}>{t('common.delete')}</Button>
</DialogFooter> </DialogFooter>
</DialogContent> </DialogContent>
</Dialog> </Dialog>
@@ -14,6 +14,7 @@ import { Dialog, DialogContent, DialogDescription, DialogHeader, DialogTitle } f
import { toast } from 'sonner'; import { toast } from 'sonner';
import { useConfirm } from '@/components/ui/confirm-dialog'; import { useConfirm } from '@/components/ui/confirm-dialog';
import { buildNodeApi, serverApi, type BuildNode } from '@/api'; import { buildNodeApi, serverApi, type BuildNode } from '@/api';
import { useTranslation } from 'react-i18next';
interface ServerItem { interface ServerItem {
id: number; id: number;
@@ -23,6 +24,7 @@ interface ServerItem {
// 构建节点管理(Jenkins Agent 风格 SSH 节点) // Logan.Li // 构建节点管理(Jenkins Agent 风格 SSH 节点) // Logan.Li
export default function BuildNodesManager({ embedded = false }: { embedded?: boolean }) { export default function BuildNodesManager({ embedded = false }: { embedded?: boolean }) {
const { t } = useTranslation();
const confirm = useConfirm(); const confirm = useConfirm();
const [nodes, setNodes] = useState<BuildNode[]>([]); const [nodes, setNodes] = useState<BuildNode[]>([]);
const [master, setMaster] = useState({ name: 'Master', max_executors: 2, running_count: 0 }); const [master, setMaster] = useState({ name: 'Master', max_executors: 2, running_count: 0 });
@@ -58,7 +60,7 @@ export default function BuildNodesManager({ embedded = false }: { embedded?: boo
const srvList = (srvRes as { list?: ServerItem[] })?.list || []; const srvList = (srvRes as { list?: ServerItem[] })?.list || [];
setServers(srvList); setServers(srvList);
} catch { } catch {
toast.error('加载构建节点失败'); toast.error(t('deploy.buildnodesmanager.sb9faa2'));
} finally { } finally {
setLoading(false); setLoading(false);
} }
@@ -90,7 +92,7 @@ export default function BuildNodesManager({ embedded = false }: { embedded?: boo
const handleSubmit = async () => { const handleSubmit = async () => {
if (!name.trim() || !serverId) { if (!name.trim() || !serverId) {
toast.error('请填写名称并选择服务器'); toast.error(t('deploy.buildnodesmanager.sda51a7'));
return; return;
} }
setSubmitting(true); setSubmitting(true);
@@ -105,29 +107,29 @@ export default function BuildNodesManager({ embedded = false }: { embedded?: boo
}; };
if (editNode) { if (editNode) {
await buildNodeApi.update(editNode.id, payload); await buildNodeApi.update(editNode.id, payload);
toast.success('已更新'); toast.success(t('deploy.toast.updated'));
} else { } else {
await buildNodeApi.create(payload); await buildNodeApi.create(payload);
toast.success('已创建'); toast.success(t('deploy.toast.created'));
} }
setDialogOpen(false); setDialogOpen(false);
load(); load();
} catch { } catch {
toast.error('操作失败'); toast.error(t('common.operationFailed'));
} finally { } finally {
setSubmitting(false); setSubmitting(false);
} }
}; };
const handleDelete = async (node: BuildNode) => { const handleDelete = async (node: BuildNode) => {
const ok = await confirm({ title: '删除节点', description: `确定删除构建节点「${node.name}」?` }); const ok = await confirm({ title: t('k8s.topology.deleteNode'), description: t('deploy.buildnodesmanager.s359e74', { node.name: node.name }) });
if (!ok) return; if (!ok) return;
try { try {
await buildNodeApi.delete(node.id); await buildNodeApi.delete(node.id);
toast.success('已删除'); toast.success(t('alert.deleted'));
load(); load();
} catch { } catch {
toast.error('删除失败,请确认无流水线绑定'); toast.error(t('deploy.buildnodesmanager.s577b18'));
} }
}; };
@@ -136,12 +138,12 @@ export default function BuildNodesManager({ embedded = false }: { embedded?: boo
try { try {
const res = await buildNodeApi.test(node.id) as { success?: boolean; message?: string }; const res = await buildNodeApi.test(node.id) as { success?: boolean; message?: string };
if (res?.success) { if (res?.success) {
toast.success(`连通成功: ${res.message || ''}`); toast.success(t('deploy.buildnodesmanager.s1c5ca7', { res.message || '': res.message || '' }));
} else { } else {
toast.error(res?.message || '连接失败'); toast.error(res?.message || t('aiops.llmTestFailed'));
} }
} catch { } catch {
toast.error('测试失败'); toast.error(t('deploy.buildnodesmanager.s9710d9'));
} finally { } finally {
setTestingId(null); setTestingId(null);
} }
@@ -152,14 +154,14 @@ export default function BuildNodesManager({ embedded = false }: { embedded?: boo
await buildNodeApi.update(node.id, { enabled: !node.enabled }); await buildNodeApi.update(node.id, { enabled: !node.enabled });
load(); load();
} catch { } catch {
toast.error('更新失败'); toast.error(t('alert.updateFailed'));
} }
}; };
const handleSaveMaster = async () => { const handleSaveMaster = async () => {
const n = Number(masterMax); const n = Number(masterMax);
if (!n || n < 1) { if (!n || n < 1) {
toast.error('并发数至少为 1'); toast.error(t('deploy.buildnodesmanager.s5f25f4'));
return; return;
} }
setSavingMaster(true); setSavingMaster(true);
@@ -171,9 +173,9 @@ export default function BuildNodesManager({ embedded = false }: { embedded?: boo
max_executors: m?.max_executors ?? n, max_executors: m?.max_executors ?? n,
running_count: m?.running_count ?? prev.running_count, running_count: m?.running_count ?? prev.running_count,
})); }));
toast.success('Master 并发已更新'); toast.success(t('deploy.buildnodesmanager.scb1ab6'));
} catch { } catch {
toast.error('更新失败'); toast.error(t('alert.updateFailed'));
} finally { } finally {
setSavingMaster(false); setSavingMaster(false);
} }
@@ -184,7 +186,7 @@ export default function BuildNodesManager({ embedded = false }: { embedded?: boo
<ContentPanel <ContentPanel
toolbar={( toolbar={(
<div className="flex items-center justify-between w-full"> <div className="flex items-center justify-between w-full">
<span className="text-sm font-medium text-[var(--dg-text-primary)]">构建节点</span> <span className="text-sm font-medium text-[var(--dg-text-primary)]">{t('pipeline.buildNode')}</span>
<div className="flex gap-2"> <div className="flex gap-2">
<Button variant="ghost" size="sm" onClick={load} disabled={loading}> <Button variant="ghost" size="sm" onClick={load} disabled={loading}>
<RefreshCw className={`h-3.5 w-3.5 mr-1${loading ? ' animate-spin' : ''}`} />刷新 <RefreshCw className={`h-3.5 w-3.5 mr-1${loading ? ' animate-spin' : ''}`} />刷新
@@ -200,14 +202,14 @@ export default function BuildNodesManager({ embedded = false }: { embedded?: boo
<div className="flex flex-wrap items-center justify-between gap-3"> <div className="flex flex-wrap items-center justify-between gap-3">
<div className="flex items-center gap-2"> <div className="flex items-center gap-2">
<Cpu className="h-4 w-4 text-[var(--dg-text-muted)]" /> <Cpu className="h-4 w-4 text-[var(--dg-text-muted)]" />
<span className="text-sm font-medium text-[var(--dg-text-primary)]">Master(内置)</span> <span className="text-sm font-medium text-[var(--dg-text-primary)]">{t('deploy.buildnodesmanager.sae7536')}</span>
<Badge variant="outline" className="text-[10px]">默认调度</Badge> <Badge variant="outline" className="text-[10px]">{t('deploy.buildnodesmanager.sa419fe')}</Badge>
<span className="text-xs text-[var(--dg-text-muted)]"> <span className="text-xs text-[var(--dg-text-muted)]">
占用 {master.running_count}/{master.max_executors} 占用 {master.running_count}/{master.max_executors}
</span> </span>
</div> </div>
<div className="flex items-center gap-2"> <div className="flex items-center gap-2">
<Label className="text-xs text-[var(--dg-text-muted)] shrink-0">最大并发</Label> <Label className="text-xs text-[var(--dg-text-muted)] shrink-0">{t('deploy.buildnodesmanager.s8e408e')}</Label>
<Input <Input
type="number" type="number"
min={1} min={1}
@@ -217,7 +219,7 @@ export default function BuildNodesManager({ embedded = false }: { embedded?: boo
className="h-7 w-16 text-xs dg-input" className="h-7 w-16 text-xs dg-input"
/> />
<Button size="sm" className="h-7 text-xs" onClick={handleSaveMaster} disabled={savingMaster}> <Button size="sm" className="h-7 text-xs" onClick={handleSaveMaster} disabled={savingMaster}>
{savingMaster ? '保存中' : '保存'} {savingMaster ? t('deploy.buildnodesmanager.s7cbf2d') : t('common.save')}
</Button> </Button>
</div> </div>
</div> </div>
@@ -228,9 +230,9 @@ export default function BuildNodesManager({ embedded = false }: { embedded?: boo
{nodes.length === 0 ? ( {nodes.length === 0 ? (
<PageEmpty <PageEmpty
title="暂无远程构建节点" title=t('deploy.buildnodesmanager.s2795bd')
description="关联服务器资产添加 SSH 节点,将重型构建任务调度到高性能机器" description=t('deploy.buildnodesmanager.s90fb5e')
action={<Button size="sm" onClick={openCreate}><Plus className="h-3.5 w-3.5 mr-1" />添加节点</Button>} action={<Button size="sm" onClick={openCreate}><Plus className="h-3.5 w-3.5 mr-1" />{t('k8s.topology.addNode')}</Button>}
/> />
) : ( ) : (
<div className="space-y-2"> <div className="space-y-2">
@@ -243,7 +245,7 @@ export default function BuildNodesManager({ embedded = false }: { embedded?: boo
<div className="flex items-center gap-2 flex-wrap"> <div className="flex items-center gap-2 flex-wrap">
<span className="font-medium text-sm text-[var(--dg-text-primary)]">{node.name}</span> <span className="font-medium text-sm text-[var(--dg-text-primary)]">{node.name}</span>
<Badge variant={node.enabled ? 'default' : 'secondary'} className="text-[10px]"> <Badge variant={node.enabled ? 'default' : 'secondary'} className="text-[10px]">
{node.enabled ? '启用' : '禁用'} {node.enabled ? t('common.enable') : t('common.disable')}
</Badge> </Badge>
<span className="text-[10px] text-[var(--dg-text-muted)] font-mono"> <span className="text-[10px] text-[var(--dg-text-muted)] font-mono">
{node.hostname || node.ip || `server#${node.server_id}`} {node.hostname || node.ip || `server#${node.server_id}`}
@@ -257,10 +259,10 @@ export default function BuildNodesManager({ embedded = false }: { embedded?: boo
</div> </div>
<div className="flex items-center gap-1 shrink-0"> <div className="flex items-center gap-1 shrink-0">
<Button variant="ghost" size="sm" className="h-7 text-xs" disabled={testingId === node.id} onClick={() => handleTest(node)}> <Button variant="ghost" size="sm" className="h-7 text-xs" disabled={testingId === node.id} onClick={() => handleTest(node)}>
{testingId === node.id ? '测试中' : '测试'} {testingId === node.id ? t('deploy.buildnodesmanager.sf85549') : t('common.test')}
</Button> </Button>
<Button variant="ghost" size="sm" className="h-7 text-xs" onClick={() => handleToggle(node)}> <Button variant="ghost" size="sm" className="h-7 text-xs" onClick={() => handleToggle(node)}>
{node.enabled ? '禁用' : '启用'} {node.enabled ? t('common.disable') : t('common.enable')}
</Button> </Button>
<Button variant="ghost" size="icon" className="h-7 w-7" onClick={() => openEdit(node)}> <Button variant="ghost" size="icon" className="h-7 w-7" onClick={() => openEdit(node)}>
<Pencil className="h-3.5 w-3.5" /> <Pencil className="h-3.5 w-3.5" />
@@ -281,22 +283,22 @@ export default function BuildNodesManager({ embedded = false }: { embedded?: boo
<Dialog open={dialogOpen} onOpenChange={setDialogOpen}> <Dialog open={dialogOpen} onOpenChange={setDialogOpen}>
<DialogContent className="max-w-md bg-[var(--dg-bg-primary)] border-[var(--dg-border)]"> <DialogContent className="max-w-md bg-[var(--dg-bg-primary)] border-[var(--dg-border)]">
<DialogHeader> <DialogHeader>
<DialogTitle>{editNode ? '编辑节点' : '添加节点'}</DialogTitle> <DialogTitle>{editNode ? t('k8s.topology.editNode') : t('k8s.topology.addNode')}</DialogTitle>
<DialogDescription className="text-[var(--dg-text-muted)]"> <DialogDescription className="text-[var(--dg-text-muted)]">
基于服务器 SSH 凭据注册构建 Agent,流水线可绑定或自动调度 基于服务器 SSH 凭据注册构建 Agent,流水线可绑定或自动调度
</DialogDescription> </DialogDescription>
</DialogHeader> </DialogHeader>
<div className="space-y-3"> <div className="space-y-3">
<div className="space-y-1"> <div className="space-y-1">
<Label className="text-xs">节点名称</Label> <Label className="text-xs">{t('k8s.topology.nodeName')}</Label>
<Input value={name} onChange={(e) => setName(e.target.value)} className="h-8 text-xs dg-input" placeholder="build-node-01" /> <Input value={name} onChange={(e) => setName(e.target.value)} className="h-8 text-xs dg-input" placeholder="build-node-01" />
</div> </div>
<div className="space-y-1"> <div className="space-y-1">
<Label className="text-xs">关联服务器</Label> <Label className="text-xs">{t('deploy.buildnodesmanager.sdfdaf1')}</Label>
<Select value={serverId || '__none'} onValueChange={(v) => setServerId(v === '__none' ? '' : v)}> <Select value={serverId || '__none'} onValueChange={(v) => setServerId(v === '__none' ? '' : v)}>
<SelectTrigger className="h-8 text-xs dg-input"><SelectValue placeholder="选择服务器" /></SelectTrigger> <SelectTrigger className="h-8 text-xs dg-input"><SelectValue placeholder=t('deploy.buildnodesmanager.s030235') /></SelectTrigger>
<SelectContent> <SelectContent>
<SelectItem value="__none">请选择</SelectItem> <SelectItem value="__none">{t('common.selectPlaceholder')}</SelectItem>
{servers.map((s) => ( {servers.map((s) => (
<SelectItem key={s.id} value={String(s.id)}> <SelectItem key={s.id} value={String(s.id)}>
{s.hostname} ({s.ip}) {s.hostname} ({s.ip})
@@ -307,25 +309,25 @@ export default function BuildNodesManager({ embedded = false }: { embedded?: boo
</div> </div>
<div className="grid grid-cols-2 gap-2"> <div className="grid grid-cols-2 gap-2">
<div className="space-y-1"> <div className="space-y-1">
<Label className="text-xs">最大并发</Label> <Label className="text-xs">{t('deploy.buildnodesmanager.s8e408e')}</Label>
<Input value={maxExecutors} onChange={(e) => setMaxExecutors(e.target.value)} type="number" min={1} className="h-8 text-xs dg-input" /> <Input value={maxExecutors} onChange={(e) => setMaxExecutors(e.target.value)} type="number" min={1} className="h-8 text-xs dg-input" />
</div> </div>
<div className="space-y-1"> <div className="space-y-1">
<Label className="text-xs">工作区路径</Label> <Label className="text-xs">{t('deploy.buildnodesmanager.sbcfcd0')}</Label>
<Input value={workspacePath} onChange={(e) => setWorkspacePath(e.target.value)} className="h-8 text-xs font-mono dg-input" /> <Input value={workspacePath} onChange={(e) => setWorkspacePath(e.target.value)} className="h-8 text-xs font-mono dg-input" />
</div> </div>
</div> </div>
<div className="space-y-1"> <div className="space-y-1">
<Label className="text-xs">标签 <span className="text-[var(--dg-text-muted)]">(可选)</span></Label> <Label className="text-xs">{t('common.tag')} <span className="text-[var(--dg-text-muted)]">{t('deploy.buildnodesmanager.s6c9a78')}</span></Label>
<Input value={labels} onChange={(e) => setLabels(e.target.value)} className="h-8 text-xs dg-input" placeholder="linux,docker,high-mem" /> <Input value={labels} onChange={(e) => setLabels(e.target.value)} className="h-8 text-xs dg-input" placeholder="linux,docker,high-mem" />
</div> </div>
<div className="space-y-1"> <div className="space-y-1">
<Label className="text-xs">描述</Label> <Label className="text-xs">{t('common.description')}</Label>
<Input value={description} onChange={(e) => setDescription(e.target.value)} className="h-8 text-xs dg-input" /> <Input value={description} onChange={(e) => setDescription(e.target.value)} className="h-8 text-xs dg-input" />
</div> </div>
<div className="flex justify-end gap-2 pt-2"> <div className="flex justify-end gap-2 pt-2">
<Button variant="outline" onClick={() => setDialogOpen(false)}>取消</Button> <Button variant="outline" onClick={() => setDialogOpen(false)}>{t('common.cancel')}</Button>
<Button onClick={handleSubmit} disabled={submitting}>{submitting ? '保存中' : '保存'}</Button> <Button onClick={handleSubmit} disabled={submitting}>{submitting ? i18n.t('deploy.buildnodesmanager.s7cbf2d') : i18n.t('common.save')}</Button>
</div> </div>
</div> </div>
</DialogContent> </DialogContent>
@@ -342,7 +344,7 @@ export default function BuildNodesManager({ embedded = false }: { embedded?: boo
} }
return ( return (
<PageShell title="构建节点" subtitle="Master 与远程 SSH 构建节点"> <PageShell title=i18n.t('pipeline.buildNode') subtitle=i18n.t('deploy.buildnodesmanager.sb2b825')>
{panel} {panel}
{dialog} {dialog}
</PageShell> </PageShell>
@@ -10,6 +10,7 @@ import { Plus, Key, Globe, Container } from 'lucide-react';
import { toast } from 'sonner'; import { toast } from 'sonner';
import { credentialApi, deployApi } from '@/api'; import { credentialApi, deployApi } from '@/api';
import type { JsonData } from '@/types/common'; import type { JsonData } from '@/types/common';
import { useTranslation } from 'react-i18next';
interface Repo { interface Repo {
id: number; name: string; url: string; credential_id: number | null; id: number; name: string; url: string; credential_id: number | null;
@@ -32,6 +33,7 @@ interface Props {
} }
export default function CredentialFormDialog({ open, onOpenChange, type, editId, repos, registries, onSave }: Props) { export default function CredentialFormDialog({ open, onOpenChange, type, editId, repos, registries, onSave }: Props) {
const { t } = useTranslation();
const isRepo = type === 'repo'; const isRepo = type === 'repo';
const [name, setName] = useState(''); const [name, setName] = useState('');
const [desc, setDesc] = useState(''); const [desc, setDesc] = useState('');
@@ -69,7 +71,7 @@ export default function CredentialFormDialog({ open, onOpenChange, type, editId,
}, [editId, open, isRepo]); }, [editId, open, isRepo]);
const handleSave = async () => { const handleSave = async () => {
if (!name.trim() || !url.trim()) { toast.error('请填写名称和地址'); return; } if (!name.trim() || !url.trim()) { toast.error(t('deploy.form.nameAddrRequired')); return; }
setSaving(true); setSaving(true);
try { try {
const cid = credentialId ? Number(credentialId) : null; const cid = credentialId ? Number(credentialId) : null;
@@ -79,15 +81,15 @@ export default function CredentialFormDialog({ open, onOpenChange, type, editId,
if (editId) { if (editId) {
if (isRepo) await deployApi.updateRepo(editId, payload); if (isRepo) await deployApi.updateRepo(editId, payload);
else await deployApi.updateRegistry(editId, payload); else await deployApi.updateRegistry(editId, payload);
toast.success('已更新'); toast.success(t('deploy.toast.updated'));
} else { } else {
if (isRepo) await deployApi.createRepo(payload); if (isRepo) await deployApi.createRepo(payload);
else await deployApi.createRegistry(payload); else await deployApi.createRegistry(payload);
toast.success('已创建'); toast.success(t('deploy.toast.created'));
} }
onOpenChange(false); onOpenChange(false);
onSave(); onSave();
} catch { toast.error('保存失败'); } } catch { toast.error(t('common.saveFailed')); }
finally { setSaving(false); } finally { setSaving(false); }
}; };
@@ -99,26 +101,26 @@ export default function CredentialFormDialog({ open, onOpenChange, type, editId,
<DialogHeader> <DialogHeader>
<DialogTitle className="text-[var(--dg-text-primary)] flex items-center gap-2"> <DialogTitle className="text-[var(--dg-text-primary)] flex items-center gap-2">
<CredIcon className="h-5 w-5 text-[var(--dg-blue)]" /> <CredIcon className="h-5 w-5 text-[var(--dg-blue)]" />
{editId ? '编辑' : '新增'}{isRepo ? ' Git 仓库' : ' 镜像仓库'} {editId ? t('common.edit') : t('deploy.credentialformdialog.s66ab5e')}{isRepo ? t('deploy.credentialformdialog.s0b7cb4') : t('deploy.credentialformdialog.s7f34a8')}
</DialogTitle> </DialogTitle>
</DialogHeader> </DialogHeader>
<div className="space-y-4 py-2"> <div className="space-y-4 py-2">
<div className="space-y-1"><Label>名称 *</Label> <div className="space-y-1"><Label>{t('deploy.form.nameStar')}</Label>
<Input value={name} onChange={e => setName(e.target.value)} placeholder={isRepo ? '如:GitLab CE' : '如:Harbor'} className="bg-[var(--dg-bg-tertiary)] border-[var(--dg-border)] text-[var(--dg-text-primary)]" /></div> <Input value={name} onChange={e => setName(e.target.value)} placeholder={isRepo ? t('deploy.credentialformdialog.se9548a') : t('deploy.credentialformdialog.sa4d9ef')} className="bg-[var(--dg-bg-tertiary)] border-[var(--dg-border)] text-[var(--dg-text-primary)]" /></div>
<div className="space-y-1"><Label>{isRepo ? '仓库 URL *' : 'Registry URL *'}</Label> <div className="space-y-1"><Label>{isRepo ? t('deploy.form.repoUrlStar') : 'Registry URL *'}</Label>
<Input value={url} onChange={e => setUrl(e.target.value)} placeholder={isRepo ? 'http://10.10.10.72:9000/group/repo.git' : 'http://10.10.10.72'} className="font-mono text-sm bg-[var(--dg-bg-tertiary)] border-[var(--dg-border)] text-[var(--dg-text-primary)]" /></div> <Input value={url} onChange={e => setUrl(e.target.value)} placeholder={isRepo ? 'http://10.10.10.72:9000/group/repo.git' : 'http://10.10.10.72'} className="font-mono text-sm bg-[var(--dg-bg-tertiary)] border-[var(--dg-border)] text-[var(--dg-text-primary)]" /></div>
{!isRepo && <div className="space-y-1"><Label>默认命名空间</Label> {!isRepo && <div className="space-y-1"><Label>{t('deploy.form.defaultNamespace')}</Label>
<Input value={namespace} onChange={e => setNamespace(e.target.value)} placeholder="如:aiops" className="bg-[var(--dg-bg-tertiary)] border-[var(--dg-border)] text-[var(--dg-text-primary)]" /></div>} <Input value={namespace} onChange={e => setNamespace(e.target.value)} placeholder=t('deploy.credentialformdialog.s2a8bb1') className="bg-[var(--dg-bg-tertiary)] border-[var(--dg-border)] text-[var(--dg-text-primary)]" /></div>}
{/* 关联凭证 */} {/* 关联凭证 */}
<div className="space-y-1"> <div className="space-y-1">
<Label>关联凭证 <span className="text-xs text-[var(--dg-text-secondary)] opacity-70">(认证由凭据管理统一配置)</span></Label> <Label>{t('deploy.cred.linkedCred')} <span className="text-xs text-[var(--dg-text-secondary)] opacity-70">{t('deploy.credentialformdialog.s30220a')}</span></Label>
<Select value={String(credentialId)} onValueChange={v => setCredentialId(v === '__none' ? '' : v)}> <Select value={String(credentialId)} onValueChange={v => setCredentialId(v === '__none' ? '' : v)}>
<SelectTrigger className="bg-[var(--dg-bg-tertiary)] border-[var(--dg-border)] text-[var(--dg-text-primary)]"> <SelectTrigger className="bg-[var(--dg-bg-tertiary)] border-[var(--dg-border)] text-[var(--dg-text-primary)]">
<SelectValue placeholder={isRepo ? '选择凭据(API/密码等)' : '选择 Docker 密码凭据'} /> <SelectValue placeholder={isRepo ? t('deploy.cred.selectApiCred') : t('deploy.cred.selectDockerPwd')} />
</SelectTrigger> </SelectTrigger>
<SelectContent> <SelectContent>
<SelectItem value="__none">不关联凭证</SelectItem> <SelectItem value="__none">{t('deploy.cred.notLinkedCred')}</SelectItem>
{filteredCredentials.map(c => ( {filteredCredentials.map(c => (
<SelectItem key={c.id} value={String(c.id)}> <SelectItem key={c.id} value={String(c.id)}>
<span className="flex items-center gap-1.5"> <span className="flex items-center gap-1.5">
@@ -132,14 +134,14 @@ export default function CredentialFormDialog({ open, onOpenChange, type, editId,
{filteredCredentials.length === 0 && ( {filteredCredentials.length === 0 && (
<p className="text-xs dg-text-yellow flex items-center gap-1 mt-1"> <p className="text-xs dg-text-yellow flex items-center gap-1 mt-1">
<Plus className="h-3 w-3" /> <Plus className="h-3 w-3" />
暂无{isRepo ? '' : 'Docker 密码'}类型凭证,请在凭证配置页面新增 暂无{isRepo ? '' : t('pipeline.dockerPassword')}类型凭证,请在凭证配置页面新增
</p> </p>
)} )}
</div> </div>
</div> </div>
<DialogFooter> <DialogFooter>
<Button variant="outline" onClick={() => onOpenChange(false)}>取消</Button> <Button variant="outline" onClick={() => onOpenChange(false)}>{t('common.cancel')}</Button>
<Button onClick={handleSave} disabled={saving}>{saving ? '保存中...' : '保存'}</Button> <Button onClick={handleSave} disabled={saving}>{saving ? i18n.t('k8s.topology.saving') : i18n.t('common.save')}</Button>
</DialogFooter> </DialogFooter>
</DialogContent> </DialogContent>
</Dialog> </Dialog>
@@ -18,6 +18,7 @@ import { deployApi } from '@/api';
import CredentialFormDialog from './CredentialFormDialog'; import CredentialFormDialog from './CredentialFormDialog';
import ToolConfigTab from './ToolConfigTab'; import ToolConfigTab from './ToolConfigTab';
import type { JsonData } from '@/types/common'; import type { JsonData } from '@/types/common';
import { useTranslation } from 'react-i18next';
interface Repo { interface Repo {
id: number; name: string; description: string; url: string; id: number; name: string; description: string; url: string;
@@ -35,6 +36,7 @@ interface Environment {
} }
function EnvFormDialog({ open, onClose, onSaved, editData }: { open: boolean; onClose: () => void; onSaved: () => void; editData: Environment | null }) { function EnvFormDialog({ open, onClose, onSaved, editData }: { open: boolean; onClose: () => void; onSaved: () => void; editData: Environment | null }) {
const { t } = useTranslation();
const [name, setName] = useState(''); const [name, setName] = useState('');
const [displayName, setDisplayName] = useState(''); const [displayName, setDisplayName] = useState('');
const [envType, setEnvType] = useState('development'); const [envType, setEnvType] = useState('development');
@@ -57,43 +59,43 @@ function EnvFormDialog({ open, onClose, onSaved, editData }: { open: boolean; on
}, [editData, open]); }, [editData, open]);
const handleSubmit = async () => { const handleSubmit = async () => {
if (!name.trim() || !displayName.trim()) { toast.error('请填写名称'); return; } if (!name.trim() || !displayName.trim()) { toast.error(t('deploy.form.nameRequired')); return; }
setSubmitting(true); setSubmitting(true);
try { try {
if (editData) await deployApi.updateEnvironment(editData.id, { name, display_name: displayName, type: envType, color, sort_order: sortOrder, description }); if (editData) await deployApi.updateEnvironment(editData.id, { name, display_name: displayName, type: envType, color, sort_order: sortOrder, description });
else await deployApi.createEnvironment({ name, display_name: displayName, type: envType, color, sort_order: sortOrder, description }); else await deployApi.createEnvironment({ name, display_name: displayName, type: envType, color, sort_order: sortOrder, description });
toast.success(editData ? '已更新' : '已创建'); toast.success(editData ? t('deploy.toast.updated') : t('deploy.toast.created'));
onSaved(); onSaved();
onClose(); onClose();
} catch { toast.error('操作失败'); } } catch { toast.error(t('common.operationFailed')); }
finally { setSubmitting(false); } finally { setSubmitting(false); }
}; };
return ( return (
<Dialog open={open} onOpenChange={onClose}> <Dialog open={open} onOpenChange={onClose}>
<DialogContent> <DialogContent>
<DialogHeader><DialogTitle>{editData ? '编辑环境' : '新增环境'}</DialogTitle></DialogHeader> <DialogHeader><DialogTitle>{editData ? t('pipeline.editEnv') : t('pipeline.addEnv')}</DialogTitle></DialogHeader>
<div className="space-y-3"> <div className="space-y-3">
<div className="space-y-1"><Label>环境标识</Label><Input value={name} onChange={e => setName(e.target.value)} placeholder="production" /></div> <div className="space-y-1"><Label>{t('pipeline.envLabel')}</Label><Input value={name} onChange={e => setName(e.target.value)} placeholder="production" /></div>
<div className="space-y-1"><Label>显示名称</Label><Input value={displayName} onChange={e => setDisplayName(e.target.value)} placeholder="生产环境" /></div> <div className="space-y-1"><Label>{t('system.userDisplayName')}</Label><Input value={displayName} onChange={e => setDisplayName(e.target.value)} placeholder=t('pipeline.prodEnv') /></div>
<div className="space-y-1"><Label>环境类型</Label> <div className="space-y-1"><Label>{t('pipeline.envType')}</Label>
<Select value={envType} onValueChange={setEnvType}> <Select value={envType} onValueChange={setEnvType}>
<SelectTrigger><SelectValue /></SelectTrigger> <SelectTrigger><SelectValue /></SelectTrigger>
<SelectContent> <SelectContent>
<SelectItem value="production">生产环境</SelectItem> <SelectItem value="production">{t('pipeline.prodEnv')}</SelectItem>
<SelectItem value="staging">预发布</SelectItem> <SelectItem value="staging">{t('pipeline.staging')}</SelectItem>
<SelectItem value="testing">测试环境</SelectItem> <SelectItem value="testing">{t('pipeline.testEnv')}</SelectItem>
<SelectItem value="development">开发环境</SelectItem> <SelectItem value="development">{t('pipeline.devEnv')}</SelectItem>
</SelectContent> </SelectContent>
</Select> </Select>
</div> </div>
<div className="space-y-1"><Label>标志颜色</Label><Input value={color} onChange={e => setColor(e.target.value)} type="color" className="w-16 h-9 p-1" /></div> <div className="space-y-1"><Label>{t('deploy.deploycredentials.sc06ac4')}</Label><Input value={color} onChange={e => setColor(e.target.value)} type="color" className="w-16 h-9 p-1" /></div>
<div className="space-y-1"><Label>排序序号</Label><Input value={sortOrder} onChange={e => setSortOrder(Number(e.target.value))} type="number" /></div> <div className="space-y-1"><Label>{t('deploy.deploycredentials.s65dd48')}</Label><Input value={sortOrder} onChange={e => setSortOrder(Number(e.target.value))} type="number" /></div>
<div className="space-y-1"><Label>描述</Label><Input value={description} onChange={e => setDescription(e.target.value)} placeholder="可选" /></div> <div className="space-y-1"><Label>{t('common.description')}</Label><Input value={description} onChange={e => setDescription(e.target.value)} placeholder=t('common.optional') /></div>
</div> </div>
<div className="flex justify-end gap-2 mt-4"> <div className="flex justify-end gap-2 mt-4">
<Button variant="outline" onClick={onClose}>取消</Button> <Button variant="outline" onClick={onClose}>{t('common.cancel')}</Button>
<Button onClick={handleSubmit} disabled={submitting}>{submitting ? '...' : editData ? '保存' : '创建'}</Button> <Button onClick={handleSubmit} disabled={submitting}>{submitting ? '...' : editData ? t('common.save') : t('common.create')}</Button>
</div> </div>
</DialogContent> </DialogContent>
</Dialog> </Dialog>
@@ -103,6 +105,7 @@ function EnvFormDialog({ open, onClose, onSaved, editData }: { open: boolean; on
const CONFIG_TABS = ['repos', 'registries', 'environments', 'tools', 'build-nodes'] as const; const CONFIG_TABS = ['repos', 'registries', 'environments', 'tools', 'build-nodes'] as const;
export default function DeployCredentials() { export default function DeployCredentials() {
const { t } = useTranslation();
const _confirm = useConfirm(); const _confirm = useConfirm();
const [searchParams] = useSearchParams(); const [searchParams] = useSearchParams();
const tabFromUrl = searchParams.get('tab'); const tabFromUrl = searchParams.get('tab');
@@ -126,39 +129,39 @@ export default function DeployCredentials() {
setRepos((rR as JsonData)?.list || []); setRepos((rR as JsonData)?.list || []);
setRegistries((rReg as JsonData)?.list || []); setRegistries((rReg as JsonData)?.list || []);
setEnvironments((rEnv as JsonData)?.list || []); setEnvironments((rEnv as JsonData)?.list || []);
} catch { toast.error('获取数据失败'); } } catch { toast.error(t('deploy.toast.getDataFailed')); }
finally { setLoading(false); } finally { setLoading(false); }
}; };
useEffect(() => { fetchAll(); }, []); useEffect(() => { fetchAll(); }, []);
const handleDelete = async (type: 'repo' | 'registry' | 'env', item: JsonData) => { const handleDelete = async (type: 'repo' | 'registry' | 'env', item: JsonData) => {
const ok = await _confirm({ title: '删除', description: `确定删除「${item.name || item.display_name}」?`, confirmText: '删除', variant: 'destructive' }); const ok = await _confirm({ title: t('common.delete'), description: t('deploy.deploycredentials.s999d97', { item.name || item.display_name: item.name || item.display_name }), confirmText: t('common.delete'), variant: 'destructive' });
if (!ok) return; if (!ok) return;
try { try {
if (type === 'repo') await deployApi.deleteRepo(item.id); if (type === 'repo') await deployApi.deleteRepo(item.id);
else if (type === 'registry') await deployApi.deleteRegistry(item.id); else if (type === 'registry') await deployApi.deleteRegistry(item.id);
else await deployApi.deleteEnvironment(item.id); else await deployApi.deleteEnvironment(item.id);
toast.success('已删除'); toast.success(t('alert.deleted'));
fetchAll(); fetchAll();
} catch { toast.error('删除失败'); } } catch { toast.error(t('common.deleteFailed')); }
}; };
const envTypeLabel: Record<string, string> = { production: '生产', staging: '预发布', testing: '测试', development: '开发' }; const envTypeLabel: Record<string, string> = { production: t('pipeline.production'), staging: t('pipeline.staging'), testing: t('common.test'), development: t('pipeline.development') };
const pageTabs = [ const pageTabs = [
{ id: 'repos', label: 'Git 仓库', badge: repos.length || undefined }, { id: 'repos', label: t('deploy.deploycredentials.sd71d03'), badge: repos.length || undefined },
{ id: 'registries', label: '镜像仓库', badge: registries.length || undefined }, { id: 'registries', label: t('pipeline.registry'), badge: registries.length || undefined },
{ id: 'environments', label: '环境管理', badge: environments.length || undefined }, { id: 'environments', label: t('pipeline.envManage'), badge: environments.length || undefined },
{ id: 'build-nodes', label: '构建节点' }, { id: 'build-nodes', label: t('pipeline.buildNode') },
{ id: 'tools', label: '工具配置' }, { id: 'tools', label: t('deploy.tool.title') },
]; ];
return ( return (
<PageShell <PageShell
variant="list" variant="list"
title="发布配置" title=t('menu.deployConfig')
subtitle="Git 仓库、镜像仓库、环境与工具" subtitle=t('deploy.deploycredentials.s15a730')
icon={<Settings2 className="h-5 w-5" />} icon={<Settings2 className="h-5 w-5" />}
loading={loading} loading={loading}
tabs={pageTabs} tabs={pageTabs}
@@ -181,18 +184,18 @@ export default function DeployCredentials() {
> >
{activeTab === 'repos' && ( {activeTab === 'repos' && (
repos.length === 0 ? ( repos.length === 0 ? (
<PageEmpty icon={<GitBranch className="h-10 w-10" />} title="暂无 Git 仓库认证配置" /> <PageEmpty icon={<GitBranch className="h-10 w-10" />} title=t('deploy.deploycredentials.sb19733') />
) : ( ) : (
<ContentPanel noPadding> <ContentPanel noPadding>
<div className="overflow-hidden"> <div className="overflow-hidden">
<table className="w-full text-sm"> <table className="w-full text-sm">
<thead className="bg-[var(--dg-bg-tertiary)] border-b border-[var(--dg-border)]"> <thead className="bg-[var(--dg-bg-tertiary)] border-b border-[var(--dg-border)]">
<tr> <tr>
<th className="px-3 py-2 text-left font-medium text-[var(--dg-text-secondary)]">名称</th> <th className="px-3 py-2 text-left font-medium text-[var(--dg-text-secondary)]">{t('common.name')}</th>
<th className="px-3 py-2 text-left font-medium text-[var(--dg-text-secondary)] hidden md:table-cell">仓库 URL</th> <th className="px-3 py-2 text-left font-medium text-[var(--dg-text-secondary)] hidden md:table-cell">{t('deploy.table.repoUrl')}</th>
<th className="px-3 py-2 text-left font-medium text-[var(--dg-text-secondary)]">认证方式</th> <th className="px-3 py-2 text-left font-medium text-[var(--dg-text-secondary)]">{t('deploy.cred.authMethod')}</th>
<th className="px-3 py-2 text-left font-medium text-[var(--dg-text-secondary)]">状态</th> <th className="px-3 py-2 text-left font-medium text-[var(--dg-text-secondary)]">{t('common.status')}</th>
<th className="px-3 py-2 text-right font-medium text-[var(--dg-text-secondary)]">操作</th> <th className="px-3 py-2 text-right font-medium text-[var(--dg-text-secondary)]">{t('common.actions')}</th>
</tr> </tr>
</thead> </thead>
<tbody> <tbody>
@@ -202,7 +205,7 @@ export default function DeployCredentials() {
<td className="px-3 py-2 text-[var(--dg-text-secondary)] hidden md:table-cell font-mono text-xs max-w-[300px] truncate">{r.url}</td> <td className="px-3 py-2 text-[var(--dg-text-secondary)] hidden md:table-cell font-mono text-xs max-w-[300px] truncate">{r.url}</td>
<td className="px-3 py-2"><Badge variant="outline" className="text-xs">{r.auth_type}</Badge></td> <td className="px-3 py-2"><Badge variant="outline" className="text-xs">{r.auth_type}</Badge></td>
<td className="px-3 py-2"> <td className="px-3 py-2">
<Badge className={r.enabled ? 'bg-emerald-500/20 dg-text-green border-emerald-500/30' : 'bg-[var(--dg-bg-active)]/20 dg-text-secondary border-[var(--dg-border)]'}>{r.enabled ? '启用' : '禁用'}</Badge> <Badge className={r.enabled ? 'bg-emerald-500/20 dg-text-green border-emerald-500/30' : 'bg-[var(--dg-bg-active)]/20 dg-text-secondary border-[var(--dg-border)]'}>{r.enabled ? t('common.enable') : t('common.disable')}</Badge>
</td> </td>
<td className="px-3 py-2 text-right"> <td className="px-3 py-2 text-right">
<div className="flex justify-end gap-1"> <div className="flex justify-end gap-1">
@@ -221,19 +224,19 @@ export default function DeployCredentials() {
{activeTab === 'registries' && ( {activeTab === 'registries' && (
registries.length === 0 ? ( registries.length === 0 ? (
<PageEmpty icon={<Container className="h-10 w-10" />} title="暂无镜像仓库认证配置" /> <PageEmpty icon={<Container className="h-10 w-10" />} title=t('deploy.deploycredentials.sdf33f0') />
) : ( ) : (
<ContentPanel noPadding> <ContentPanel noPadding>
<div className="overflow-hidden"> <div className="overflow-hidden">
<table className="w-full text-sm"> <table className="w-full text-sm">
<thead className="bg-[var(--dg-bg-tertiary)] border-b border-[var(--dg-border)]"> <thead className="bg-[var(--dg-bg-tertiary)] border-b border-[var(--dg-border)]">
<tr> <tr>
<th className="px-3 py-2 text-left font-medium text-[var(--dg-text-secondary)]">名称</th> <th className="px-3 py-2 text-left font-medium text-[var(--dg-text-secondary)]">{t('common.name')}</th>
<th className="px-3 py-2 text-left font-medium text-[var(--dg-text-secondary)] hidden md:table-cell">Registry URL</th> <th className="px-3 py-2 text-left font-medium text-[var(--dg-text-secondary)] hidden md:table-cell">Registry URL</th>
<th className="px-3 py-2 text-left font-medium text-[var(--dg-text-secondary)] hidden sm:table-cell">命名空间</th> <th className="px-3 py-2 text-left font-medium text-[var(--dg-text-secondary)] hidden sm:table-cell">{t('k8s.column.namespace')}</th>
<th className="px-3 py-2 text-left font-medium text-[var(--dg-text-secondary)]">认证</th> <th className="px-3 py-2 text-left font-medium text-[var(--dg-text-secondary)]">{t('deploy.deploycredentials.sb7158a')}</th>
<th className="px-3 py-2 text-left font-medium text-[var(--dg-text-secondary)]">状态</th> <th className="px-3 py-2 text-left font-medium text-[var(--dg-text-secondary)]">{t('common.status')}</th>
<th className="px-3 py-2 text-right font-medium text-[var(--dg-text-secondary)]">操作</th> <th className="px-3 py-2 text-right font-medium text-[var(--dg-text-secondary)]">{t('common.actions')}</th>
</tr> </tr>
</thead> </thead>
<tbody> <tbody>
@@ -244,7 +247,7 @@ export default function DeployCredentials() {
<td className="px-3 py-2 text-[var(--dg-text-secondary)] hidden sm:table-cell">{r.namespace || '-'}</td> <td className="px-3 py-2 text-[var(--dg-text-secondary)] hidden sm:table-cell">{r.namespace || '-'}</td>
<td className="px-3 py-2"><Badge variant="outline" className="text-xs">{r.auth_type}</Badge></td> <td className="px-3 py-2"><Badge variant="outline" className="text-xs">{r.auth_type}</Badge></td>
<td className="px-3 py-2"> <td className="px-3 py-2">
<Badge className={r.enabled ? 'bg-emerald-500/20 dg-text-green border-emerald-500/30' : 'bg-[var(--dg-bg-active)]/20 dg-text-secondary border-[var(--dg-border)]'}>{r.enabled ? '启用' : '禁用'}</Badge> <Badge className={r.enabled ? 'bg-emerald-500/20 dg-text-green border-emerald-500/30' : 'bg-[var(--dg-bg-active)]/20 dg-text-secondary border-[var(--dg-border)]'}>{r.enabled ? t('common.enable') : t('common.disable')}</Badge>
</td> </td>
<td className="px-3 py-2 text-right"> <td className="px-3 py-2 text-right">
<div className="flex justify-end gap-1"> <div className="flex justify-end gap-1">
@@ -271,8 +274,8 @@ export default function DeployCredentials() {
{environments.length === 0 ? ( {environments.length === 0 ? (
<PageEmpty <PageEmpty
icon={<Globe className="h-10 w-10" />} icon={<Globe className="h-10 w-10" />}
title="暂无环境配置" title=t('pipeline.noEnv')
description='点击"新增环境"创建' description=t('deploy.deploycredentials.sac4fb6')
action={( action={(
<Button size="sm" onClick={() => { setEditEnv(null); setEnvDialogOpen(true); }}> <Button size="sm" onClick={() => { setEditEnv(null); setEnvDialogOpen(true); }}>
<Plus className="w-4 h-4 mr-1" />新增环境 <Plus className="w-4 h-4 mr-1" />新增环境
@@ -285,13 +288,13 @@ export default function DeployCredentials() {
<table className="w-full text-sm"> <table className="w-full text-sm">
<thead className="bg-[var(--dg-bg-tertiary)] border-b border-[var(--dg-border)]"> <thead className="bg-[var(--dg-bg-tertiary)] border-b border-[var(--dg-border)]">
<tr> <tr>
<th className="px-3 py-2 text-left font-medium text-[var(--dg-text-secondary)]">环境标识</th> <th className="px-3 py-2 text-left font-medium text-[var(--dg-text-secondary)]">{t('pipeline.envLabel')}</th>
<th className="px-3 py-2 text-left font-medium text-[var(--dg-text-secondary)]">显示名称</th> <th className="px-3 py-2 text-left font-medium text-[var(--dg-text-secondary)]">{t('system.userDisplayName')}</th>
<th className="px-3 py-2 text-left font-medium text-[var(--dg-text-secondary)]">类型</th> <th className="px-3 py-2 text-left font-medium text-[var(--dg-text-secondary)]">{t('common.type')}</th>
<th className="px-3 py-2 text-left font-medium text-[var(--dg-text-secondary)]">颜色</th> <th className="px-3 py-2 text-left font-medium text-[var(--dg-text-secondary)]">{t('common.color')}</th>
<th className="px-3 py-2 text-left font-medium text-[var(--dg-text-secondary)]">排序</th> <th className="px-3 py-2 text-left font-medium text-[var(--dg-text-secondary)]">{t('common.sort')}</th>
<th className="px-3 py-2 text-left font-medium text-[var(--dg-text-secondary)]">状态</th> <th className="px-3 py-2 text-left font-medium text-[var(--dg-text-secondary)]">{t('common.status')}</th>
<th className="px-3 py-2 text-right font-medium text-[var(--dg-text-secondary)]">操作</th> <th className="px-3 py-2 text-right font-medium text-[var(--dg-text-secondary)]">{t('common.actions')}</th>
</tr> </tr>
</thead> </thead>
<tbody> <tbody>
@@ -308,7 +311,7 @@ export default function DeployCredentials() {
<td className="px-3 py-2"><div className="w-6 h-6 rounded border" style={{ backgroundColor: env.color }} /></td> <td className="px-3 py-2"><div className="w-6 h-6 rounded border" style={{ backgroundColor: env.color }} /></td>
<td className="px-3 py-2 text-[var(--dg-text-secondary)]">{env.sort_order}</td> <td className="px-3 py-2 text-[var(--dg-text-secondary)]">{env.sort_order}</td>
<td className="px-3 py-2"> <td className="px-3 py-2">
<Badge className={env.enabled ? 'bg-emerald-500/20 dg-text-green border-emerald-500/30' : 'bg-[var(--dg-bg-active)]/20 dg-text-secondary border-[var(--dg-border)]'}>{env.enabled ? '启用' : '禁用'}</Badge> <Badge className={env.enabled ? 'bg-emerald-500/20 dg-text-green border-emerald-500/30' : 'bg-[var(--dg-bg-active)]/20 dg-text-secondary border-[var(--dg-border)]'}>{env.enabled ? t('common.enable') : t('common.disable')}</Badge>
</td> </td>
<td className="px-3 py-2 text-right"> <td className="px-3 py-2 text-right">
<div className="flex justify-end gap-1"> <div className="flex justify-end gap-1">
+45 -42
View File
@@ -17,6 +17,8 @@ import UserGroupsManager from './UserGroupsManager';
import { JobRoleCreateDialog } from './deploy-rbac/JobRoleCreateDialog'; import { JobRoleCreateDialog } from './deploy-rbac/JobRoleCreateDialog';
import { matchPipelines, pipelineDisplayLabel, type PipelineMatchItem } from './deploy-rbac/matchPipeline'; import { matchPipelines, pipelineDisplayLabel, type PipelineMatchItem } from './deploy-rbac/matchPipeline';
import type { JsonData } from '@/types/common'; import type { JsonData } from '@/types/common';
import { useTranslation } from 'react-i18next';
import i18n from '@/i18n';
interface ItemRole { interface ItemRole {
id: number; id: number;
@@ -37,15 +39,16 @@ interface AssignedUser {
} }
const ROLE_LABEL: Record<string, string> = { const ROLE_LABEL: Record<string, string> = {
owner: '拥有者', owner: i18n.t('common.owner'),
editor: '编辑者', editor: i18n.t('pipeline.editor'),
viewer: '查看者', viewer: i18n.t('pipeline.viewer'),
}; };
const RBAC_TABS = ['roles', 'users', 'preview', 'groups'] as const; const RBAC_TABS = ['roles', 'users', 'preview', 'groups'] as const;
// 发布 Job 权限 — 正则匹配 code / job_name,Jenkins Role Strategy 风格 // Logan.Li // 发布 Job 权限 — 正则匹配 code / job_name,Jenkins Role Strategy 风格 // Logan.Li
export default function DeployRBAC() { export default function DeployRBAC() {
const { t } = useTranslation();
const [searchParams] = useSearchParams(); const [searchParams] = useSearchParams();
const tabFromUrl = searchParams.get('tab'); const tabFromUrl = searchParams.get('tab');
const [roles, setRoles] = useState<ItemRole[]>([]); const [roles, setRoles] = useState<ItemRole[]>([]);
@@ -110,7 +113,7 @@ export default function DeployRBAC() {
const handleCreate = async () => { const handleCreate = async () => {
if (!newName.trim() || !newCode.trim() || !newPattern.trim()) { if (!newName.trim() || !newCode.trim() || !newPattern.trim()) {
toast.error('请填写名称、标识与正则'); return; toast.error(t('deploy.deployrbac.sf6e80b')); return;
} }
setSaving(true); setSaving(true);
try { try {
@@ -121,84 +124,84 @@ export default function DeployRBAC() {
role: newRole, role: newRole,
description: newDesc, description: newDesc,
}); });
toast.success('已创建'); toast.success(t('deploy.toast.created'));
setCreateOpen(false); setCreateOpen(false);
setNewName(''); setNewCode(''); setNewPattern(''); setNewRole('editor'); setNewDesc(''); setNewName(''); setNewCode(''); setNewPattern(''); setNewRole('editor'); setNewDesc('');
loadData(); loadData();
} catch (e: unknown) { } catch (e: unknown) {
toast.error((e as Error)?.message || '创建失败'); toast.error((e as Error)?.message || t('monitor.quickSetupFailed'));
} finally { setSaving(false); } } finally { setSaving(false); }
}; };
const handleUpdate = async (id: number) => { const handleUpdate = async (id: number) => {
if (!editPattern.trim()) { toast.error('正则不能为空'); return; } if (!editPattern.trim()) { toast.error(t('pipeline.regexEmpty')); return; }
setSaving(true); setSaving(true);
try { try {
await deployApi.updateItemRole(id, { pattern: editPattern, role: editRole }); await deployApi.updateItemRole(id, { pattern: editPattern, role: editRole });
toast.success('已更新'); toast.success(t('deploy.toast.updated'));
setEditing(null); setEditing(null);
loadData(); loadData();
} catch (e: unknown) { } catch (e: unknown) {
toast.error((e as Error)?.message || '更新失败'); toast.error((e as Error)?.message || t('alert.updateFailed'));
} finally { setSaving(false); } } finally { setSaving(false); }
}; };
const handleDelete = async (role: ItemRole) => { const handleDelete = async (role: ItemRole) => {
const ok = await _confirm({ const ok = await _confirm({
title: '删除权限', title: t('deploy.deployrbac.s5d79e4'),
description: `确定删除「${role.name}」?将影响 ${matchCount[role.id]?.length || 0} 个发布任务`, description: t('deploy.deployrbac.s2c1ef5', { role.name: role.name, matchCount[role.id]?.length || 0: matchCount[role.id]?.length || 0 }),
variant: 'destructive', variant: 'destructive',
}); });
if (!ok) return; if (!ok) return;
try { await deployApi.deleteItemRole(role.id); toast.success('已删除'); loadData(); } try { await deployApi.deleteItemRole(role.id); toast.success(t('alert.deleted')); loadData(); }
catch { toast.error('删除失败'); } catch { toast.error(t('common.deleteFailed')); }
}; };
const handleToggleStatus = async (role: ItemRole) => { const handleToggleStatus = async (role: ItemRole) => {
try { try {
await deployApi.updateItemRole(role.id, { status: role.status ? 0 : 1 }); await deployApi.updateItemRole(role.id, { status: role.status ? 0 : 1 });
toast.success(role.status ? '已禁用' : '已启用'); toast.success(role.status ? t('alert.disabled') : t('alert.enabled'));
loadData(); loadData();
} catch { toast.error('操作失败'); } } catch { toast.error(t('common.operationFailed')); }
}; };
const handleAssign = async () => { const handleAssign = async () => {
if (!selectedUserId || !assignRoleId) { toast.error('请选择用户和权限'); return; } if (!selectedUserId || !assignRoleId) { toast.error(t('deploy.deployrbac.s0fc539')); return; }
setAssignLoading(true); setAssignLoading(true);
try { try {
await deployApi.assignItemRole(Number(selectedUserId), { await deployApi.assignItemRole(Number(selectedUserId), {
user_id: Number(selectedUserId), user_id: Number(selectedUserId),
item_role_id: Number(assignRoleId), item_role_id: Number(assignRoleId),
}); });
toast.success('已分配'); toast.success(t('common.assigned'));
setAssignRoleId(''); setAssignRoleId('');
loadAssignments(); loadAssignments();
} catch (e: unknown) { } catch (e: unknown) {
toast.error((e as Error)?.message || '分配失败'); toast.error((e as Error)?.message || t('deploy.rbac.assignFail'));
} finally { setAssignLoading(false); } } finally { setAssignLoading(false); }
}; };
const handleRevoke = async (id: number) => { const handleRevoke = async (id: number) => {
try { try {
await deployApi.removeItemRole(Number(selectedUserId), id); await deployApi.removeItemRole(Number(selectedUserId), id);
toast.success('已撤销'); toast.success(t('deploy.toast.revoked'));
loadAssignments(); loadAssignments();
} catch { toast.error('撤销失败'); } } catch { toast.error(t('deploy.toast.revokeFailed')); }
}; };
const selectedUser = users.find((u) => String(u.id) === selectedUserId); const selectedUser = users.find((u) => String(u.id) === selectedUserId);
const pageTabs = [ const pageTabs = [
{ id: 'roles', label: '权限策略', badge: roles.length || undefined }, { id: 'roles', label: t('deploy.deployrbac.s93ef07'), badge: roles.length || undefined },
{ id: 'users', label: '用户授权' }, { id: 'users', label: t('deploy.deployrbac.s2de895') },
{ id: 'groups', label: '用户组' }, { id: 'groups', label: t('pipeline.userGroup') },
{ id: 'preview', label: '命中预览' }, { id: 'preview', label: t('pipeline.matchPreview') },
]; ];
return ( return (
<PageShell <PageShell
variant="list" variant="list"
title="Job 权限" title=t('deploy.deployNav.jobPermission')
subtitle="按流水线 code / Job 名称正则分配发布权限" subtitle=t('deploy.deployrbac.sa596d6')
icon={<Shield className="h-5 w-5" />} icon={<Shield className="h-5 w-5" />}
loading={loading} loading={loading}
tabs={pageTabs} tabs={pageTabs}
@@ -215,9 +218,9 @@ export default function DeployRBAC() {
roles.length === 0 ? ( roles.length === 0 ? (
<PageEmpty <PageEmpty
icon={<Shield className="h-10 w-10" />} icon={<Shield className="h-10 w-10" />}
title="暂无 Job 权限策略" title=t('deploy.deployrbac.sca578c')
description="创建策略后,用户将按正则自动获得匹配流水线的访问权限" description=t('deploy.deployrbac.s5ac382')
action={<Button onClick={() => setCreateOpen(true)}><Plus className="h-4 w-4 mr-1" />新建权限</Button>} action={<Button onClick={() => setCreateOpen(true)}><Plus className="h-4 w-4 mr-1" />{t('deploy.deployrbac.s605884')}</Button>}
/> />
) : ( ) : (
<div className="space-y-2"> <div className="space-y-2">
@@ -231,7 +234,7 @@ export default function DeployRBAC() {
<Badge variant="outline" className="text-[10px] border-[var(--dg-border)]"> <Badge variant="outline" className="text-[10px] border-[var(--dg-border)]">
{ROLE_LABEL[role.role] || role.role} {ROLE_LABEL[role.role] || role.role}
</Badge> </Badge>
{role.status === 0 && <Badge variant="outline" className="text-[10px]">已禁用</Badge>} {role.status === 0 && <Badge variant="outline" className="text-[10px]">{t('alert.disabled')}</Badge>}
<Badge <Badge
variant="outline" variant="outline"
className="text-[10px] cursor-pointer border-[var(--dg-border)]" className="text-[10px] cursor-pointer border-[var(--dg-border)]"
@@ -252,9 +255,9 @@ export default function DeployRBAC() {
<Select value={editRole} onValueChange={setEditRole}> <Select value={editRole} onValueChange={setEditRole}>
<SelectTrigger className="h-7 w-20 text-xs"><SelectValue /></SelectTrigger> <SelectTrigger className="h-7 w-20 text-xs"><SelectValue /></SelectTrigger>
<SelectContent> <SelectContent>
<SelectItem value="owner">拥有者</SelectItem> <SelectItem value="owner">{t('common.owner')}</SelectItem>
<SelectItem value="editor">编辑者</SelectItem> <SelectItem value="editor">{t('pipeline.editor')}</SelectItem>
<SelectItem value="viewer">查看者</SelectItem> <SelectItem value="viewer">{t('pipeline.viewer')}</SelectItem>
</SelectContent> </SelectContent>
</Select> </Select>
<Button size="icon" variant="ghost" className="h-7 w-7" onClick={() => handleUpdate(role.id)}><Check className="w-3.5 h-3.5" /></Button> <Button size="icon" variant="ghost" className="h-7 w-7" onClick={() => handleUpdate(role.id)}><Check className="w-3.5 h-3.5" /></Button>
@@ -262,8 +265,8 @@ export default function DeployRBAC() {
</> </>
) : ( ) : (
<> <>
<Button variant="ghost" size="sm" className="h-7 text-xs" onClick={() => { setEditing(role.id); setEditPattern(role.pattern); setEditRole(role.role); }}>编辑</Button> <Button variant="ghost" size="sm" className="h-7 text-xs" onClick={() => { setEditing(role.id); setEditPattern(role.pattern); setEditRole(role.role); }}>{t('common.edit')}</Button>
<Button variant="ghost" size="sm" className="h-7 text-xs" onClick={() => handleToggleStatus(role)}>{role.status ? '禁用' : '启用'}</Button> <Button variant="ghost" size="sm" className="h-7 text-xs" onClick={() => handleToggleStatus(role)}>{role.status ? t('common.disable') : t('common.enable')}</Button>
<Button variant="ghost" size="icon" className="h-7 w-7 text-[var(--dg-red)]" onClick={() => handleDelete(role)}><Trash2 className="w-3.5 h-3.5" /></Button> <Button variant="ghost" size="icon" className="h-7 w-7 text-[var(--dg-red)]" onClick={() => handleDelete(role)}><Trash2 className="w-3.5 h-3.5" /></Button>
</> </>
)} )}
@@ -281,9 +284,9 @@ export default function DeployRBAC() {
<CardContent className="p-4 space-y-4"> <CardContent className="p-4 space-y-4">
<div className="flex flex-wrap gap-3 items-end"> <div className="flex flex-wrap gap-3 items-end">
<div className="space-y-1 flex-1 min-w-[200px]"> <div className="space-y-1 flex-1 min-w-[200px]">
<Label className="text-xs">用户</Label> <Label className="text-xs">{t('system.roleUsers')}</Label>
<Select value={selectedUserId} onValueChange={setSelectedUserId}> <Select value={selectedUserId} onValueChange={setSelectedUserId}>
<SelectTrigger className="h-8 text-sm dg-input"><SelectValue placeholder="选择用户" /></SelectTrigger> <SelectTrigger className="h-8 text-sm dg-input"><SelectValue placeholder=t('deploy.rbac.selectUser') /></SelectTrigger>
<SelectContent className="max-h-60"> <SelectContent className="max-h-60">
{users.map((u) => ( {users.map((u) => (
<SelectItem key={u.id as number} value={String(u.id)}> <SelectItem key={u.id as number} value={String(u.id)}>
@@ -294,9 +297,9 @@ export default function DeployRBAC() {
</Select> </Select>
</div> </div>
<div className="space-y-1 w-48"> <div className="space-y-1 w-48">
<Label className="text-xs">权限策略</Label> <Label className="text-xs">{t('deploy.deployrbac.s93ef07')}</Label>
<Select value={assignRoleId} onValueChange={setAssignRoleId}> <Select value={assignRoleId} onValueChange={setAssignRoleId}>
<SelectTrigger className="h-8 text-sm dg-input"><SelectValue placeholder="选择策略" /></SelectTrigger> <SelectTrigger className="h-8 text-sm dg-input"><SelectValue placeholder=t('kubernetes.hpa.selectPolicy') /></SelectTrigger>
<SelectContent> <SelectContent>
{roles.filter((r) => r.status === 1).map((r) => ( {roles.filter((r) => r.status === 1).map((r) => (
<SelectItem key={r.id} value={String(r.id)}>{r.name} ({ROLE_LABEL[r.role]})</SelectItem> <SelectItem key={r.id} value={String(r.id)}>{r.name} ({ROLE_LABEL[r.role]})</SelectItem>
@@ -311,7 +314,7 @@ export default function DeployRBAC() {
</div> </div>
{selectedUser ? ( {selectedUser ? (
assignments.length === 0 ? ( assignments.length === 0 ? (
<p className="text-xs text-[var(--dg-text-muted)]">该用户尚未分配 Job 权限</p> <p className="text-xs text-[var(--dg-text-muted)]">{t('deploy.deployrbac.sef9548')}</p>
) : ( ) : (
<div className="space-y-1.5"> <div className="space-y-1.5">
{assignments.map((a) => { {assignments.map((a) => {
@@ -332,7 +335,7 @@ export default function DeployRBAC() {
</div> </div>
) )
) : ( ) : (
<p className="text-xs text-[var(--dg-text-muted)] flex items-center gap-1"><Users className="w-3.5 h-3.5" />选择用户后查看已分配权限</p> <p className="text-xs text-[var(--dg-text-muted)] flex items-center gap-1"><Users className="w-3.5 h-3.5" />{t('deploy.deployrbac.s9be00c')}</p>
)} )}
</CardContent> </CardContent>
</Card> </Card>
@@ -367,7 +370,7 @@ export default function DeployRBAC() {
</Badge> </Badge>
))} ))}
{previewRoleId !== null && previewMatches.length === 0 && ( {previewRoleId !== null && previewMatches.length === 0 && (
<span className="text-xs text-[var(--dg-text-muted)]">无匹配 — 请调整正则</span> <span className="text-xs text-[var(--dg-text-muted)]">{t('deploy.deployrbac.s64096f')}</span>
)} )}
</div> </div>
</CardContent> </CardContent>
@@ -19,6 +19,7 @@ import {
import { cn } from '@/lib/utils'; import { cn } from '@/lib/utils';
import { pipelineApi } from '@/api'; import { pipelineApi } from '@/api';
import { useUserStore } from '@/store'; import { useUserStore } from '@/store';
import { useTranslation } from 'react-i18next';
interface FileItem { interface FileItem {
name: string; name: string;
@@ -57,6 +58,7 @@ export function FileBrowserDialog({
runId, runId,
buildNumber, buildNumber,
}: FileBrowserDialogProps) { }: FileBrowserDialogProps) {
const { t } = useTranslation();
const [listing, setListing] = useState<ListingData | null>(null); const [listing, setListing] = useState<ListingData | null>(null);
const [loading, setLoading] = useState(false); const [loading, setLoading] = useState(false);
const [error, setError] = useState(''); const [error, setError] = useState('');
@@ -73,7 +75,7 @@ export function FileBrowserDialog({
setListing(data); setListing(data);
setCurrentPath(data?.current || ''); setCurrentPath(data?.current || '');
} catch (err) { } catch (err) {
setError(err?.message || '加载失败'); setError(err?.message || t('common.loadFailed'));
setListing(null); setListing(null);
} finally { } finally {
setLoading(false); setLoading(false);
@@ -114,7 +116,7 @@ export function FileBrowserDialog({
style={fullscreen ? { maxWidth: '100vw', width: '100vw', height: '100vh' } : { maxWidth: '700px', width: '85vw' }} style={fullscreen ? { maxWidth: '100vw', width: '100vw', height: '100vh' } : { maxWidth: '700px', width: '85vw' }}
> >
<DialogTitle className="sr-only">文件浏览器 #{buildNumber}</DialogTitle> <DialogTitle className="sr-only">文件浏览器 #{buildNumber}</DialogTitle>
<DialogDescription className="sr-only">流水线构建目录文件浏览</DialogDescription> <DialogDescription className="sr-only">{t('deploy.pipeline.buildDirFiles')}</DialogDescription>
{/* Header */} {/* Header */}
<div className="flex items-center justify-between px-4 py-2.5 border-b border-[var(--dg-border)] shrink-0"> <div className="flex items-center justify-between px-4 py-2.5 border-b border-[var(--dg-border)] shrink-0">
@@ -184,9 +186,9 @@ export function FileBrowserDialog({
<table className="w-full text-sm"> <table className="w-full text-sm">
<thead className="sticky top-0 bg-[var(--dg-bg-primary)] border-b border-[var(--dg-border)]"> <thead className="sticky top-0 bg-[var(--dg-bg-primary)] border-b border-[var(--dg-border)]">
<tr className="text-left text-[var(--dg-text-muted)] text-xs"> <tr className="text-left text-[var(--dg-text-muted)] text-xs">
<th className="py-2 pl-4 pr-2 font-medium">名称</th> <th className="py-2 pl-4 pr-2 font-medium">{t('common.name')}</th>
<th className="py-2 px-2 font-medium w-24 text-right">大小</th> <th className="py-2 px-2 font-medium w-24 text-right">{t('deploy.table.size')}</th>
<th className="py-2 pr-4 pl-2 font-medium w-40 hidden sm:table-cell">修改时间</th> <th className="py-2 pr-4 pl-2 font-medium w-40 hidden sm:table-cell">{t('deploy.table.modifyTime')}</th>
<th className="py-2 pr-4 pl-2 font-medium w-16" /> <th className="py-2 pr-4 pl-2 font-medium w-16" />
</tr> </tr>
</thead> </thead>
@@ -243,7 +245,7 @@ export function FileBrowserDialog({
<button <button
onClick={(e) => { e.stopPropagation(); downloadFile(file); }} onClick={(e) => { e.stopPropagation(); downloadFile(file); }}
className="p-1 rounded hover:bg-[var(--dg-bg-hover)] text-[var(--dg-text-secondary)] hover:text-white" className="p-1 rounded hover:bg-[var(--dg-bg-hover)] text-[var(--dg-text-secondary)] hover:text-white"
title="下载" title=t('common.download')
> >
<Download className="h-3.5 w-3.5" /> <Download className="h-3.5 w-3.5" />
</button> </button>
@@ -255,7 +257,7 @@ export function FileBrowserDialog({
{listing.dirs?.length === 0 && listing.files?.length === 0 && !currentPath && ( {listing.dirs?.length === 0 && listing.files?.length === 0 && !currentPath && (
<tr> <tr>
<td colSpan={4} className="py-8 text-center text-[var(--dg-text-muted)]"> <td colSpan={4} className="py-8 text-center text-[var(--dg-text-muted)]">
{loading ? '加载中...' : '目录为空'} {loading ? t('common.loading') : t('deploy.label.emptyDir')}
</td> </td>
</tr> </tr>
)} )}
@@ -15,15 +15,17 @@ import { FileBrowserDialog } from './FileBrowserDialog';
import { PageShell } from '@/components/layout/PageShell'; import { PageShell } from '@/components/layout/PageShell';
import { StatStrip } from '@/components/ui/stat-strip'; import { StatStrip } from '@/components/ui/stat-strip';
import type { JsonData } from '@/types/common'; import type { JsonData } from '@/types/common';
import { useTranslation } from 'react-i18next';
import i18n from '@/i18n';
// ═══════════ 阶段定义 (与 PipelineManager 共用) ═══════════ // ═══════════ 阶段定义 (与 PipelineManager 共用) ═══════════
const STAGE_DEFS = [ const STAGE_DEFS = [
{ key: 'checkout', label: '代码检出', icon: GitBranch, color: '#6366F1', order: 1 }, { key: 'checkout', label: i18n.t('pipeline.checkout'), icon: GitBranch, color: '#6366F1', order: 1 },
{ key: 'build', label: '构建', icon: Box, color: '#F59E0B', order: 2 }, { key: 'build', label: i18n.t('pipeline.build'), icon: Box, color: '#F59E0B', order: 2 },
{ key: 'test', label: '测试', icon: CheckCircle2,color: '#10B981', order: 3 }, { key: 'test', label: i18n.t('common.test'), icon: CheckCircle2,color: '#10B981', order: 3 },
{ key: 'image', label: '镜像打包', icon: Container, color: '#06B6D4', order: 4 }, { key: 'image', label: i18n.t('deploy.stage.image'), icon: Container, color: '#06B6D4', order: 4 },
{ key: 'deploy', label: '部署', icon: Rocket, color: '#EF4444', order: 5 }, { key: 'deploy', label: i18n.t('pipeline.deploy'), icon: Rocket, color: '#EF4444', order: 5 },
{ key: 'verify', label: '验证', icon: ShieldCheck, color: '#3B82F6', order: 6 }, { key: 'verify', label: i18n.t('common.validate'), icon: ShieldCheck, color: '#3B82F6', order: 6 },
].sort((a, b) => a.order - b.order); ].sort((a, b) => a.order - b.order);
interface PipelineRun { interface PipelineRun {
@@ -74,10 +76,10 @@ const STATUS_ICONS: JsonData = {
function formatDuration(seconds: number): string { function formatDuration(seconds: number): string {
if (!seconds) return '-'; if (!seconds) return '-';
if (seconds < 60) return `${seconds}秒`; if (seconds < 60) return i18n.t('deploy.pipelinerundetail.sbe383c', { seconds: seconds });
const m = Math.floor(seconds / 60); const m = Math.floor(seconds / 60);
const s = seconds % 60; const s = seconds % 60;
return `${m}分${s}秒`; return i18n.t('deploy.pipelinerundetail.s084409', { m: m, s: s });
} }
function formatTime(ts: string): string { function formatTime(ts: string): string {
@@ -130,6 +132,7 @@ function getStageLogSummary(logs: LogEntry[], stageKey: string): string {
} }
export default function PipelineRunDetail() { export default function PipelineRunDetail() {
const { t } = useTranslation();
const { code: pipelineCode } = useParams<{ code: string }>(); const { code: pipelineCode } = useParams<{ code: string }>();
const [pipeline, setPipeline] = useState<JsonData>(null); const [pipeline, setPipeline] = useState<JsonData>(null);
const [runs, setRuns] = useState<PipelineRun[]>([]); const [runs, setRuns] = useState<PipelineRun[]>([]);
@@ -165,7 +168,7 @@ export default function PipelineRunDetail() {
if (!selectedRun && list.length > 0) { if (!selectedRun && list.length > 0) {
setSelectedRun(list[0]); setSelectedRun(list[0]);
} }
} catch { toast.error('获取执行记录失败'); } } catch { toast.error(t('deploy.pipelinerundetail.sa4e14e')); }
finally { setLoading(false); } finally { setLoading(false); }
}, [pipelineCode, pageSize]); }, [pipelineCode, pageSize]);
@@ -236,18 +239,18 @@ export default function PipelineRunDetail() {
const triggerRun = async () => { const triggerRun = async () => {
try { try {
await pipelineApi.triggerByCode(pipelineCode); await pipelineApi.triggerByCode(pipelineCode);
toast.success('已触发'); toast.success(t('automation.triggered'));
fetchRuns(); fetchRuns();
} catch { toast.error('触发失败'); } } catch { toast.error(t('automation.triggerFailed')); }
}; };
// 停止 // 停止
const stopRun = async (runId: number) => { const stopRun = async (runId: number) => {
try { try {
await pipelineApi.stopRunByCode(pipelineCode, runId); await pipelineApi.stopRunByCode(pipelineCode, runId);
toast.success('已停止'); toast.success(t('common.stopped'));
fetchRuns(); fetchRuns();
} catch { toast.error('停止失败'); } } catch { toast.error(t('pipeline.stopFailed')); }
}; };
// 批量删除 // 批量删除
@@ -256,10 +259,10 @@ export default function PipelineRunDetail() {
setDeleting(true); setDeleting(true);
try { try {
await pipelineApi.batchDeleteRuns(pipelineCode, Array.from(selectedIds)); await pipelineApi.batchDeleteRuns(pipelineCode, Array.from(selectedIds));
toast.success(`已删除 ${selectedIds.size} 条记录`); toast.success(t('deploy.pipelinerundetail.s4b340c', { selectedIds.size: selectedIds.size }));
setSelectedIds(new Set()); setSelectedIds(new Set());
fetchRuns(); fetchRuns();
} catch { toast.error('批量删除失败'); } } catch { toast.error(t('cloud.batchDeleteFailed')); }
finally { setDeleting(false); } finally { setDeleting(false); }
}; };
@@ -298,16 +301,16 @@ export default function PipelineRunDetail() {
return ( return (
<PageShell <PageShell
variant="workspace" variant="workspace"
title={pipeline?.name || '流水线详情'} title={pipeline?.name || t('deploy.pipeline.detail')}
subtitle={selectedRun ? `发布 #${selectedRun.build_number}` : (pipeline?.code ? `code: ${pipeline.code}` : '执行记录与日志')} subtitle={selectedRun ? t('deploy.pipelinerundetail.se9940a', { selectedRun.build_number: selectedRun.build_number }) : (pipeline?.code ? `code: ${pipeline.code}` : t('deploy.pipelinerundetail.sefc52b'))}
icon={<History className="h-5 w-5" />} icon={<History className="h-5 w-5" />}
contentClassName="space-y-4 h-full flex flex-col" contentClassName="space-y-4 h-full flex flex-col"
metrics={( metrics={(
<StatStrip <StatStrip
items={[ items={[
{ label: '执行记录', value: runs.length, color: 'blue' }, { label: t('deploy.pipelinerundetail.s9b409b'), value: runs.length, color: 'blue' },
{ label: '成功', value: successCount, color: 'emerald' }, { label: t('common.success'), value: successCount, color: 'emerald' },
{ label: '执行中', value: runningCount, color: 'amber' }, { label: t('common.executing'), value: runningCount, color: 'amber' },
]} ]}
/> />
)} )}
@@ -331,9 +334,9 @@ export default function PipelineRunDetail() {
onChange={e => setPageSize(Number(e.target.value))} onChange={e => setPageSize(Number(e.target.value))}
className="h-8 px-2 text-xs rounded border border-[var(--dg-border)] dg-input" className="h-8 px-2 text-xs rounded border border-[var(--dg-border)] dg-input"
> >
<option value={10}>10条/页</option> <option value={10}>{t('deploy.pipelinerundetail.s8776a1')}</option>
<option value={20}>20条/页</option> <option value={20}>{t('deploy.pipelinerundetail.s96dbf3')}</option>
<option value={30}>30条/页</option> <option value={30}>{t('deploy.pipelinerundetail.s074a81')}</option>
</select> </select>
<Button variant="outline" size="sm" className="dg-btn-secondary" onClick={fetchRuns}> <Button variant="outline" size="sm" className="dg-btn-secondary" onClick={fetchRuns}>
<RefreshCw className="w-4 h-4 mr-1" />刷新 <RefreshCw className="w-4 h-4 mr-1" />刷新
@@ -380,7 +383,7 @@ export default function PipelineRunDetail() {
<div key={def.key} className="flex items-center"> <div key={def.key} className="flex items-center">
<button <button
onClick={() => setSelectedStage(selectedStage === def.key ? null : def.key)} onClick={() => setSelectedStage(selectedStage === def.key ? null : def.key)}
title={`${def.label}${status ? ` (${status})` : ''} — 点击查看日志`} title={`${def.label}${status ? ` (${status})t('deploy.pipelinerundetail.sdaf2bb')}
className={`flex items-center gap-1.5 px-3 py-2 text-[12px] font-semibold border shadow-sm transition-all cursor-pointer className={`flex items-center gap-1.5 px-3 py-2 text-[12px] font-semibold border shadow-sm transition-all cursor-pointer
${isActive ? 'ring-1 ring-offset-0 scale-[1.02]' : 'hover:brightness-110'}`} ${isActive ? 'ring-1 ring-offset-0 scale-[1.02]' : 'hover:brightness-110'}`}
style={{ style={{
@@ -403,7 +406,7 @@ export default function PipelineRunDetail() {
})} })}
{selectedRun && ( {selectedRun && (
<span className="ml-auto text-[10px] text-[var(--dg-text-secondary)] opacity-40 shrink-0 pl-3 whitespace-nowrap"> <span className="ml-auto text-[10px] text-[var(--dg-text-secondary)] opacity-40 shrink-0 pl-3 whitespace-nowrap">
{selectedStage ? STAGE_DEFS.find(d => d.key === selectedStage)?.label : '全阶段'} {selectedStage ? STAGE_DEFS.find(d => d.key === selectedStage)?.label : t('pipeline.allStages')}
</span> </span>
)} )}
</div> </div>
@@ -420,7 +423,7 @@ export default function PipelineRunDetail() {
) : runs.length === 0 ? ( ) : runs.length === 0 ? (
<div className="text-center py-12 border border-dashed border-[var(--dg-border)] rounded-lg m-4"> <div className="text-center py-12 border border-dashed border-[var(--dg-border)] rounded-lg m-4">
<History className="w-10 h-10 mx-auto mb-3 text-[var(--dg-text-muted)]" /> <History className="w-10 h-10 mx-auto mb-3 text-[var(--dg-text-muted)]" />
<p className="text-[var(--dg-text-secondary)]">暂无执行记录,点击"立即执行"触发构建</p> <p className="text-[var(--dg-text-secondary)]">{t('deploy.run.noRecordsHint')}</p>
</div> </div>
) : ( ) : (
<table className="w-full text-sm"> <table className="w-full text-sm">
@@ -430,13 +433,13 @@ export default function PipelineRunDetail() {
<input type="checkbox" checked={selectedIds.size === runs.length && runs.length > 0} <input type="checkbox" checked={selectedIds.size === runs.length && runs.length > 0}
onChange={toggleAll} className="rounded" /> onChange={toggleAll} className="rounded" />
</th> </th>
<th className="px-3 py-2.5 text-left font-medium text-[var(--dg-text-secondary)] w-16">构建</th> <th className="px-3 py-2.5 text-left font-medium text-[var(--dg-text-secondary)] w-16">{t('pipeline.build')}</th>
<th className="px-3 py-2.5 text-left font-medium text-[var(--dg-text-secondary)] w-20">状态</th> <th className="px-3 py-2.5 text-left font-medium text-[var(--dg-text-secondary)] w-20">{t('common.status')}</th>
<th className="px-3 py-2.5 text-left font-medium text-[var(--dg-text-secondary)]">触发方式</th> <th className="px-3 py-2.5 text-left font-medium text-[var(--dg-text-secondary)]">{t('deploy.table.trigger')}</th>
<th className="px-3 py-2.5 text-left font-medium text-[var(--dg-text-secondary)]">用户</th> <th className="px-3 py-2.5 text-left font-medium text-[var(--dg-text-secondary)]">{t('system.roleUsers')}</th>
<th className="px-3 py-2.5 text-left font-medium text-[var(--dg-text-secondary)]">耗时</th> <th className="px-3 py-2.5 text-left font-medium text-[var(--dg-text-secondary)]">{t('common.elapsed')}</th>
<th className="px-3 py-2.5 text-left font-medium text-[var(--dg-text-secondary)] hidden md:table-cell">时间</th> <th className="px-3 py-2.5 text-left font-medium text-[var(--dg-text-secondary)] hidden md:table-cell">{t('monitor.logTime')}</th>
<th className="px-3 py-2.5 text-right font-medium text-[var(--dg-text-secondary)] w-32">操作</th> <th className="px-3 py-2.5 text-right font-medium text-[var(--dg-text-secondary)] w-32">{t('common.actions')}</th>
</tr> </tr>
</thead> </thead>
<tbody> <tbody>
@@ -457,11 +460,11 @@ export default function PipelineRunDetail() {
<td className="px-3 py-2.5"> <td className="px-3 py-2.5">
<Badge className={`text-xs ${STATUS_BADGES[run.status] || ''} flex items-center gap-1 w-fit`}> <Badge className={`text-xs ${STATUS_BADGES[run.status] || ''} flex items-center gap-1 w-fit`}>
<StatusIcon className={`w-3 h-3 ${run.status === 'running' ? 'animate-spin' : ''}`} /> <StatusIcon className={`w-3 h-3 ${run.status === 'running' ? 'animate-spin' : ''}`} />
{run.status === 'success' ? '成功' {run.status === 'success' ? t('common.success')
: run.status === 'failed' ? '失败' : run.status === 'failed' ? t('common.failed')
: run.status === 'running' ? '执行中' : run.status === 'running' ? t('common.executing')
: run.status === 'cancelled' ? '已取消' : run.status === 'cancelled' ? t('deploy.toast.cancelled')
: '待执行'} : t('deploy.status.pending')}
</Badge> </Badge>
</td> </td>
<td className="px-3 py-2.5"> <td className="px-3 py-2.5">
@@ -572,7 +575,7 @@ export default function PipelineRunDetail() {
<div className="h-full overflow-y-auto bg-[#0d1117] font-mono text-xs leading-5 p-4" style={{ minHeight: 280 }}> <div className="h-full overflow-y-auto bg-[#0d1117] font-mono text-xs leading-5 p-4" style={{ minHeight: 280 }}>
{filteredLogs.length === 0 && selectedRun.status !== 'running' ? ( {filteredLogs.length === 0 && selectedRun.status !== 'running' ? (
<div className="text-center py-12 dg-text-muted"> <div className="text-center py-12 dg-text-muted">
{selectedStage ? '该阶段暂无日志输出' : '暂无日志输出'} {selectedStage ? t('deploy.pipeline.noLogStage') : t('deploy.pipeline.logOutput')}
</div> </div>
) : ( ) : (
<> <>
@@ -630,7 +633,7 @@ export default function PipelineRunDetail() {
{selectedRun.status === 'running' && ( {selectedRun.status === 'running' && (
<div className="flex items-center gap-2 mt-2 py-1.5 px-3 bg-blue-500/10 border-l-4 border-blue-500 rounded-r"> <div className="flex items-center gap-2 mt-2 py-1.5 px-3 bg-blue-500/10 border-l-4 border-blue-500 rounded-r">
<Loader2 className="w-3 h-3 animate-spin dg-text-blue shrink-0" /> <Loader2 className="w-3 h-3 animate-spin dg-text-blue shrink-0" />
<span className="text-[11px] text-blue-300 font-medium">流水线执行中,实时输出...</span> <span className="text-[11px] text-blue-300 font-medium">{t('deploy.pipeline.realtimeOutput')}</span>
<span className="flex gap-1 ml-1"> <span className="flex gap-1 ml-1">
<span className="w-1 h-1 rounded-full bg-blue-400 animate-bounce" style={{ animationDelay: '0ms' }}></span> <span className="w-1 h-1 rounded-full bg-blue-400 animate-bounce" style={{ animationDelay: '0ms' }}></span>
<span className="w-1 h-1 rounded-full bg-blue-400 animate-bounce" style={{ animationDelay: '150ms' }}></span> <span className="w-1 h-1 rounded-full bg-blue-400 animate-bounce" style={{ animationDelay: '150ms' }}></span>
@@ -22,6 +22,7 @@ import {
import { Loader2 } from 'lucide-react'; import { Loader2 } from 'lucide-react';
import { releaseApi } from '@/api'; import { releaseApi } from '@/api';
import { toast } from 'sonner'; import { toast } from 'sonner';
import { useTranslation } from 'react-i18next';
interface ReleaseApplyDialogProps { interface ReleaseApplyDialogProps {
open: boolean; open: boolean;
@@ -30,6 +31,7 @@ interface ReleaseApplyDialogProps {
} }
export function ReleaseApplyDialog({ open, onOpenChange, onSuccess }: ReleaseApplyDialogProps) { export function ReleaseApplyDialog({ open, onOpenChange, onSuccess }: ReleaseApplyDialogProps) {
const { t } = useTranslation();
const [submitting, setSubmitting] = useState(false); const [submitting, setSubmitting] = useState(false);
const [form, setForm] = useState({ const [form, setForm] = useState({
appName: '', appName: '',
@@ -49,7 +51,7 @@ export function ReleaseApplyDialog({ open, onOpenChange, onSuccess }: ReleaseApp
const handleSubmit = async () => { const handleSubmit = async () => {
if (!form.appName.trim() || !form.version.trim()) { if (!form.appName.trim() || !form.version.trim()) {
toast.error('请填写应用名称和版本号'); toast.error(t('deploy.release.nameVerRequired'));
return; return;
} }
setSubmitting(true); setSubmitting(true);
@@ -62,11 +64,11 @@ export function ReleaseApplyDialog({ open, onOpenChange, onSuccess }: ReleaseApp
commit_msg: form.commitMsg.trim(), commit_msg: form.commitMsg.trim(),
description: form.description.trim(), description: form.description.trim(),
}); });
toast.success('发布申请已提交'); toast.success(t('deploy.release.submitFail'));
onOpenChange(false); onOpenChange(false);
onSuccess?.(); onSuccess?.();
} catch { } catch {
toast.error('创建失败'); toast.error(t('monitor.quickSetupFailed'));
} finally { } finally {
setSubmitting(false); setSubmitting(false);
} }
@@ -76,22 +78,22 @@ export function ReleaseApplyDialog({ open, onOpenChange, onSuccess }: ReleaseApp
<Dialog open={open} onOpenChange={onOpenChange}> <Dialog open={open} onOpenChange={onOpenChange}>
<DialogContent className="max-w-2xl"> <DialogContent className="max-w-2xl">
<DialogHeader> <DialogHeader>
<DialogTitle>新建发布</DialogTitle> <DialogTitle>{t('pipeline.newRelease')}</DialogTitle>
<DialogDescription>创建新的应用版本发布申请</DialogDescription> <DialogDescription>{t('deploy.release.createNew')}</DialogDescription>
</DialogHeader> </DialogHeader>
<div className="space-y-4 py-4"> <div className="space-y-4 py-4">
<div> <div>
<Label>应用名称</Label> <Label>{t('pipeline.releaseApp')}</Label>
<Input <Input
value={form.appName} value={form.appName}
onChange={(e) => setForm({ ...form, appName: e.target.value })} onChange={(e) => setForm({ ...form, appName: e.target.value })}
placeholder="如:用户中心服务" placeholder=t('deploy.releaseCreate.appPlaceholder')
className="mt-1" className="mt-1"
/> />
</div> </div>
<div className="grid grid-cols-2 gap-4"> <div className="grid grid-cols-2 gap-4">
<div> <div>
<Label>版本号</Label> <Label>{t('pipeline.releaseVersion')}</Label>
<Input <Input
value={form.version} value={form.version}
onChange={(e) => setForm({ ...form, version: e.target.value })} onChange={(e) => setForm({ ...form, version: e.target.value })}
@@ -100,7 +102,7 @@ export function ReleaseApplyDialog({ open, onOpenChange, onSuccess }: ReleaseApp
/> />
</div> </div>
<div> <div>
<Label>目标环境</Label> <Label>{t('pipeline.targetEnv')}</Label>
<Select <Select
value={form.environment} value={form.environment}
onValueChange={(value) => setForm({ ...form, environment: value })} onValueChange={(value) => setForm({ ...form, environment: value })}
@@ -109,10 +111,10 @@ export function ReleaseApplyDialog({ open, onOpenChange, onSuccess }: ReleaseApp
<SelectValue /> <SelectValue />
</SelectTrigger> </SelectTrigger>
<SelectContent> <SelectContent>
<SelectItem value="dev">开发环境</SelectItem> <SelectItem value="dev">{t('pipeline.devEnv')}</SelectItem>
<SelectItem value="test">测试环境</SelectItem> <SelectItem value="test">{t('pipeline.testEnv')}</SelectItem>
<SelectItem value="staging">预发环境</SelectItem> <SelectItem value="staging">{t('pipeline.stagingEnv')}</SelectItem>
<SelectItem value="prod">生产环境</SelectItem> <SelectItem value="prod">{t('pipeline.prodEnv')}</SelectItem>
</SelectContent> </SelectContent>
</Select> </Select>
</div> </div>
@@ -128,21 +130,21 @@ export function ReleaseApplyDialog({ open, onOpenChange, onSuccess }: ReleaseApp
/> />
</div> </div>
<div> <div>
<Label>提交信息</Label> <Label>{t('deploy.releaseCreate.commitMsg')}</Label>
<Input <Input
value={form.commitMsg} value={form.commitMsg}
onChange={(e) => setForm({ ...form, commitMsg: e.target.value })} onChange={(e) => setForm({ ...form, commitMsg: e.target.value })}
placeholder="feat: 新增功能" placeholder=t('deploy.releaseCreate.commitMsgPlaceholder')
className="mt-1" className="mt-1"
/> />
</div> </div>
</div> </div>
<div> <div>
<Label>发布说明</Label> <Label>{t('pipeline.releaseDesc')}</Label>
<Textarea <Textarea
value={form.description} value={form.description}
onChange={(e) => setForm({ ...form, description: e.target.value })} onChange={(e) => setForm({ ...form, description: e.target.value })}
placeholder="描述本次发布的内容..." placeholder=t('deploy.releaseCreate.descPlaceholder')
className="mt-1" className="mt-1"
/> />
</div> </div>
@@ -13,6 +13,7 @@ import { AlertCircle, X, Check, Loader2 } from 'lucide-react';
import { releaseApi } from '@/api'; import { releaseApi } from '@/api';
import { toast } from 'sonner'; import { toast } from 'sonner';
import type { JsonData } from '@/types/common'; import type { JsonData } from '@/types/common';
import { useTranslation } from 'react-i18next';
interface ReleaseApproveDialogProps { interface ReleaseApproveDialogProps {
release: JsonData | null; release: JsonData | null;
@@ -22,6 +23,7 @@ interface ReleaseApproveDialogProps {
} }
export function ReleaseApproveDialog({ release, open, onOpenChange, onSuccess }: ReleaseApproveDialogProps) { export function ReleaseApproveDialog({ release, open, onOpenChange, onSuccess }: ReleaseApproveDialogProps) {
const { t } = useTranslation();
const [submitting, setSubmitting] = useState(false); const [submitting, setSubmitting] = useState(false);
// 提交完成即重置 loading(防复用) // Logan.Li // 提交完成即重置 loading(防复用) // Logan.Li
@@ -35,15 +37,15 @@ export function ReleaseApproveDialog({ release, open, onOpenChange, onSuccess }:
try { try {
if (approved) { if (approved) {
await releaseApi.approveRelease(release.id); await releaseApi.approveRelease(release.id);
toast.success('审批通过'); toast.success(t('approval.flow.approveTitle'));
} else { } else {
await releaseApi.rejectRelease(release.id); await releaseApi.rejectRelease(release.id);
toast.success('已驳回'); toast.success(t('deploy.toast.rejected'));
} }
onOpenChange(false); onOpenChange(false);
onSuccess?.(); onSuccess?.();
} catch { } catch {
toast.error(approved ? '审批失败' : '驳回失败'); toast.error(approved ? t('approval.msg.approveFailed') : t('deploy.release.rejectFail'));
} finally { } finally {
setSubmitting(false); setSubmitting(false);
} }
@@ -53,7 +55,7 @@ export function ReleaseApproveDialog({ release, open, onOpenChange, onSuccess }:
<Dialog open={open} onOpenChange={onOpenChange}> <Dialog open={open} onOpenChange={onOpenChange}>
<DialogContent> <DialogContent>
<DialogHeader> <DialogHeader>
<DialogTitle>审批发布</DialogTitle> <DialogTitle>{t('pipeline.approve')}</DialogTitle>
<DialogDescription> <DialogDescription>
{release?.app_name} - {release?.version} {release?.app_name} - {release?.version}
</DialogDescription> </DialogDescription>
@@ -61,7 +63,7 @@ export function ReleaseApproveDialog({ release, open, onOpenChange, onSuccess }:
<div className="py-4"> <div className="py-4">
{release?.description && ( {release?.description && (
<div className="p-3 rounded-lg bg-[var(--dg-bg-tertiary)] mb-4"> <div className="p-3 rounded-lg bg-[var(--dg-bg-tertiary)] mb-4">
<p className="text-xs text-[var(--dg-text-secondary)] mb-1">发布说明</p> <p className="text-xs text-[var(--dg-text-secondary)] mb-1">{t('pipeline.releaseDesc')}</p>
<p className="text-sm text-[var(--dg-text-primary)]">{release.description}</p> <p className="text-sm text-[var(--dg-text-primary)]">{release.description}</p>
</div> </div>
)} )}
@@ -8,6 +8,7 @@ import { useConfirm } from '@/components/ui/confirm-dialog';
import { toast } from 'sonner'; import { toast } from 'sonner';
import { deployApi } from '@/api'; import { deployApi } from '@/api';
import type { JsonData } from '@/types/common'; import type { JsonData } from '@/types/common';
import { useTranslation } from 'react-i18next';
interface ToolConfig { interface ToolConfig {
id: number; name: string; display_name: string; description: string; id: number; name: string; display_name: string; description: string;
@@ -34,6 +35,7 @@ const categoryColor: Record<string, string> = {
const VERSIONED_TOOLS = ['jdk', 'golang', 'nodejs', 'maven', 'nvm']; const VERSIONED_TOOLS = ['jdk', 'golang', 'nodejs', 'maven', 'nvm'];
export default function ToolConfigTab() { export default function ToolConfigTab() {
const { t } = useTranslation();
const confirm = useConfirm(); const confirm = useConfirm();
const [tools, setTools] = useState<ToolConfig[]>([]); const [tools, setTools] = useState<ToolConfig[]>([]);
const [loading, setLoading] = useState(false); const [loading, setLoading] = useState(false);
@@ -52,7 +54,7 @@ export default function ToolConfigTab() {
try { try {
const res: JsonData = await deployApi.getTools(); const res: JsonData = await deployApi.getTools();
setTools((res as JsonData)?.list || []); setTools((res as JsonData)?.list || []);
} catch { toast.error('获取工具配置失败'); } } catch { toast.error(t('deploy.tool.getToolFail')); }
finally { setLoading(false); } finally { setLoading(false); }
}; };
@@ -77,7 +79,7 @@ export default function ToolConfigTab() {
} }
setVersionDialog({ tool, versions }); setVersionDialog({ tool, versions });
const preferred = versions.find((v) => v.version === 'lts')?.version const preferred = versions.find((v) => v.version === 'lts')?.version
|| versions.find((v) => v.label.includes('推荐'))?.version || versions.find((v) => v.label.includes(t('common.recommended')))?.version
|| tool.default_version || tool.default_version
|| versions[0]?.version || versions[0]?.version
|| ''; || '';
@@ -93,21 +95,21 @@ export default function ToolConfigTab() {
try { try {
const v = version || tool.default_version; const v = version || tool.default_version;
await deployApi.installTool(tool.id, v); await deployApi.installTool(tool.id, v);
toast.success(`${tool.display_name}${v ? ` (${v})` : ''} 安装已触发,可在审计日志查看结果`); toast.success(`${tool.display_name}${v ? ` (${v})t('deploy.toolconfigtab.s5002c0'));
setVersionDialog(null); setVersionDialog(null);
setInstalling(null); setInstalling(null);
void fetchTools(); void fetchTools();
} catch { } catch {
toast.error('触发安装失败'); toast.error(t('deploy.toolconfigtab.se80fdc'));
setInstalling(null); setInstalling(null);
} }
}; };
const handleUninstall = async (tool: ToolConfig) => { const handleUninstall = async (tool: ToolConfig) => {
const ok = await confirm({ const ok = await confirm({
title: '卸载工具', title: t('agent.uninstallTool'),
description: `确定卸载 ${tool.display_name}?卸载后可重新选择版本安装。`, description: t('deploy.toolconfigtab.s8d9b47', { tool.display_name: tool.display_name }),
confirmText: '卸载', confirmText: t('agent.uninstall'),
variant: 'destructive', variant: 'destructive',
}); });
if (!ok) return; if (!ok) return;
@@ -115,10 +117,10 @@ export default function ToolConfigTab() {
setUninstalling(tool.id); setUninstalling(tool.id);
try { try {
await deployApi.uninstallTool(tool.id); await deployApi.uninstallTool(tool.id);
toast.success(`${tool.display_name} 已卸载,可重新安装`); toast.success(t('deploy.toolconfigtab.sda0cb3', { tool.display_name: tool.display_name }));
void fetchTools(); void fetchTools();
} catch { } catch {
toast.error('卸载失败'); toast.error(t('agent.uninstallFailed'));
} finally { } finally {
setUninstalling(null); setUninstalling(null);
} }
@@ -127,9 +129,9 @@ export default function ToolConfigTab() {
const handleCheckStatus = async (tool: ToolConfig) => { const handleCheckStatus = async (tool: ToolConfig) => {
try { try {
const res: JsonData = await deployApi.checkTool(tool.id); const res: JsonData = await deployApi.checkTool(tool.id);
toast.success(res?.available ? `${tool.display_name} 可用` : `${tool.display_name} 不可用`); toast.success(res?.available ? t('deploy.toolconfigtab.sa5b175', { tool.display_name: tool.display_name }) : t('deploy.toolconfigtab.sf13096', { tool.display_name: tool.display_name }));
fetchTools(); fetchTools();
} catch { toast.error('检测失败'); } } catch { toast.error(t('deploy.toolconfigtab.s6bc0fb')); }
}; };
// 检测工具安装状态(磁盘验证)// Logan.Li // 检测工具安装状态(磁盘验证)// Logan.Li
@@ -140,14 +142,14 @@ export default function ToolConfigTab() {
const res: JsonData = await deployApi.checkTool(tool.id); const res: JsonData = await deployApi.checkTool(tool.id);
const elapsed = ((Date.now() - start) / 1000).toFixed(1); const elapsed = ((Date.now() - start) / 1000).toFixed(1);
if (res?.available) { if (res?.available) {
toast.success(`${tool.display_name} 已就绪${res.version ? ` (${res.version})` : ''} (${elapsed}s)`); toast.success(t('deploy.toolconfigtab.s0ac554', { tool.display_name: tool.display_name }) (${res.version})` : ''} (${elapsed}s)`);
} else { } else {
const errMsg = (res?.tool as ToolConfig | undefined)?.error_msg; const errMsg = (res?.tool as ToolConfig | undefined)?.error_msg;
toast(`${tool.display_name} 未安装或不可用`, { description: errMsg || '可点击「安装」触发懒加载' }); toast(t('deploy.toolconfigtab.s258f2b', { tool.display_name: tool.display_name }), { description: errMsg || t('deploy.toolconfigtab.s6f0fef') });
} }
fetchTools(); fetchTools();
} catch { } catch {
toast.error(`${tool.display_name} 检测失败`); toast.error(t('deploy.toolconfigtab.s8c74ac', { tool.display_name: tool.display_name }));
} }
setTesting(null); setTesting(null);
}; };
@@ -176,10 +178,10 @@ export default function ToolConfigTab() {
<table className="w-full text-sm"> <table className="w-full text-sm">
<thead className="bg-[var(--dg-bg-tertiary)] border-b border-[var(--dg-border)]"> <thead className="bg-[var(--dg-bg-tertiary)] border-b border-[var(--dg-border)]">
<tr> <tr>
<th className="px-3 py-2 text-left font-medium text-[var(--dg-text-secondary)]">工具</th> <th className="px-3 py-2 text-left font-medium text-[var(--dg-text-secondary)]">{t('pipeline.tool')}</th>
<th className="px-3 py-2 text-left font-medium text-[var(--dg-text-secondary)] hidden sm:table-cell">分类</th> <th className="px-3 py-2 text-left font-medium text-[var(--dg-text-secondary)] hidden sm:table-cell">{t('common.category')}</th>
<th className="px-3 py-2 text-left font-medium text-[var(--dg-text-secondary)]">状态</th> <th className="px-3 py-2 text-left font-medium text-[var(--dg-text-secondary)]">{t('common.status')}</th>
<th className="px-3 py-2 text-right font-medium text-[var(--dg-text-secondary)]">操作</th> <th className="px-3 py-2 text-right font-medium text-[var(--dg-text-secondary)]">{t('common.actions')}</th>
</tr> </tr>
</thead> </thead>
<tbody> <tbody>
@@ -283,7 +285,7 @@ export default function ToolConfigTab() {
测试 测试
</Button> </Button>
)} )}
<Button variant="ghost" size="icon" className="h-7 w-7" onClick={() => handleCheckStatus(tool)} title="检测"> <Button variant="ghost" size="icon" className="h-7 w-7" onClick={() => handleCheckStatus(tool)} title=t('common.detect')>
<Settings2 className="w-3.5 h-3.5" /> <Settings2 className="w-3.5 h-3.5" />
</Button> </Button>
</div> </div>
@@ -300,10 +302,10 @@ export default function ToolConfigTab() {
<Dialog open={!!versionDialog} onOpenChange={() => setVersionDialog(null)}> <Dialog open={!!versionDialog} onOpenChange={() => setVersionDialog(null)}>
<DialogContent className="max-w-sm"> <DialogContent className="max-w-sm">
<DialogHeader> <DialogHeader>
<DialogTitle>选择安装版本</DialogTitle> <DialogTitle>{t('deploy.tool.selectVersion')}</DialogTitle>
<DialogDescription> <DialogDescription>
{versionDialog?.tool.display_name} — 请选择要安装的版本 {versionDialog?.tool.display_name} — 请选择要安装的版本
{versionDialog?.tool.name === 'nodejs' && '(推荐「最新 LTS」由 nvm 自动解析当前 LTS 线)'} {versionDialog?.tool.name === 'nodejs' && t('deploy.toolconfigtab.se0142a')}
</DialogDescription> </DialogDescription>
</DialogHeader> </DialogHeader>
<div className="space-y-4 py-2"> <div className="space-y-4 py-2">
@@ -324,7 +326,7 @@ export default function ToolConfigTab() {
))} ))}
</div> </div>
<div className="flex justify-end gap-2 pt-2 border-t border-[var(--dg-border)]"> <div className="flex justify-end gap-2 pt-2 border-t border-[var(--dg-border)]">
<Button variant="outline" size="sm" onClick={() => setVersionDialog(null)}>取消</Button> <Button variant="outline" size="sm" onClick={() => setVersionDialog(null)}>{t('common.cancel')}</Button>
<Button <Button
size="sm" size="sm"
onClick={() => versionDialog && handleInstall(versionDialog.tool, selectedVersion)} onClick={() => versionDialog && handleInstall(versionDialog.tool, selectedVersion)}
@@ -13,6 +13,7 @@ import { toast } from 'sonner';
import { useConfirm } from '@/components/ui/confirm-dialog'; import { useConfirm } from '@/components/ui/confirm-dialog';
import { deployApi } from '@/api'; import { deployApi } from '@/api';
import type { JsonData } from '@/types/common'; import type { JsonData } from '@/types/common';
import { useTranslation } from 'react-i18next';
interface Group { interface Group {
id: number; name: string; description: string; id: number; name: string; description: string;
@@ -23,6 +24,7 @@ interface GroupMember {
} }
export default function UserGroupsManager({ embedded = false }: { embedded?: boolean }) { export default function UserGroupsManager({ embedded = false }: { embedded?: boolean }) {
const { t } = useTranslation();
const _confirm = useConfirm(); const _confirm = useConfirm();
const [groups, setGroups] = useState<Group[]>([]); const [groups, setGroups] = useState<Group[]>([]);
const [loading, setLoading] = useState(true); const [loading, setLoading] = useState(true);
@@ -41,43 +43,43 @@ export default function UserGroupsManager({ embedded = false }: { embedded?: boo
const loadGroups = async () => { const loadGroups = async () => {
setLoading(true); setLoading(true);
try { const res = await deployApi.getGroups(); setGroups((res as JsonData)?.list || []); } try { const res = await deployApi.getGroups(); setGroups((res as JsonData)?.list || []); }
catch { toast.error('加载失败'); } catch { toast.error(t('common.loadFailed')); }
finally { setLoading(false); } finally { setLoading(false); }
}; };
useEffect(() => { loadGroups(); }, []); useEffect(() => { loadGroups(); }, []);
const handleSave = async () => { const handleSave = async () => {
if (!formName.trim()) { toast.error('请输入组名'); return; } if (!formName.trim()) { toast.error(t('deploy.rbac.groupPlaceholder')); return; }
setSaving(true); setSaving(true);
try { try {
if (editId) await deployApi.updateGroup(editId, { name: formName, description: formDesc }); if (editId) await deployApi.updateGroup(editId, { name: formName, description: formDesc });
else await deployApi.createGroup({ name: formName, description: formDesc }); else await deployApi.createGroup({ name: formName, description: formDesc });
toast.success(editId ? '已更新' : '已创建'); toast.success(editId ? t('deploy.toast.updated') : t('deploy.toast.created'));
setFormOpen(false); loadGroups(); setFormOpen(false); loadGroups();
} catch { toast.error('操作失败'); } } catch { toast.error(t('common.operationFailed')); }
finally { setSaving(false); } finally { setSaving(false); }
}; };
const handleDelete = async (g: Group) => { const handleDelete = async (g: Group) => {
const ok = await _confirm({ title: '删除用户组', description: `确定删除「${g.name}」?所有成员和流水线授权将同时移除。`, variant: 'destructive' }); const ok = await _confirm({ title: t('deploy.rbac.deleteGroup'), description: t('deploy.usergroupsmanager.se76125', { g.name: g.name }), variant: 'destructive' });
if (!ok) return; if (!ok) return;
try { await deployApi.deleteGroup(g.id); toast.success('已删除'); loadGroups(); } try { await deployApi.deleteGroup(g.id); toast.success(t('alert.deleted')); loadGroups(); }
catch { toast.error('删除失败'); } catch { toast.error(t('common.deleteFailed')); }
}; };
const handleAddMember = async (groupId: number) => { const handleAddMember = async (groupId: number) => {
const username = (memberUsers[groupId] || '').trim(); const username = (memberUsers[groupId] || '').trim();
if (!username) { toast.error('输入用户名'); return; } if (!username) { toast.error(t('pipeline.usernamePlaceholder')); return; }
try { await deployApi.addGroupMember(groupId, { username }); toast.success('已添加'); loadGroups(); setMemberUsers(prev => ({ ...prev, [groupId]: '' })); } try { await deployApi.addGroupMember(groupId, { username }); toast.success(t('deploy.toast.added')); loadGroups(); setMemberUsers(prev => ({ ...prev, [groupId]: '' })); }
catch { toast.error('添加失败'); } catch { toast.error(t('deploy.toast.addFailed')); }
}; };
const handleRemoveMember = async (groupId: number, memberId: number, username: string) => { const handleRemoveMember = async (groupId: number, memberId: number, username: string) => {
const ok = await _confirm({ title: '移除成员', description: `确定从组中移除「${username}」?` }); const ok = await _confirm({ title: t('pipeline.removeMember'), description: t('deploy.usergroupsmanager.s9270e4', { username: username }) });
if (!ok) return; if (!ok) return;
try { await deployApi.removeGroupMember(groupId, memberId); toast.success('已移除'); loadGroups(); } try { await deployApi.removeGroupMember(groupId, memberId); toast.success(t('deploy.rbac.removed')); loadGroups(); }
catch { toast.error('移除失败'); } catch { toast.error(t('deploy.rbac.removeFail')); }
}; };
const toggleExpand = (gid: number) => setExpanded(p => ({ ...p, [gid]: !p[gid] })); const toggleExpand = (gid: number) => setExpanded(p => ({ ...p, [gid]: !p[gid] }));
@@ -98,8 +100,8 @@ export default function UserGroupsManager({ embedded = false }: { embedded?: boo
const listBody = !loading && groups.length === 0 ? ( const listBody = !loading && groups.length === 0 ? (
<PageEmpty <PageEmpty
icon={<Users className="h-10 w-10" />} icon={<Users className="h-10 w-10" />}
title="暂无用户组" title=t('deploy.usergroupsmanager.sd1edd8')
description="点击「新建用户组」创建第一个用户组" description=t('deploy.usergroupsmanager.scf9865')
action={( action={(
<Button size="sm" onClick={() => { setEditId(null); setFormName(''); setFormDesc(''); setFormOpen(true); }}> <Button size="sm" onClick={() => { setEditId(null); setFormName(''); setFormDesc(''); setFormOpen(true); }}>
<Plus className="w-4 h-4 mr-1" />新建用户组 <Plus className="w-4 h-4 mr-1" />新建用户组
@@ -115,7 +117,7 @@ export default function UserGroupsManager({ embedded = false }: { embedded?: boo
<Shield className="w-5 h-5 dg-text-blue" /> <Shield className="w-5 h-5 dg-text-blue" />
<div> <div>
<div className="font-medium text-[var(--dg-text-primary)]">{g.name}</div> <div className="font-medium text-[var(--dg-text-primary)]">{g.name}</div>
<div className="text-xs text-[var(--dg-text-secondary)]">{g.description || '暂无描述'} · {(g.members || []).length} 位成员</div> <div className="text-xs text-[var(--dg-text-secondary)]">{g.description || t('pipeline.desc2')} · {(g.members || []).length} 位成员</div>
</div> </div>
</div> </div>
<div className="flex items-center gap-2"> <div className="flex items-center gap-2">
@@ -132,14 +134,14 @@ export default function UserGroupsManager({ embedded = false }: { embedded?: boo
<div className="border-t border-[var(--dg-border)] px-4 py-3 space-y-3"> <div className="border-t border-[var(--dg-border)] px-4 py-3 space-y-3">
{/* Add member */} {/* Add member */}
<div className="flex items-end gap-2"> <div className="flex items-end gap-2">
<div className="flex-1 space-y-1"><Label className="text-xs">添加用户</Label> <div className="flex-1 space-y-1"><Label className="text-xs">{t('system.addUser')}</Label>
<Input value={memberUsers[g.id] || ''} onChange={e => setMemberUsers(prev => ({ ...prev, [g.id]: e.target.value }))} placeholder="输入用户名" className="h-8 text-sm" onKeyDown={e => e.key === 'Enter' && handleAddMember(g.id)} /> <Input value={memberUsers[g.id] || ''} onChange={e => setMemberUsers(prev => ({ ...prev, [g.id]: e.target.value }))} placeholder=t('pipeline.usernamePlaceholder') className="h-8 text-sm" onKeyDown={e => e.key === 'Enter' && handleAddMember(g.id)} />
</div> </div>
<Button size="sm" className="h-8" onClick={() => handleAddMember(g.id)}><UserPlus className="w-3.5 h-3.5 mr-1" />添加</Button> <Button size="sm" className="h-8" onClick={() => handleAddMember(g.id)}><UserPlus className="w-3.5 h-3.5 mr-1" />{t('common.add')}</Button>
</div> </div>
{/* Members list */} {/* Members list */}
{(g.members || []).length === 0 ? ( {(g.members || []).length === 0 ? (
<div className="text-xs text-[var(--dg-text-secondary)] py-2">暂无成员</div> <div className="text-xs text-[var(--dg-text-secondary)] py-2">{t('deploy.rbac.noMembers')}</div>
) : ( ) : (
<div className="flex flex-wrap gap-2"> <div className="flex flex-wrap gap-2">
{(g.members || []).map(m => ( {(g.members || []).map(m => (
@@ -162,14 +164,14 @@ export default function UserGroupsManager({ embedded = false }: { embedded?: boo
const formDialog = ( const formDialog = (
<Dialog open={formOpen} onOpenChange={setFormOpen}> <Dialog open={formOpen} onOpenChange={setFormOpen}>
<DialogContent> <DialogContent>
<DialogHeader><DialogTitle>{editId ? '编辑用户组' : '新建用户组'}</DialogTitle></DialogHeader> <DialogHeader><DialogTitle>{editId ? t('deploy.rbac.groupEditTitle') : t('pipeline.newGroup')}</DialogTitle></DialogHeader>
<div className="space-y-3"> <div className="space-y-3">
<div className="space-y-1"><Label>组名</Label><Input value={formName} onChange={e => setFormName(e.target.value)} placeholder="例如: 后端开发组" /></div> <div className="space-y-1"><Label>{t('monitor.groupName')}</Label><Input value={formName} onChange={e => setFormName(e.target.value)} placeholder=t('deploy.usergroupsmanager.s5a5632') /></div>
<div className="space-y-1"><Label>描述</Label><Input value={formDesc} onChange={e => setFormDesc(e.target.value)} placeholder="可选" /></div> <div className="space-y-1"><Label>{t('common.description')}</Label><Input value={formDesc} onChange={e => setFormDesc(e.target.value)} placeholder=t('common.optional') /></div>
</div> </div>
<div className="flex justify-end gap-2 mt-4 pt-4 border-t"> <div className="flex justify-end gap-2 mt-4 pt-4 border-t">
<Button variant="outline" onClick={() => setFormOpen(false)}>取消</Button> <Button variant="outline" onClick={() => setFormOpen(false)}>{t('common.cancel')}</Button>
<Button onClick={handleSave} disabled={saving}>{saving ? '...' : '保存'}</Button> <Button onClick={handleSave} disabled={saving}>{saving ? '...' : t('common.save')}</Button>
</div> </div>
</DialogContent> </DialogContent>
</Dialog> </Dialog>
@@ -188,15 +190,15 @@ export default function UserGroupsManager({ embedded = false }: { embedded?: boo
return ( return (
<PageShell <PageShell
variant="list" variant="list"
title="应用发布" title=t('menu.deploy')
subtitle="用户组 — 批量授权流水线访问权限" subtitle=t('deploy.usergroupsmanager.sf80ecf')
icon={<Users className="h-5 w-5" />} icon={<Users className="h-5 w-5" />}
loading={loading} loading={loading}
metrics={( metrics={(
<StatStrip <StatStrip
items={[ items={[
{ label: '用户组', value: groups.length, color: 'blue' }, { label: t('pipeline.userGroup'), value: groups.length, color: 'blue' },
{ label: '成员总数', value: memberCount, color: 'purple' }, { label: t('deploy.usergroupsmanager.sdf2b42'), value: memberCount, color: 'purple' },
]} ]}
/> />
)} )}
@@ -13,6 +13,7 @@ import { cn } from '@/lib/utils';
import { useUserStore } from '@/store'; import { useUserStore } from '@/store';
import { pipelineApi } from '@/api'; import { pipelineApi } from '@/api';
import type { JsonData } from '@/types/common'; import type { JsonData } from '@/types/common';
import { useTranslation } from 'react-i18next';
interface WorkspaceTermDialogProps { interface WorkspaceTermDialogProps {
open: boolean; open: boolean;
@@ -30,6 +31,7 @@ export function WorkspaceTermDialog({
runId, runId,
buildNumber, buildNumber,
}: WorkspaceTermDialogProps) { }: WorkspaceTermDialogProps) {
const { t } = useTranslation();
const containerRef = useRef<HTMLDivElement>(null); const containerRef = useRef<HTMLDivElement>(null);
const termRef = useRef<XTerm | null>(null); const termRef = useRef<XTerm | null>(null);
const wsRef = useRef<WebSocket | null>(null); const wsRef = useRef<WebSocket | null>(null);
@@ -102,11 +104,11 @@ export function WorkspaceTermDialog({
ws.onclose = () => { ws.onclose = () => {
setConnected(false); setConnected(false);
term.write('\r\n\x1b[31m[连接已关闭]\x1b[0m\r\n'); term.write(t('deploy.workspacetermdialog.safab20'));
}; };
ws.onerror = () => { ws.onerror = () => {
term.write('\r\n\x1b[31m[连接发生错误]\x1b[0m\r\n'); term.write(t('deploy.workspacetermdialog.sc81077'));
}; };
return () => { return () => {
@@ -159,7 +161,7 @@ export function WorkspaceTermDialog({
style={fullscreen ? { maxWidth: '100vw', width: '100vw', height: '100vh' } : { maxWidth: '900px', width: '90vw' }} style={fullscreen ? { maxWidth: '100vw', width: '100vw', height: '100vh' } : { maxWidth: '900px', width: '90vw' }}
> >
<DialogTitle className="sr-only">Workspace 终端 #{buildNumber}</DialogTitle> <DialogTitle className="sr-only">Workspace 终端 #{buildNumber}</DialogTitle>
<DialogDescription className="sr-only">流水线构建目录终端</DialogDescription> <DialogDescription className="sr-only">{t('deploy.pipeline.buildDir')}</DialogDescription>
<div className="flex items-center justify-between px-4 py-2 border-b border-[var(--dg-border)]"> <div className="flex items-center justify-between px-4 py-2 border-b border-[var(--dg-border)]">
<div className="flex items-center gap-2 text-sm min-w-0"> <div className="flex items-center gap-2 text-sm min-w-0">
<div className={cn('w-2 h-2 rounded-full shrink-0', connected ? 'bg-emerald-400' : 'bg-red-400')} /> <div className={cn('w-2 h-2 rounded-full shrink-0', connected ? 'bg-emerald-400' : 'bg-red-400')} />
@@ -11,6 +11,7 @@ import { toast } from 'sonner';
import { useCredentialDetail } from '@/hooks/api'; import { useCredentialDetail } from '@/hooks/api';
import type { SecretType } from './types'; import type { SecretType } from './types';
import { TYPE_CONFIG, TYPE_BADGE_CLASS } from './constants'; import { TYPE_CONFIG, TYPE_BADGE_CLASS } from './constants';
import { useTranslation } from 'react-i18next';
export interface CredDetailDialogProps { export interface CredDetailDialogProps {
open: boolean; open: boolean;
@@ -20,13 +21,14 @@ export interface CredDetailDialogProps {
// 凭据详情弹窗 // Logan.Li // 凭据详情弹窗 // Logan.Li
export function CredDetailDialog({ open, onClose, credId }: CredDetailDialogProps) { export function CredDetailDialog({ open, onClose, credId }: CredDetailDialogProps) {
const { t } = useTranslation();
const [showMap, setShowMap] = useState<Record<string, boolean>>({}); const [showMap, setShowMap] = useState<Record<string, boolean>>({});
const { data: detail, isLoading: loading } = useCredentialDetail(credId, open); const { data: detail, isLoading: loading } = useCredentialDetail(credId, open);
if (!open || !credId) return null; if (!open || !credId) return null;
const toggleShow = (key: string) => setShowMap(prev => ({ ...prev, [key]: !prev[key] })); const toggleShow = (key: string) => setShowMap(prev => ({ ...prev, [key]: !prev[key] }));
const copyValue = (val: string) => { navigator.clipboard.writeText(val); toast.success('已复制'); }; const copyValue = (val: string) => { navigator.clipboard.writeText(val); toast.success(t('common.copied')); };
const st = detail?.secret_type as SecretType; const st = detail?.secret_type as SecretType;
const cfg = TYPE_CONFIG[st]; const cfg = TYPE_CONFIG[st];
@@ -77,39 +79,39 @@ export function CredDetailDialog({ open, onClose, credId }: CredDetailDialogProp
</DialogTitle> </DialogTitle>
</DialogHeader> </DialogHeader>
{loading ? ( {loading ? (
<div className="text-center py-8 text-[var(--dg-text-muted)]">加载中...</div> <div className="text-center py-8 text-[var(--dg-text-muted)]">{t('common.loading')}</div>
) : detail ? ( ) : detail ? (
<div className="space-y-4"> <div className="space-y-4">
{/* 基本信息 // Logan.Li */} {/* 基本信息 // Logan.Li */}
<div className="grid grid-cols-2 gap-3 text-sm"> <div className="grid grid-cols-2 gap-3 text-sm">
<div><span className="text-[var(--dg-text-muted)]">名称:</span><span className="text-[var(--dg-text-primary)] font-medium">{detailRecord?.name as string}</span></div> <div><span className="text-[var(--dg-text-muted)]">{t('deploy.creddetaildialog.s5b4786')}</span><span className="text-[var(--dg-text-primary)] font-medium">{detailRecord?.name as string}</span></div>
<div><span className="text-[var(--dg-text-muted)]">类型:</span> <div><span className="text-[var(--dg-text-muted)]">{t('deploy.creddetaildialog.se91f5a')}</span>
<Badge variant="outline" className={`text-xs ml-1 ${TYPE_BADGE_CLASS[st] || ''}`}>{cfg?.label || st}</Badge> <Badge variant="outline" className={`text-xs ml-1 ${TYPE_BADGE_CLASS[st] || ''}`}>{cfg?.label || st}</Badge>
</div> </div>
<div><span className="text-[var(--dg-text-muted)]">状态:</span> <div><span className="text-[var(--dg-text-muted)]">{t('approval.detail.statusLabel')}</span>
{detailRecord?.is_active {detailRecord?.is_active
? <Badge className="bg-green-500/20 dg-text-green text-xs ml-1"><CheckCircle2 className="h-3 w-3 mr-0.5" />启用</Badge> ? <Badge className="bg-green-500/20 dg-text-green text-xs ml-1"><CheckCircle2 className="h-3 w-3 mr-0.5" />{t('common.enable')}</Badge>
: <Badge className="bg-red-500/20 dg-text-red text-xs ml-1"><XCircle className="h-3 w-3 mr-0.5" />禁用</Badge>} : <Badge className="bg-red-500/20 dg-text-red text-xs ml-1"><XCircle className="h-3 w-3 mr-0.5" />{t('common.disable')}</Badge>}
{detailRecord?.expires_at && new Date(detailRecord.expires_at as string) < new Date() && ( {detailRecord?.expires_at && new Date(detailRecord.expires_at as string) < new Date() && (
<Badge className="bg-yellow-500/20 dg-text-yellow text-xs ml-1"><AlertTriangle className="h-3 w-3 mr-0.5" />已过期</Badge> <Badge className="bg-yellow-500/20 dg-text-yellow text-xs ml-1"><AlertTriangle className="h-3 w-3 mr-0.5" />{t('monitor.sslExpired')}</Badge>
)} )}
</div> </div>
<div className="col-span-2 cursor-pointer" onClick={() => copyValue((detailRecord?.env_prefix as string) || '')}> <div className="col-span-2 cursor-pointer" onClick={() => copyValue((detailRecord?.env_prefix as string) || '')}>
<span className="text-[var(--dg-text-muted)]">引用ID:</span> <span className="text-[var(--dg-text-muted)]">{t('deploy.cred.refIdLabel')}</span>
<code className="text-[var(--dg-blue)] font-mono text-xs">{detailRecord?.env_prefix as string || '无'}</code> <code className="text-[var(--dg-blue)] font-mono text-xs">{detailRecord?.env_prefix as string || t('common.none')}</code>
<Copy className="h-3 w-3 inline ml-1 text-[var(--dg-text-muted)]" /> <Copy className="h-3 w-3 inline ml-1 text-[var(--dg-text-muted)]" />
</div> </div>
{(detailRecord?.tags as string[])?.length > 0 && ( {(detailRecord?.tags as string[])?.length > 0 && (
<div className="col-span-2"> <div className="col-span-2">
<span className="text-[var(--dg-text-muted)]">标签:</span> <span className="text-[var(--dg-text-muted)]">{t('deploy.creddetaildialog.s1655dd')}</span>
{(detailRecord?.tags as string[]).map((t: string) => ( {(detailRecord?.tags as string[]).map((t: string) => (
<Badge key={t} variant="outline" className="text-xs ml-1 border-[var(--dg-border)]">{t}</Badge> <Badge key={t} variant="outline" className="text-xs ml-1 border-[var(--dg-border)]">{t}</Badge>
))} ))}
</div> </div>
)} )}
<div className="col-span-2"><span className="text-[var(--dg-text-muted)]">描述:</span><span className="text-[var(--dg-text-secondary)]">{(detailRecord?.description as string) || '无'}</span></div> <div className="col-span-2"><span className="text-[var(--dg-text-muted)]">{t('deploy.creddetaildialog.s4a4e3b')}</span><span className="text-[var(--dg-text-secondary)]">{(detailRecord?.description as string) || t('common.none')}</span></div>
<div><span className="text-[var(--dg-text-muted)]">创建:</span><span className="text-[var(--dg-text-secondary)] text-xs">{new Date(detailRecord?.created_at as string).toLocaleString()}</span></div> <div><span className="text-[var(--dg-text-muted)]">{t('deploy.creddetaildialog.s76d768')}</span><span className="text-[var(--dg-text-secondary)] text-xs">{new Date(detailRecord?.created_at as string).toLocaleString()}</span></div>
<div><span className="text-[var(--dg-text-muted)]">更新:</span><span className="text-[var(--dg-text-secondary)] text-xs">{new Date(detailRecord?.updated_at as string).toLocaleString()}</span></div> <div><span className="text-[var(--dg-text-muted)]">{t('deploy.creddetaildialog.s3820b7')}</span><span className="text-[var(--dg-text-secondary)] text-xs">{new Date(detailRecord?.updated_at as string).toLocaleString()}</span></div>
</div> </div>
{/* 密钥数据 // Logan.Li */} {/* 密钥数据 // Logan.Li */}
@@ -118,41 +120,41 @@ export function CredDetailDialog({ open, onClose, credId }: CredDetailDialogProp
<Key className="h-4 w-4 text-yellow-500" />密钥数据 <Key className="h-4 w-4 text-yellow-500" />密钥数据
</div> </div>
<div className="p-3 rounded-md bg-yellow-500/5 border border-yellow-500/20 mb-3"> <div className="p-3 rounded-md bg-yellow-500/5 border border-yellow-500/20 mb-3">
<p className="text-xs dg-text-yellow/80">以下内容包含敏感信息,请妥善保管,不要泄露给他人。</p> <p className="text-xs dg-text-yellow/80">{t('deploy.creddetaildialog.s03b218')}</p>
</div> </div>
{st === 'ssh' && <> {st === 'ssh' && <>
<Field label="SSH 用户" value={content.ssh_user} /> <Field label=t('deploy.creddetaildialog.s2272f5') value={content.ssh_user} />
<Field label="SSH 端口" value={content.ssh_port} /> <Field label=t('deploy.creddetaildialog.s3f284a') value={content.ssh_port} />
<Field label="SSH 密码" value={content.password} sensitive fieldKey="ssh_password" /> <Field label=t('system.sshPassword') value={content.password} sensitive fieldKey="ssh_password" />
<Field label="私钥" value={content.private_key} sensitive fieldKey="ssh_private_key" /> <Field label=t('system.sshPrivateKey') value={content.private_key} sensitive fieldKey="ssh_private_key" />
<Field label="公钥" value={content.public_key} fieldKey="ssh_public_key" /> <Field label=t('system.sshPublicKey') value={content.public_key} fieldKey="ssh_public_key" />
</>} </>}
{st === 'docker' && <> {st === 'docker' && <>
<Field label="Registry 地址" value={content.server} /> <Field label=t('deploy.form.registryAddr') value={content.server} />
<Field label="用户名" value={content.username} /> <Field label=t('login.username') value={content.username} />
<Field label="密码" value={content.password} sensitive fieldKey="docker_password" /> <Field label=t('login.password') value={content.password} sensitive fieldKey="docker_password" />
</>} </>}
{st === 'tls' && <> {st === 'tls' && <>
<Field label="证书" value={content.cert} sensitive fieldKey="tls_cert" /> <Field label=t('deploy.creddetaildialog.sd40b51') value={content.cert} sensitive fieldKey="tls_cert" />
<Field label="私钥" value={content.key} sensitive fieldKey="tls_key" /> <Field label=t('system.sshPrivateKey') value={content.key} sensitive fieldKey="tls_key" />
<Field label="CA 证书" value={content.ca} sensitive fieldKey="tls_ca" /> <Field label=t('deploy.creddetaildialog.sa24356') value={content.ca} sensitive fieldKey="tls_ca" />
</>} </>}
{st === 'aksk' && <> {st === 'aksk' && <>
<Field label="Access Key ID" value={content.access_key} /> <Field label="Access Key ID" value={content.access_key} />
<Field label="Secret Access Key" value={content.secret_key} sensitive fieldKey="aksk_secret_key" /> <Field label="Secret Access Key" value={content.secret_key} sensitive fieldKey="aksk_secret_key" />
</>} </>}
{st === 'database' && <> {st === 'database' && <>
<Field label="数据库类型" value={String(content.db_type || '').toUpperCase()} /> <Field label=t('deploy.creddetaildialog.s84b916') value={String(content.db_type || '').toUpperCase()} />
<Field label="主机" value={content.host} /> <Field label=t('agent.agentHost') value={content.host} />
<Field label="端口" value={content.port} /> <Field label=t('server.csv.port') value={content.port} />
<Field label="数据库名" value={content.db_name} /> <Field label=t('deploy.creddetaildialog.s5ccbbd') value={content.db_name} />
<Field label="用户名" value={content.username} /> <Field label=t('login.username') value={content.username} />
<Field label="密码" value={content.password} sensitive fieldKey="db_password" /> <Field label=t('login.password') value={content.password} sensitive fieldKey="db_password" />
</>} </>}
{st === 'api' && <> {st === 'api' && <>
<Field label="API Key" value={content.api_key} sensitive fieldKey="api_key" /> <Field label="API Key" value={content.api_key} sensitive fieldKey="api_key" />
<Field label="API 端点" value={content.endpoint} /> <Field label=t('deploy.creddetaildialog.s48ec34') value={content.endpoint} />
</>} </>}
{st === 'generic' && <> {st === 'generic' && <>
<Field label="Key" value={content.generic_key} /> <Field label="Key" value={content.generic_key} />
@@ -162,17 +164,17 @@ export function CredDetailDialog({ open, onClose, credId }: CredDetailDialogProp
{/* 引用提示 // Logan.Li */} {/* 引用提示 // Logan.Li */}
<div className="border-t border-[var(--dg-border)] pt-3"> <div className="border-t border-[var(--dg-border)] pt-3">
<div className="text-xs text-[var(--dg-text-muted)] mb-2">在流水线/脚本中引用此凭据:</div> <div className="text-xs text-[var(--dg-text-muted)] mb-2">{t('deploy.cred.refHint')}</div>
<code className="text-xs bg-[var(--dg-bg-tertiary)] px-3 py-1.5 rounded block text-[var(--dg-blue)]"> <code className="text-xs bg-[var(--dg-bg-tertiary)] px-3 py-1.5 rounded block text-[var(--dg-blue)]">
{'${'}{String(detailRecord?.variable_name || String(detailRecord?.name || '').toUpperCase().replace(/[^A-Z0-9]/g, '_'))}{'}'} {'${'}{String(detailRecord?.variable_name || String(detailRecord?.name || '').toUpperCase().replace(/[^A-Z0-9]/g, '_'))}{'}'}
</code> </code>
</div> </div>
</div> </div>
) : ( ) : (
<div className="text-center py-8 text-[var(--dg-text-muted)]">未找到凭据数据</div> <div className="text-center py-8 text-[var(--dg-text-muted)]">{t('deploy.cred.noCredData')}</div>
)} )}
<DialogFooter> <DialogFooter>
<Button variant="outline" onClick={onClose}>关闭</Button> <Button variant="outline" onClick={onClose}>{t('common.close')}</Button>
</DialogFooter> </DialogFooter>
</DialogContent> </DialogContent>
</Dialog> </Dialog>
@@ -9,6 +9,7 @@ import { toast } from 'sonner';
import { credentialApi } from '@/api'; import { credentialApi } from '@/api';
import type { Credential, SecretType } from './types'; import type { Credential, SecretType } from './types';
import { TYPE_CONFIG } from './constants'; import { TYPE_CONFIG } from './constants';
import { useTranslation } from 'react-i18next';
export interface CredFormDialogProps { export interface CredFormDialogProps {
open: boolean; open: boolean;
@@ -19,6 +20,7 @@ export interface CredFormDialogProps {
// 凭据新增/编辑弹窗 // Logan.Li // 凭据新增/编辑弹窗 // Logan.Li
export function CredFormDialog({ open, onClose, onSaved, editData }: CredFormDialogProps) { export function CredFormDialog({ open, onClose, onSaved, editData }: CredFormDialogProps) {
const { t } = useTranslation();
const isEdit = !!editData; const isEdit = !!editData;
const [name, setName] = useState(''); const [name, setName] = useState('');
const [varName, setVarName] = useState(''); const [varName, setVarName] = useState('');
@@ -95,7 +97,7 @@ export function CredFormDialog({ open, onClose, onSaved, editData }: CredFormDia
const toggleShow = (key: string) => setShowMap(prev => ({ ...prev, [key]: !prev[key] })); const toggleShow = (key: string) => setShowMap(prev => ({ ...prev, [key]: !prev[key] }));
const handleSubmit = async () => { const handleSubmit = async () => {
if (!name.trim()) { toast.error('请填写凭据名称'); return; } if (!name.trim()) { toast.error(t('deploy.cred.nameRequired')); return; }
setSubmitting(true); setSubmitting(true);
try { try {
const payload: Record<string, unknown> = { const payload: Record<string, unknown> = {
@@ -141,16 +143,16 @@ export function CredFormDialog({ open, onClose, onSaved, editData }: CredFormDia
if (isEdit) { if (isEdit) {
await credentialApi.update(editData!.id, payload); await credentialApi.update(editData!.id, payload);
toast.success('已更新'); toast.success(t('deploy.toast.updated'));
} else { } else {
await credentialApi.create(payload); await credentialApi.create(payload);
toast.success('已创建'); toast.success(t('deploy.toast.created'));
} }
onSaved(); onSaved();
onClose(); onClose();
} catch (e: unknown) { } catch (e: unknown) {
const err = e as { response?: { data?: { message?: string } } }; const err = e as { response?: { data?: { message?: string } } };
toast.error(err?.response?.data?.message || '操作失败'); toast.error(err?.response?.data?.message || t('common.operationFailed'));
} finally { setSubmitting(false); } } finally { setSubmitting(false); }
}; };
@@ -190,25 +192,25 @@ export function CredFormDialog({ open, onClose, onSaved, editData }: CredFormDia
<DialogHeader> <DialogHeader>
<DialogTitle className="text-[var(--dg-text-primary)] flex items-center gap-2"> <DialogTitle className="text-[var(--dg-text-primary)] flex items-center gap-2">
<TIicon className={`h-5 w-5 ${TI?.color || ''}`} /> <TIicon className={`h-5 w-5 ${TI?.color || ''}`} />
{isEdit ? '编辑凭据' : '新增凭据'} {isEdit ? t('pipeline.editCred') : t('pipeline.addCred')}
</DialogTitle> </DialogTitle>
<DialogDescription className="text-[var(--dg-text-muted)] text-xs"> <DialogDescription className="text-[var(--dg-text-muted)] text-xs">
{TI?.desc || '管理敏感凭据信息'} {TI?.desc || t('deploy.cred.descDefault')}
</DialogDescription> </DialogDescription>
</DialogHeader> </DialogHeader>
<div className="space-y-4 py-2"> <div className="space-y-4 py-2">
{/* 基本信息 // Logan.Li */} {/* 基本信息 // Logan.Li */}
<div className="border-b border-[var(--dg-border)] pb-3"> <div className="border-b border-[var(--dg-border)] pb-3">
<div className="text-xs font-medium text-[var(--dg-text-secondary)] mb-2">基本信息</div> <div className="text-xs font-medium text-[var(--dg-text-secondary)] mb-2">{t('deploy.label.basicInfo')}</div>
<div className="grid grid-cols-2 gap-3"> <div className="grid grid-cols-2 gap-3">
<div className="space-y-1"> <div className="space-y-1">
<Label className="text-[var(--dg-text-secondary)] text-xs">凭据名称 <span className="dg-text-red">*</span></Label> <Label className="text-[var(--dg-text-secondary)] text-xs">{t('pipeline.credName')} <span className="dg-text-red">*</span></Label>
<Input value={name} onChange={e => setName(e.target.value)} placeholder="如:生产环境 SSH" <Input value={name} onChange={e => setName(e.target.value)} placeholder=t('deploy.credformdialog.s97afec')
className="bg-[var(--dg-bg-tertiary)] border-[var(--dg-border)] text-[var(--dg-text-primary)]" /> className="bg-[var(--dg-bg-tertiary)] border-[var(--dg-border)] text-[var(--dg-text-primary)]" />
</div> </div>
<div className="space-y-1"> <div className="space-y-1">
<Label className="text-[var(--dg-text-secondary)] text-xs">变量别名</Label> <Label className="text-[var(--dg-text-secondary)] text-xs">{t('pipeline.varAlias')}</Label>
<Input value={varName} onChange={e => setVarName(e.target.value)} placeholder="如:MYSQL_PROD" <Input value={varName} onChange={e => setVarName(e.target.value)} placeholder=t('deploy.credformdialog.s92c3a5')
className="bg-[var(--dg-bg-tertiary)] border-[var(--dg-border)] text-[var(--dg-text-primary)] font-mono text-sm" /> className="bg-[var(--dg-bg-tertiary)] border-[var(--dg-border)] text-[var(--dg-text-primary)] font-mono text-sm" />
</div> </div>
<div className="space-y-1"> <div className="space-y-1">
@@ -227,14 +229,14 @@ export function CredFormDialog({ open, onClose, onSaved, editData }: CredFormDia
</Select> </Select>
</div> </div>
<div className="space-y-1"> <div className="space-y-1">
<Label className="text-[var(--dg-text-secondary)] text-xs">标签</Label> <Label className="text-[var(--dg-text-secondary)] text-xs">{t('common.tag')}</Label>
<Input value={tags} onChange={e => setTags(e.target.value)} placeholder="生产环境, 阿里云" <Input value={tags} onChange={e => setTags(e.target.value)} placeholder=t('deploy.credformdialog.s29e67e')
className="bg-[var(--dg-bg-tertiary)] border-[var(--dg-border)] text-[var(--dg-text-primary)]" /> className="bg-[var(--dg-bg-tertiary)] border-[var(--dg-border)] text-[var(--dg-text-primary)]" />
</div> </div>
</div> </div>
<div className="mt-2 space-y-1"> <div className="mt-2 space-y-1">
<Label className="text-[var(--dg-text-secondary)] text-xs">描述</Label> <Label className="text-[var(--dg-text-secondary)] text-xs">{t('common.description')}</Label>
<Input value={description} onChange={e => setDescription(e.target.value)} placeholder="可选备注信息" <Input value={description} onChange={e => setDescription(e.target.value)} placeholder=t('deploy.credformdialog.s9216f1')
className="bg-[var(--dg-bg-tertiary)] border-[var(--dg-border)] text-[var(--dg-text-primary)]" /> className="bg-[var(--dg-bg-tertiary)] border-[var(--dg-border)] text-[var(--dg-text-primary)]" />
</div> </div>
</div> </div>
@@ -243,32 +245,32 @@ export function CredFormDialog({ open, onClose, onSaved, editData }: CredFormDia
<div> <div>
<div className="text-xs font-medium text-[var(--dg-text-secondary)] mb-2 flex items-center gap-2"> <div className="text-xs font-medium text-[var(--dg-text-secondary)] mb-2 flex items-center gap-2">
<TIicon className="h-3.5 w-3.5" />{TI?.label || secretType} 配置 <TIicon className="h-3.5 w-3.5" />{TI?.label || secretType} 配置
{isEdit && <span className="text-[var(--dg-text-muted)]">(仅填写需要修改的字段)</span>} {isEdit && <span className="text-[var(--dg-text-muted)]">{t('deploy.credformdialog.s088965')}</span>}
</div> </div>
{secretType === 'ssh' && ( {secretType === 'ssh' && (
<div className="grid grid-cols-2 gap-3"> <div className="grid grid-cols-2 gap-3">
<div className="space-y-1"> <div className="space-y-1">
<Label className="text-[var(--dg-text-secondary)] text-xs">SSH 用户</Label> <Label className="text-[var(--dg-text-secondary)] text-xs">{t('deploy.credformdialog.s2272f5')}</Label>
<Input value={sshUser} onChange={e => setSshUser(e.target.value)} placeholder="root" <Input value={sshUser} onChange={e => setSshUser(e.target.value)} placeholder="root"
className="bg-[var(--dg-bg-tertiary)] border-[var(--dg-border)] text-[var(--dg-text-primary)]" /> className="bg-[var(--dg-bg-tertiary)] border-[var(--dg-border)] text-[var(--dg-text-primary)]" />
</div> </div>
<div className="space-y-1"> <div className="space-y-1">
<Label className="text-[var(--dg-text-secondary)] text-xs">SSH 端口</Label> <Label className="text-[var(--dg-text-secondary)] text-xs">{t('deploy.credformdialog.s3f284a')}</Label>
<Input value={sshPort} onChange={e => setSshPort(e.target.value)} placeholder="22" type="number" <Input value={sshPort} onChange={e => setSshPort(e.target.value)} placeholder="22" type="number"
className="bg-[var(--dg-bg-tertiary)] border-[var(--dg-border)] text-[var(--dg-text-primary)]" /> className="bg-[var(--dg-bg-tertiary)] border-[var(--dg-border)] text-[var(--dg-text-primary)]" />
</div> </div>
<div className="col-span-2"> <div className="col-span-2">
<FieldWithToggle label="SSH 密码" value={sshPassword} onChange={setSshPassword} <FieldWithToggle label=t('system.sshPassword') value={sshPassword} onChange={setSshPassword}
placeholder="密码(或留空用密钥)" fieldKey="ssh_pwd" /> placeholder=t('deploy.credformdialog.se98d4e') fieldKey="ssh_pwd" />
</div> </div>
<div className="col-span-2"> <div className="col-span-2">
<FieldWithToggle label="私钥内容" value={sshPrivateKey} onChange={setSshPrivateKey} <FieldWithToggle label=t('deploy.credformdialog.sfcef97') value={sshPrivateKey} onChange={setSshPrivateKey}
placeholder="粘贴 SSH 私钥..." fieldKey="ssh_pk" isLong /> placeholder=t('deploy.credformdialog.s824277') fieldKey="ssh_pk" isLong />
</div> </div>
<div className="col-span-2"> <div className="col-span-2">
<FieldWithToggle label="公钥内容" value={sshPublicKey} onChange={setSshPublicKey} <FieldWithToggle label=t('deploy.credformdialog.s6fc01d') value={sshPublicKey} onChange={setSshPublicKey}
placeholder="粘贴 SSH 公钥..." fieldKey="ssh_pub" isLong /> placeholder=t('deploy.credformdialog.s5eccd4') fieldKey="ssh_pub" isLong />
</div> </div>
</div> </div>
)} )}
@@ -276,28 +278,28 @@ export function CredFormDialog({ open, onClose, onSaved, editData }: CredFormDia
{secretType === 'docker' && ( {secretType === 'docker' && (
<div className="grid grid-cols-2 gap-3"> <div className="grid grid-cols-2 gap-3">
<div className="col-span-2 space-y-1"> <div className="col-span-2 space-y-1">
<Label className="text-[var(--dg-text-secondary)] text-xs">Registry 地址 <span className="dg-text-red">*</span></Label> <Label className="text-[var(--dg-text-secondary)] text-xs">{t('deploy.form.registryAddr')} <span className="dg-text-red">*</span></Label>
<Input value={dockerServer} onChange={e => setDockerServer(e.target.value)} placeholder="registry.example.com" <Input value={dockerServer} onChange={e => setDockerServer(e.target.value)} placeholder="registry.example.com"
className="bg-[var(--dg-bg-tertiary)] border-[var(--dg-border)] text-[var(--dg-text-primary)] font-mono" /> className="bg-[var(--dg-bg-tertiary)] border-[var(--dg-border)] text-[var(--dg-text-primary)] font-mono" />
</div> </div>
<div className="space-y-1"> <div className="space-y-1">
<Label className="text-[var(--dg-text-secondary)] text-xs">用户名</Label> <Label className="text-[var(--dg-text-secondary)] text-xs">{t('login.username')}</Label>
<Input value={dockerUsername} onChange={e => setDockerUsername(e.target.value)} placeholder="admin" <Input value={dockerUsername} onChange={e => setDockerUsername(e.target.value)} placeholder="admin"
className="bg-[var(--dg-bg-tertiary)] border-[var(--dg-border)] text-[var(--dg-text-primary)]" /> className="bg-[var(--dg-bg-tertiary)] border-[var(--dg-border)] text-[var(--dg-text-primary)]" />
</div> </div>
<div><FieldWithToggle label="密码" value={dockerPassword} onChange={setDockerPassword} <div><FieldWithToggle label=t('login.password') value={dockerPassword} onChange={setDockerPassword}
placeholder="Registry 密码" fieldKey="docker_pwd" required /></div> placeholder=t('deploy.credformdialog.s929297') fieldKey="docker_pwd" required /></div>
</div> </div>
)} )}
{secretType === 'tls' && ( {secretType === 'tls' && (
<div className="space-y-3"> <div className="space-y-3">
<FieldWithToggle label="证书 (PEM)" value={tlsCert} onChange={setTlsCert} <FieldWithToggle label=t('deploy.credformdialog.s3391e4') value={tlsCert} onChange={setTlsCert}
placeholder="-----BEGIN CERTIFICATE-----" fieldKey="tls_cert" isLong required /> placeholder="-----BEGIN CERTIFICATE-----" fieldKey="tls_cert" isLong required />
<FieldWithToggle label="私钥 (PEM)" value={tlsKey} onChange={setTlsKey} <FieldWithToggle label=t('deploy.credformdialog.s517151') value={tlsKey} onChange={setTlsKey}
placeholder="-----BEGIN PRIVATE KEY-----" fieldKey="tls_key" isLong required /> placeholder="-----BEGIN PRIVATE KEY-----" fieldKey="tls_key" isLong required />
<FieldWithToggle label="CA 证书" value={tlsCa} onChange={setTlsCa} <FieldWithToggle label=t('deploy.credformdialog.sa24356') value={tlsCa} onChange={setTlsCa}
placeholder="CA 证书内容..." fieldKey="tls_ca" isLong /> placeholder=t('deploy.credformdialog.s7db02d') fieldKey="tls_ca" isLong />
</div> </div>
)} )}
@@ -310,7 +312,7 @@ export function CredFormDialog({ open, onClose, onSaved, editData }: CredFormDia
</div> </div>
<div className="col-span-2"> <div className="col-span-2">
<FieldWithToggle label="Secret Access Key" value={akskSecretKey} onChange={setAkskSecretKey} <FieldWithToggle label="Secret Access Key" value={akskSecretKey} onChange={setAkskSecretKey}
placeholder="输入 Secret Key" fieldKey="aksk_sk" required /> placeholder=t('deploy.credformdialog.sdef8f6') fieldKey="aksk_sk" required />
</div> </div>
</div> </div>
)} )}
@@ -318,7 +320,7 @@ export function CredFormDialog({ open, onClose, onSaved, editData }: CredFormDia
{secretType === 'database' && ( {secretType === 'database' && (
<div className="grid grid-cols-3 gap-3"> <div className="grid grid-cols-3 gap-3">
<div className="space-y-1"> <div className="space-y-1">
<Label className="text-[var(--dg-text-secondary)] text-xs">数据库类型</Label> <Label className="text-[var(--dg-text-secondary)] text-xs">{t('deploy.credformdialog.s84b916')}</Label>
<Select value={dbType} onValueChange={setDbType}> <Select value={dbType} onValueChange={setDbType}>
<SelectTrigger className="bg-[var(--dg-bg-tertiary)] border-[var(--dg-border)] text-[var(--dg-text-primary)]"> <SelectTrigger className="bg-[var(--dg-bg-tertiary)] border-[var(--dg-border)] text-[var(--dg-text-primary)]">
<SelectValue /> <SelectValue />
@@ -334,34 +336,34 @@ export function CredFormDialog({ open, onClose, onSaved, editData }: CredFormDia
</Select> </Select>
</div> </div>
<div className="space-y-1"> <div className="space-y-1">
<Label className="text-[var(--dg-text-secondary)] text-xs">主机 <span className="dg-text-red">*</span></Label> <Label className="text-[var(--dg-text-secondary)] text-xs">{t('agent.agentHost')} <span className="dg-text-red">*</span></Label>
<Input value={dbHost} onChange={e => setDbHost(e.target.value)} placeholder="10.0.0.1" <Input value={dbHost} onChange={e => setDbHost(e.target.value)} placeholder="10.0.0.1"
className="bg-[var(--dg-bg-tertiary)] border-[var(--dg-border)] text-[var(--dg-text-primary)] font-mono" /> className="bg-[var(--dg-bg-tertiary)] border-[var(--dg-border)] text-[var(--dg-text-primary)] font-mono" />
</div> </div>
<div className="space-y-1"> <div className="space-y-1">
<Label className="text-[var(--dg-text-secondary)] text-xs">端口</Label> <Label className="text-[var(--dg-text-secondary)] text-xs">{t('server.csv.port')}</Label>
<Input value={dbPort} onChange={e => setDbPort(e.target.value)} placeholder="3306" type="number" <Input value={dbPort} onChange={e => setDbPort(e.target.value)} placeholder="3306" type="number"
className="bg-[var(--dg-bg-tertiary)] border-[var(--dg-border)] text-[var(--dg-text-primary)]" /> className="bg-[var(--dg-bg-tertiary)] border-[var(--dg-border)] text-[var(--dg-text-primary)]" />
</div> </div>
<div className="space-y-1"> <div className="space-y-1">
<Label className="text-[var(--dg-text-secondary)] text-xs">数据库名</Label> <Label className="text-[var(--dg-text-secondary)] text-xs">{t('deploy.credformdialog.s5ccbbd')}</Label>
<Input value={dbName} onChange={e => setDbName(e.target.value)} placeholder="aiops" <Input value={dbName} onChange={e => setDbName(e.target.value)} placeholder="aiops"
className="bg-[var(--dg-bg-tertiary)] border-[var(--dg-border)] text-[var(--dg-text-primary)]" /> className="bg-[var(--dg-bg-tertiary)] border-[var(--dg-border)] text-[var(--dg-text-primary)]" />
</div> </div>
<div className="space-y-1"> <div className="space-y-1">
<Label className="text-[var(--dg-text-secondary)] text-xs">用户名</Label> <Label className="text-[var(--dg-text-secondary)] text-xs">{t('login.username')}</Label>
<Input value={dbUsername} onChange={e => setDbUsername(e.target.value)} placeholder="root" <Input value={dbUsername} onChange={e => setDbUsername(e.target.value)} placeholder="root"
className="bg-[var(--dg-bg-tertiary)] border-[var(--dg-border)] text-[var(--dg-text-primary)]" /> className="bg-[var(--dg-bg-tertiary)] border-[var(--dg-border)] text-[var(--dg-text-primary)]" />
</div> </div>
<div><FieldWithToggle label="密码" value={dbPassword} onChange={setDbPassword} <div><FieldWithToggle label=t('login.password') value={dbPassword} onChange={setDbPassword}
placeholder="数据库密码" fieldKey="db_pwd" /></div> placeholder=t('deploy.credformdialog.s58b49c') fieldKey="db_pwd" /></div>
</div> </div>
)} )}
{secretType === 'api' && ( {secretType === 'api' && (
<div className="space-y-3"> <div className="space-y-3">
<div className="space-y-1"> <div className="space-y-1">
<Label className="text-[var(--dg-text-secondary)] text-xs">API 端点</Label> <Label className="text-[var(--dg-text-secondary)] text-xs">{t('deploy.credformdialog.s48ec34')}</Label>
<Input value={apiEndpoint} onChange={e => setApiEndpoint(e.target.value)} placeholder="https://api.example.com" <Input value={apiEndpoint} onChange={e => setApiEndpoint(e.target.value)} placeholder="https://api.example.com"
className="bg-[var(--dg-bg-tertiary)] border-[var(--dg-border)] text-[var(--dg-text-primary)] font-mono" /> className="bg-[var(--dg-bg-tertiary)] border-[var(--dg-border)] text-[var(--dg-text-primary)] font-mono" />
</div> </div>
@@ -378,15 +380,15 @@ export function CredFormDialog({ open, onClose, onSaved, editData }: CredFormDia
className="bg-[var(--dg-bg-tertiary)] border-[var(--dg-border)] text-[var(--dg-text-primary)] font-mono" /> className="bg-[var(--dg-bg-tertiary)] border-[var(--dg-border)] text-[var(--dg-text-primary)] font-mono" />
</div> </div>
<FieldWithToggle label="Value" value={genericValue} onChange={setGenericValue} <FieldWithToggle label="Value" value={genericValue} onChange={setGenericValue}
placeholder="密钥值" fieldKey="generic_val" required /> placeholder=t('deploy.credformdialog.s63ec0a') fieldKey="generic_val" required />
</div> </div>
)} )}
</div> </div>
</div> </div>
<DialogFooter> <DialogFooter>
<Button variant="outline" onClick={onClose}>取消</Button> <Button variant="outline" onClick={onClose}>{t('common.cancel')}</Button>
<Button onClick={handleSubmit} disabled={submitting} className="bg-[var(--dg-blue)] hover:bg-[var(--dg-blue)]/80"> <Button onClick={handleSubmit} disabled={submitting} className="bg-[var(--dg-blue)] hover:bg-[var(--dg-blue)]/80">
{submitting ? '保存中...' : (isEdit ? '更新' : '创建')} {submitting ? i18n.t('k8s.topology.saving') : (isEdit ? i18n.t('common.update') : i18n.t('common.create'))}
</Button> </Button>
</DialogFooter> </DialogFooter>
</DialogContent> </DialogContent>
@@ -4,15 +4,16 @@ import {
Key, Server, Container, Shield, Cloud, Database, FileText, Globe, Key, Server, Container, Shield, Cloud, Database, FileText, Globe,
} from 'lucide-react'; } from 'lucide-react';
import type { SecretType } from './types'; import type { SecretType } from './types';
import i18n from '@/i18n';
export const TYPE_CONFIG: Record<SecretType, { label: string; icon: typeof Key; color: string; desc: string }> = { export const TYPE_CONFIG: Record<SecretType, { label: string; icon: typeof Key; color: string; desc: string }> = {
ssh: { label: 'SSH 密钥', icon: Server, color: 'dg-text-yellow', desc: 'SSH 私钥/公钥/密码' }, ssh: { label: i18n.t('system.sshKey'), icon: Server, color: 'dg-text-yellow', desc: i18n.t('deploy.constants.sedc7f9') },
docker: { label: 'Docker 凭证', icon: Container, color: 'dg-text-cyan', desc: 'Docker Registry 登录凭据' }, docker: { label: i18n.t('pipeline.dockerCred'), icon: Container, color: 'dg-text-cyan', desc: i18n.t('deploy.constants.sbd6cf1') },
tls: { label: 'TLS 证书', icon: Shield, color: 'dg-text-green', desc: 'TLS/SSL 证书与私钥' }, tls: { label: i18n.t('deploy.constants.sfa5a64'), icon: Shield, color: 'dg-text-green', desc: i18n.t('deploy.constants.s43f00c') },
aksk: { label: 'AKSK 密钥', icon: Cloud, color: 'dg-text-purple', desc: '云服务 AccessKey/SecretKey' }, aksk: { label: i18n.t('deploy.constants.sb82698'), icon: Cloud, color: 'dg-text-purple', desc: i18n.t('deploy.constants.s564e98') },
database: { label: '数据库凭证', icon: Database, color: 'dg-text-blue', desc: '数据库连接信息' }, database: { label: i18n.t('system.dbCredential'), icon: Database, color: 'dg-text-blue', desc: i18n.t('deploy.constants.se47498') },
api: { label: 'API 密钥', icon: Globe, color: 'dg-text-orange', desc: 'API Token/Key + 端点' }, api: { label: i18n.t('system.apiKeys'), icon: Globe, color: 'dg-text-orange', desc: i18n.t('deploy.constants.sb3edf0') },
generic: { label: '通用凭证', icon: FileText, color: 'dg-text-secondary', desc: '自定义 Key/Value 键值对' }, generic: { label: i18n.t('deploy.constants.s1d319b'), icon: FileText, color: 'dg-text-secondary', desc: i18n.t('deploy.constants.s51b5b2') },
}; };
export const TYPE_BADGE_CLASS: Record<SecretType, string> = { export const TYPE_BADGE_CLASS: Record<SecretType, string> = {
@@ -1,5 +1,6 @@
import { Badge } from '@/components/ui/badge'; import { Badge } from '@/components/ui/badge';
import { CheckCircle, XCircle, Loader2 } from 'lucide-react'; import { CheckCircle, XCircle, Loader2 } from 'lucide-react';
import i18n from '@/i18n';
// 流水线阶段定义 // Logan.Li // 流水线阶段定义 // Logan.Li
export interface PipelineStage { export interface PipelineStage {
@@ -12,10 +13,10 @@ export interface PipelineStage {
// 流水线模板(新建时快捷选择) // Logan.Li // 流水线模板(新建时快捷选择) // Logan.Li
export const pipelineTemplates = [ export const pipelineTemplates = [
{ id: 'template-1', name: 'Node.js 项目', description: '适用于 Node.js 前端项目', stages: ['代码检出', '依赖安装', '代码检查', '构建打包', '部署'] }, { id: 'template-1', name: i18n.t('deploy.template.nodejs'), description: i18n.t('deploy.template.nodejsDesc'), stages: [i18n.t('pipeline.checkout'), i18n.t('pipeline.depInstall'), i18n.t('pipeline.testDesc'), i18n.t('pipeline.buildDesc'), i18n.t('pipeline.deploy')] },
{ id: 'template-2', name: 'Go 项目', description: '适用于 Go 后端项目', stages: ['代码检出', '单元测试', '构建', '构建镜像', '部署'] }, { id: 'template-2', name: i18n.t('deploy.template.go'), description: i18n.t('deploy.template.goDesc'), stages: [i18n.t('pipeline.checkout'), i18n.t('pipeline.unitTest'), i18n.t('pipeline.build'), i18n.t('deploy.releaseHelpers.pipelineStep.buildImage'), i18n.t('pipeline.deploy')] },
{ id: 'template-3', name: 'Java 项目', description: '适用于 Java Spring Boot 项目', stages: ['代码检出', 'Maven构建', '单元测试', '打包', '部署'] }, { id: 'template-3', name: i18n.t('deploy.template.java'), description: i18n.t('deploy.template.javaDesc'), stages: [i18n.t('pipeline.checkout'), i18n.t('deploy.template.mavenBuild'), i18n.t('pipeline.unitTest'), i18n.t('pipeline.package'), i18n.t('pipeline.deploy')] },
{ id: 'template-4', name: 'Python 项目', description: '适用于 Python 项目', stages: ['代码检出', '依赖安装', '代码检查', '测试', '部署'] }, { id: 'template-4', name: i18n.t('deploy.template.python'), description: i18n.t('deploy.template.pythonDesc'), stages: [i18n.t('pipeline.checkout'), i18n.t('pipeline.depInstall'), i18n.t('pipeline.testDesc'), i18n.t('common.test'), i18n.t('pipeline.deploy')] },
]; ];
// 解析 stages 字段(兼容 JSON 数组 / 逗号分隔字符串) // Logan.Li // 解析 stages 字段(兼容 JSON 数组 / 逗号分隔字符串) // Logan.Li
@@ -84,8 +85,8 @@ export function getStageStatusIcon(status: PipelineStage['status']) {
case 'running': case 'running':
return <Loader2 className="h-4 w-4 dg-text-blue animate-spin" />; return <Loader2 className="h-4 w-4 dg-text-blue animate-spin" />;
case 'skipped': case 'skipped':
return <span className="text-[var(--dg-text-secondary)] text-xs">跳过</span>; return <span className="text-[var(--dg-text-secondary)] text-xs">{i18n.t('deploy.pipelineHelpers.s92636e')}</span>;
default: default:
return <span className="text-[var(--dg-text-secondary)] opacity-60 text-xs">待执行</span>; return <span className="text-[var(--dg-text-secondary)] opacity-60 text-xs">{i18n.t('deploy.status.pending')}</span>;
} }
} }
@@ -8,6 +8,7 @@ import { Search, Server, Network, Loader2, Check } from 'lucide-react';
import { cn } from '@/lib/utils'; import { cn } from '@/lib/utils';
import { serverApi, kubernetesApi } from '@/api'; import { serverApi, kubernetesApi } from '@/api';
import { getPublicApiBase } from '@/utils/request'; import { getPublicApiBase } from '@/utils/request';
import { useTranslation } from 'react-i18next';
export interface DeployTargetValue { export interface DeployTargetValue {
deployTarget: 'ssh' | 'k8s'; deployTarget: 'ssh' | 'k8s';
@@ -49,6 +50,7 @@ interface DeploymentItem {
// 发布目标选择:SSH 关联主机 / K8s 关联 Deployment // Logan.Li // 发布目标选择:SSH 关联主机 / K8s 关联 Deployment // Logan.Li
export function DeployTargetFields({ value, onChange, requireTarget = true }: DeployTargetFieldsProps) { export function DeployTargetFields({ value, onChange, requireTarget = true }: DeployTargetFieldsProps) {
const { t } = useTranslation();
const [servers, setServers] = useState<ServerItem[]>([]); const [servers, setServers] = useState<ServerItem[]>([]);
const [clusters, setClusters] = useState<ClusterItem[]>([]); const [clusters, setClusters] = useState<ClusterItem[]>([]);
const [deployments, setDeployments] = useState<DeploymentItem[]>([]); const [deployments, setDeployments] = useState<DeploymentItem[]>([]);
@@ -148,8 +150,8 @@ export function DeployTargetFields({ value, onChange, requireTarget = true }: De
<div className="space-y-3"> <div className="space-y-3">
<div className="flex gap-1 p-1 rounded-lg bg-[var(--dg-bg-secondary)] border border-[var(--dg-border)]"> <div className="flex gap-1 p-1 rounded-lg bg-[var(--dg-bg-secondary)] border border-[var(--dg-border)]">
{([ {([
{ key: 'ssh' as const, label: '主机发布', icon: Server }, { key: 'ssh' as const, label: t('deploy.deploytargetfields.secf819'), icon: Server },
{ key: 'k8s' as const, label: 'Kubernetes 发布', icon: Network }, { key: 'k8s' as const, label: t('deploy.deploytargetfields.s7ff062'), icon: Network },
]).map((item) => { ]).map((item) => {
const active = value.deployTarget === item.key; const active = value.deployTarget === item.key;
const Icon = item.icon; const Icon = item.icon;
@@ -199,7 +201,7 @@ export function DeployTargetFields({ value, onChange, requireTarget = true }: De
<Input <Input
value={serverSearch} value={serverSearch}
onChange={(e) => setServerSearch(e.target.value)} onChange={(e) => setServerSearch(e.target.value)}
placeholder="搜索主机名或 IP" placeholder=t('deploy.deploytargetfields.sc76249')
className="pl-8 h-8 text-xs dg-input" className="pl-8 h-8 text-xs dg-input"
/> />
</div> </div>
@@ -209,7 +211,7 @@ export function DeployTargetFields({ value, onChange, requireTarget = true }: De
<Loader2 className="h-4 w-4 animate-spin mr-1.5" />加载中 <Loader2 className="h-4 w-4 animate-spin mr-1.5" />加载中
</div> </div>
) : filteredServers.length === 0 ? ( ) : filteredServers.length === 0 ? (
<p className="text-xs text-[var(--dg-text-muted)] text-center py-8">暂无可用主机</p> <p className="text-xs text-[var(--dg-text-muted)] text-center py-8">{t('deploy.deploytargetfields.sb42401')}</p>
) : ( ) : (
<div className="p-1.5 space-y-1"> <div className="p-1.5 space-y-1">
{filteredServers.map((srv) => { {filteredServers.map((srv) => {
@@ -241,10 +243,10 @@ export function DeployTargetFields({ value, onChange, requireTarget = true }: De
</div> </div>
)} )}
</ScrollArea> </ScrollArea>
<p className="text-[10px] text-[var(--dg-text-muted)]">构建完成后 SCP 上传 jar/tar.gz 到远程目录并执行部署命令</p> <p className="text-[10px] text-[var(--dg-text-muted)]">{t('deploy.deploytargetfields.sb2b6db')}</p>
<div className="grid grid-cols-2 gap-2"> <div className="grid grid-cols-2 gap-2">
<div className="space-y-1"> <div className="space-y-1">
<Label className="text-xs">远程目录</Label> <Label className="text-xs">{t('deploy.deploytargetfields.s5ca05a')}</Label>
<Input <Input
value={value.deployRemotePath} value={value.deployRemotePath}
onChange={(e) => onChange({ deployRemotePath: e.target.value })} onChange={(e) => onChange({ deployRemotePath: e.target.value })}
@@ -253,7 +255,7 @@ export function DeployTargetFields({ value, onChange, requireTarget = true }: De
/> />
</div> </div>
<div className="space-y-1"> <div className="space-y-1">
<Label className="text-xs">部署命令</Label> <Label className="text-xs">{t('deploy.deploytargetfields.s65b20b')}</Label>
<Input <Input
value={value.deployScript} value={value.deployScript}
onChange={(e) => onChange({ deployScript: e.target.value })} onChange={(e) => onChange({ deployScript: e.target.value })}
@@ -280,10 +282,10 @@ export function DeployTargetFields({ value, onChange, requireTarget = true }: De
})} })}
> >
<SelectTrigger className="h-8 text-xs dg-input"> <SelectTrigger className="h-8 text-xs dg-input">
<SelectValue placeholder="选择集群" /> <SelectValue placeholder=t('k8s.topology.selectCluster') />
</SelectTrigger> </SelectTrigger>
<SelectContent> <SelectContent>
<SelectItem value="__none">请选择</SelectItem> <SelectItem value="__none">{t('common.selectPlaceholder')}</SelectItem>
{clusters.map((c) => ( {clusters.map((c) => (
<SelectItem key={c.id} value={String(c.id)}>{c.name}</SelectItem> <SelectItem key={c.id} value={String(c.id)}>{c.name}</SelectItem>
))} ))}
@@ -291,11 +293,11 @@ export function DeployTargetFields({ value, onChange, requireTarget = true }: De
</Select> </Select>
</div> </div>
<div className="space-y-1"> <div className="space-y-1">
<Label className="text-xs">已选 Deployment</Label> <Label className="text-xs">{t('deploy.deploytargetfields.s806e4e')}</Label>
<Input <Input
readOnly readOnly
value={value.k8sDeployment ? `${value.k8sNamespace}/${value.k8sDeployment}` : ''} value={value.k8sDeployment ? `${value.k8sNamespace}/${value.k8sDeployment}` : ''}
placeholder="从下方列表选择" placeholder=t('deploy.deploytargetfields.sbb1671')
className="h-8 text-xs dg-input font-mono" className="h-8 text-xs dg-input font-mono"
/> />
</div> </div>
@@ -307,7 +309,7 @@ export function DeployTargetFields({ value, onChange, requireTarget = true }: De
<Input <Input
value={depSearch} value={depSearch}
onChange={(e) => setDepSearch(e.target.value)} onChange={(e) => setDepSearch(e.target.value)}
placeholder="搜索 Deployment 或命名空间" placeholder=t('deploy.deploytargetfields.saa98b2')
className="pl-8 h-8 text-xs dg-input" className="pl-8 h-8 text-xs dg-input"
/> />
</div> </div>
@@ -317,7 +319,7 @@ export function DeployTargetFields({ value, onChange, requireTarget = true }: De
<Loader2 className="h-4 w-4 animate-spin mr-1.5" />加载 Deployment <Loader2 className="h-4 w-4 animate-spin mr-1.5" />加载 Deployment
</div> </div>
) : filteredDeployments.length === 0 ? ( ) : filteredDeployments.length === 0 ? (
<p className="text-xs text-[var(--dg-text-muted)] text-center py-8">暂无 Deployment</p> <p className="text-xs text-[var(--dg-text-muted)] text-center py-8">{t('deploy.deploytargetfields.s5689d3')}</p>
) : ( ) : (
<div className="p-1.5 space-y-1"> <div className="p-1.5 space-y-1">
{filteredDeployments.map((dep) => { {filteredDeployments.map((dep) => {
@@ -348,11 +350,11 @@ export function DeployTargetFields({ value, onChange, requireTarget = true }: De
)} )}
</ScrollArea> </ScrollArea>
<div className="space-y-1"> <div className="space-y-1">
<Label className="text-xs">容器名 <span className="text-[var(--dg-text-muted)]">(多容器时填写)</span></Label> <Label className="text-xs">{t('kubernetes.pod.containerName')} <span className="text-[var(--dg-text-muted)]">{t('deploy.deploytargetfields.s7f5a1e')}</span></Label>
<Input <Input
value={value.k8sContainerName} value={value.k8sContainerName}
onChange={(e) => onChange({ k8sContainerName: e.target.value })} onChange={(e) => onChange({ k8sContainerName: e.target.value })}
placeholder="默认首个容器" placeholder=t('deploy.deploytargetfields.s389076')
className="h-8 text-xs font-mono dg-input" className="h-8 text-xs font-mono dg-input"
/> />
</div> </div>
@@ -13,6 +13,7 @@ import {
import { pipelineApi } from '@/api'; import { pipelineApi } from '@/api';
import { toast } from 'sonner'; import { toast } from 'sonner';
import { fmtDuration, type LogEntry } from './constants'; import { fmtDuration, type LogEntry } from './constants';
import { useTranslation } from 'react-i18next';
interface PipelineRunPanelProps { interface PipelineRunPanelProps {
pipeline: Record<string, unknown>; pipeline: Record<string, unknown>;
@@ -23,6 +24,7 @@ interface PipelineRunPanelProps {
// 流水线队列面板(Jenkins 风格) // Logan.Li // 流水线队列面板(Jenkins 风格) // Logan.Li
function PipelineQueuePanel({ pipeline }: { pipeline: Record<string, unknown> }) { function PipelineQueuePanel({ pipeline }: { pipeline: Record<string, unknown> }) {
const { t } = useTranslation();
const [queue, setQueue] = useState<Record<string, unknown> | null>(null); const [queue, setQueue] = useState<Record<string, unknown> | null>(null);
const [loading, setLoading] = useState(false); const [loading, setLoading] = useState(false);
const code = (pipeline.code || pipeline.id) as string; const code = (pipeline.code || pipeline.id) as string;
@@ -49,10 +51,10 @@ function PipelineQueuePanel({ pipeline }: { pipeline: Record<string, unknown> })
const handleCancel = async (runId: number) => { const handleCancel = async (runId: number) => {
try { try {
await pipelineApi.removeFromQueue(code, runId); await pipelineApi.removeFromQueue(code, runId);
toast.success('已取消'); toast.success(t('deploy.toast.cancelled'));
loadQueue(); loadQueue();
} catch { } catch {
toast.error('取消失败'); toast.error(t('deploy.toast.cancelFailed'));
} }
}; };
@@ -68,7 +70,7 @@ function PipelineQueuePanel({ pipeline }: { pipeline: Record<string, unknown> })
return ( return (
<div className="px-4 py-2 space-y-2"> <div className="px-4 py-2 space-y-2">
<div className="flex items-center gap-2 text-xs"> <div className="flex items-center gap-2 text-xs">
<span className="text-[var(--dg-text-secondary)]">构建执行状态</span> <span className="text-[var(--dg-text-secondary)]">{t('deploy.run.buildStatus')}</span>
<span className="font-bold text-[var(--dg-text-primary)]">{running}/{max}</span> <span className="font-bold text-[var(--dg-text-primary)]">{running}/{max}</span>
{queued > 0 && ( {queued > 0 && (
<span className="text-[var(--dg-text-secondary)] ml-2"> <span className="text-[var(--dg-text-secondary)] ml-2">
@@ -116,6 +118,7 @@ function PipelineQueuePanel({ pipeline }: { pipeline: Record<string, unknown> })
// 展开后的运行列表面板 // Logan.Li // 展开后的运行列表面板 // Logan.Li
export function PipelineRunPanel({ pipeline, pipelineRuns, isLoadingRuns, onStopRun }: PipelineRunPanelProps) { export function PipelineRunPanel({ pipeline, pipelineRuns, isLoadingRuns, onStopRun }: PipelineRunPanelProps) {
const { t } = useTranslation();
const [logOpen, setLogOpen] = useState(false); const [logOpen, setLogOpen] = useState(false);
const [logRun, setLogRun] = useState<Record<string, unknown> | null>(null); const [logRun, setLogRun] = useState<Record<string, unknown> | null>(null);
const [logs, setLogs] = useState<LogEntry[]>([]); const [logs, setLogs] = useState<LogEntry[]>([]);
@@ -141,17 +144,17 @@ export function PipelineRunPanel({ pipeline, pipelineRuns, isLoadingRuns, onStop
<Loader2 className="h-5 w-5 animate-spin text-[var(--dg-text-secondary)]" /> <Loader2 className="h-5 w-5 animate-spin text-[var(--dg-text-secondary)]" />
</div> </div>
) : pipelineRuns.length === 0 ? ( ) : pipelineRuns.length === 0 ? (
<div className="py-6 text-center text-[var(--dg-text-secondary)] text-sm">暂无执行记录</div> <div className="py-6 text-center text-[var(--dg-text-secondary)] text-sm">{t('pipeline.noRecords')}</div>
) : ( ) : (
<table className="w-full text-sm"> <table className="w-full text-sm">
<thead className="border-b border-[var(--dg-border)]"> <thead className="border-b border-[var(--dg-border)]">
<tr className="bg-[var(--dg-bg-tertiary)]"> <tr className="bg-[var(--dg-bg-tertiary)]">
<th className="px-4 py-2 text-left text-xs font-medium text-[var(--dg-text-secondary)]">#</th> <th className="px-4 py-2 text-left text-xs font-medium text-[var(--dg-text-secondary)]">#</th>
<th className="px-4 py-2 text-left text-xs font-medium text-[var(--dg-text-secondary)]">状态</th> <th className="px-4 py-2 text-left text-xs font-medium text-[var(--dg-text-secondary)]">{t('common.status')}</th>
<th className="px-4 py-2 text-left text-xs font-medium text-[var(--dg-text-secondary)]">触发人</th> <th className="px-4 py-2 text-left text-xs font-medium text-[var(--dg-text-secondary)]">{t('pipeline.triggerBy')}</th>
<th className="px-4 py-2 text-left text-xs font-medium text-[var(--dg-text-secondary)]">耗时</th> <th className="px-4 py-2 text-left text-xs font-medium text-[var(--dg-text-secondary)]">{t('common.elapsed')}</th>
<th className="px-4 py-2 text-left text-xs font-medium text-[var(--dg-text-secondary)]">时间</th> <th className="px-4 py-2 text-left text-xs font-medium text-[var(--dg-text-secondary)]">{t('monitor.logTime')}</th>
<th className="px-4 py-2 text-right text-xs font-medium text-[var(--dg-text-secondary)]">操作</th> <th className="px-4 py-2 text-right text-xs font-medium text-[var(--dg-text-secondary)]">{t('common.actions')}</th>
</tr> </tr>
</thead> </thead>
<tbody> <tbody>
@@ -217,7 +220,7 @@ export function PipelineRunPanel({ pipeline, pipelineRuns, isLoadingRuns, onStop
</div> </div>
<div className="bg-[var(--dg-bg-primary)] rounded-md p-3 max-h-[50vh] overflow-y-auto font-mono text-xs"> <div className="bg-[var(--dg-bg-primary)] rounded-md p-3 max-h-[50vh] overflow-y-auto font-mono text-xs">
{logs.length === 0 ? ( {logs.length === 0 ? (
<div className="dg-text-muted py-4 text-center">暂无日志</div> <div className="dg-text-muted py-4 text-center">{t('pipeline.noLog')}</div>
) : ( ) : (
logs.map((l, i) => ( logs.map((l, i) => (
<div key={i} className="flex gap-2 py-0.5"> <div key={i} className="flex gap-2 py-0.5">
@@ -1,4 +1,5 @@
import { import {
import i18n from '@/i18n';
GitBranch, GitBranch,
Box, Box,
CheckCircle, CheckCircle,
@@ -9,12 +10,12 @@ import {
// 流水线阶段定义(固定顺序) // Logan.Li // 流水线阶段定义(固定顺序) // Logan.Li
export const STAGE_DEFS = [ export const STAGE_DEFS = [
{ key: 'checkout', label: '代码检出', icon: GitBranch, color: '#6366F1', order: 1, needs: ['repo'], desc: '从 Git 仓库拉取代码' }, { key: 'checkout', label: i18n.t('pipeline.checkout'), icon: GitBranch, color: '#6366F1', order: 1, needs: ['repo'], desc: i18n.t('deploy.constants.s4769ce') },
{ key: 'build', label: '构建', icon: Box, color: '#F59E0B', order: 2, needs: [], desc: '编译/打包项目' }, { key: 'build', label: i18n.t('pipeline.build'), icon: Box, color: '#F59E0B', order: 2, needs: [], desc: i18n.t('deploy.constants.s3318af') },
{ key: 'test', label: '测试', icon: CheckCircle, color: '#10B981', order: 3, needs: [], desc: '运行单元/集成测试' }, { key: 'test', label: i18n.t('common.test'), icon: CheckCircle, color: '#10B981', order: 3, needs: [], desc: i18n.t('deploy.constants.s350a98') },
{ key: 'image', label: '镜像打包', icon: Container, color: '#06B6D4', order: 4, needs: ['registry'], desc: 'Docker 构建 & 推送' }, { key: 'image', label: i18n.t('deploy.stage.image'), icon: Container, color: '#06B6D4', order: 4, needs: ['registry'], desc: i18n.t('deploy.constants.s98ea11') },
{ key: 'deploy', label: '部署', icon: Rocket, color: '#EF4444', order: 5, needs: [], desc: '部署到目标环境' }, { key: 'deploy', label: i18n.t('pipeline.deploy'), icon: Rocket, color: '#EF4444', order: 5, needs: [], desc: i18n.t('deploy.constants.s45f0eb') },
{ key: 'verify', label: '验证', icon: ShieldCheck, color: '#3B82F6', order: 6, needs: [], desc: '部署后健康检查' }, { key: 'verify', label: i18n.t('common.validate'), icon: ShieldCheck, color: '#3B82F6', order: 6, needs: [], desc: i18n.t('deploy.constants.seb164c') },
].sort((a, b) => a.order - b.order); ].sort((a, b) => a.order - b.order);
// 运行日志条目 // Logan.Li // 运行日志条目 // Logan.Li
@@ -31,7 +32,7 @@ export function fmtDuration(s: number | undefined): string {
if (s < 60) return `${s}s`; if (s < 60) return `${s}s`;
const m = Math.floor(s / 60); const m = Math.floor(s / 60);
const sec = s % 60; const sec = s % 60;
return sec > 0 ? `${m}分${sec}秒` : `${m}分`; return sec > 0 ? i18n.t('deploy.constants.s3ae00c', { m: m, sec: sec }) : i18n.t('deploy.constants.s45c7e1', { m: m });
} }
// 解析 stages 字段 // Logan.Li // 解析 stages 字段 // Logan.Li
@@ -13,8 +13,10 @@ import { kubernetesApi } from '@/api';
import { PageShell } from '@/components/layout/PageShell'; import { PageShell } from '@/components/layout/PageShell';
import { ContentPanel } from '@/components/layout/ContentPanel'; import { ContentPanel } from '@/components/layout/ContentPanel';
import type { JsonData } from '@/types/common'; import type { JsonData } from '@/types/common';
import { useTranslation } from 'react-i18next';
export default function CapacityPage() { export default function CapacityPage() {
const { t } = useTranslation();
const { clusterCode } = useParams<{ clusterCode: string }>(); const { clusterCode } = useParams<{ clusterCode: string }>();
const navigate = useNavigate(); const navigate = useNavigate();
const [loading, setLoading] = useState(false); const [loading, setLoading] = useState(false);
@@ -76,8 +78,8 @@ export default function CapacityPage() {
return ( return (
<PageShell <PageShell
variant="list" variant="list"
title="资源容量分析" title=t('kubernetes.capacitypage.s4e67a9')
subtitle={clusterName ? `${clusterName} · Deployment 资源请求与限制` : 'Deployment 资源请求与限制'} subtitle={clusterName ? t('kubernetes.capacitypage.sd54408', { clusterName: clusterName }) : t('kubernetes.capacitypage.s6a1128')}
icon={<BarChart3 className="h-5 w-5" />} icon={<BarChart3 className="h-5 w-5" />}
actions={( actions={(
<> <>
@@ -88,9 +90,9 @@ export default function CapacityPage() {
</SelectContent> </SelectContent>
</Select> </Select>
<Select value={selectedNs} onValueChange={setSelectedNs}> <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> <SelectContent>
<SelectItem value="all">所有命名空间</SelectItem> <SelectItem value="all">{t('kubernetes.capacitypage.s58173b')}</SelectItem>
{namespaces.map(n => <SelectItem key={n} value={n}>{n}</SelectItem>)} {namespaces.map(n => <SelectItem key={n} value={n}>{n}</SelectItem>)}
</SelectContent> </SelectContent>
</Select> </Select>
@@ -109,9 +111,9 @@ export default function CapacityPage() {
<Table> <Table>
<TableHeader><TableRow className="border-[var(--dg-border)] hover:bg-transparent"> <TableHeader><TableRow className="border-[var(--dg-border)] hover:bg-transparent">
<TableHead className="dg-text-secondary">Deployment</TableHead> <TableHead className="dg-text-secondary">Deployment</TableHead>
<TableHead className="dg-text-secondary">命名空间</TableHead> <TableHead className="dg-text-secondary">{t('k8s.column.namespace')}</TableHead>
<TableHead className="dg-text-secondary">副本</TableHead> <TableHead className="dg-text-secondary">{t('kubernetes.capacitypage.s0428b3')}</TableHead>
<TableHead className="dg-text-secondary">容器</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 Req</TableHead>
<TableHead className="dg-text-secondary"><Cpu className="h-3 w-3 inline mr-1" />CPU Lim</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> <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 { kubernetesApi } from '@/api';
import type { JsonData } from '@/types/common'; import type { JsonData } from '@/types/common';
import { useTranslation } from 'react-i18next';
const CHART_COLORS = ['#3B82F6', '#207060', '#F59E0B', '#EF4444', '#8B5CF6', '#EC4899', '#14B8A6', '#F97316']; const CHART_COLORS = ['#3B82F6', '#207060', '#F59E0B', '#EF4444', '#8B5CF6', '#EC4899', '#14B8A6', '#F97316'];
export default function ClusterComparePage() { export default function ClusterComparePage() {
const { t } = useTranslation();
const navigate = useNavigate(); const navigate = useNavigate();
const [loading, setLoading] = useState(false); const [loading, setLoading] = useState(false);
const [data, setData] = useState<JsonData>(null); const [data, setData] = useState<JsonData>(null);
@@ -42,7 +44,7 @@ export default function ClusterComparePage() {
const res: JsonData = await kubernetesApi.getMultiClusterComparison(); const res: JsonData = await kubernetesApi.getMultiClusterComparison();
setData(res || null); setData(res || null);
} catch (e) { } catch (e) {
setError(e?.message || '加载失败'); setError(e?.message || t('common.loadFailed'));
setData(null); setData(null);
} finally { } finally {
setLoading(false); setLoading(false);
@@ -66,16 +68,16 @@ export default function ClusterComparePage() {
const usageBarData = clusters.map((c: JsonData) => ({ const usageBarData = clusters.map((c: JsonData) => ({
name: c.code || c.name, name: c.code || c.name,
'CPU %': Number((c.cpu_usage || 0).toFixed(1)), '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 ? [ const radarData = clusters.length > 0 ? [
{ metric: '节点数', ...Object.fromEntries(clusters.map((c: JsonData) => [c.code || c.name, c.node_count || 0])) }, { metric: t('kubernetes.cluster.nodeCount'), ...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: t('kubernetes.clustercomparepage.s5fe4af'), ...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: t('kubernetes.clustercomparepage.s7d207a'), ...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: t('kubernetes.clustercomparepage.s020267'), ...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: t('kubernetes.clustercomparepage.s5d9ce3'), ...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.clustercomparepage.sbdb608'), ...Object.fromEntries(clusters.map((c: JsonData) => [c.code || c.name, c.total_cpu_cores || 0])) },
] : []; ] : [];
const nodeRolePie = clusters.flatMap((c: JsonData) => [ const nodeRolePie = clusters.flatMap((c: JsonData) => [
@@ -97,7 +99,7 @@ export default function ClusterComparePage() {
// 格式化同步时间 // 格式化同步时间
const fmtTime = (t: string | null | undefined) => { const fmtTime = (t: string | null | undefined) => {
if (!t) return '从未同步'; if (!t) return t('kubernetes.clustercomparepage.s910982');
try { try {
const d = new Date(t); const d = new Date(t);
return d.toLocaleString('zh-CN', { hour12: false }); return d.toLocaleString('zh-CN', { hour12: false });
@@ -111,8 +113,8 @@ export default function ClusterComparePage() {
<div className="flex items-center gap-3"> <div className="flex items-center gap-3">
<Layers className="h-5 w-5 dg-text-blue" /> <Layers className="h-5 w-5 dg-text-blue" />
<div> <div>
<h1 className="text-lg font-semibold">多集群资源对比看板</h1> <h1 className="text-lg font-semibold">{t('kubernetes.clustercomparepage.s5a25a6')}</h1>
<p className="text-xs dg-text-muted">跨集群资源用量、节点分布、健康状态对比</p> <p className="text-xs dg-text-muted">{t('kubernetes.clustercomparepage.s9807a2')}</p>
</div> </div>
</div> </div>
<div className="flex items-center gap-2"> <div className="flex items-center gap-2">
@@ -139,8 +141,8 @@ export default function ClusterComparePage() {
{/* 概览卡片 */} {/* 概览卡片 */}
<StatStrip <StatStrip
items={[ items={[
{ label: '集群', value: totals.cluster_count || 0, color: 'blue' }, { label: t('kubernetes.clustercomparepage.s85fe50'), value: totals.cluster_count || 0, color: 'blue' },
{ label: '节点', value: totals.node_count || 0, color: 'emerald' }, { label: t('k8s.tab.nodes'), value: totals.node_count || 0, color: 'emerald' },
{ label: 'Pod', value: totals.pod_count || 0, color: 'purple' }, { label: 'Pod', value: totals.pod_count || 0, color: 'purple' },
{ label: 'Deploy', value: totals.deployment_count || 0, color: 'amber' }, { label: 'Deploy', value: totals.deployment_count || 0, color: 'amber' },
{ label: 'Service', value: totals.service_count || 0, color: 'cyan' }, { 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)]"> <Card className="bg-[var(--dg-bg-secondary)]/60 border-[var(--dg-border)]">
<CardContent className="py-12 text-center"> <CardContent className="py-12 text-center">
<Cloud className="h-12 w-12 dg-text-muted mx-auto mb-3" /> <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"> <Link to="/kubernetes" className="inline-block mt-3">
<Button variant="outline" size="sm" className="border-[var(--dg-border)]"> <Button variant="outline" size="sm" className="border-[var(--dg-border)]">
去添加集群 <ChevronRight className="h-3.5 w-3.5 ml-1" /> 去添加集群 <ChevronRight className="h-3.5 w-3.5 ml-1" />
@@ -169,7 +171,7 @@ export default function ClusterComparePage() {
<CardContent className="p-5"> <CardContent className="p-5">
<div className="flex items-center gap-2 mb-4"> <div className="flex items-center gap-2 mb-4">
<Layers className="h-4 w-4 dg-text-blue" /> <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> </div>
<ResponsiveContainer width="100%" height={280}> <ResponsiveContainer width="100%" height={280}>
<BarChart data={resourceBarData} margin={{ top: 5, right: 10, left: -15, bottom: 5 }}> <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 }} /> <YAxis tick={{ fill: '#94a3b8', fontSize: 11 }} />
<Tooltip contentStyle={{ background: '#0f172a', border: '1px solid #334155', borderRadius: 8, fontSize: 12 }} /> <Tooltip contentStyle={{ background: '#0f172a', border: '1px solid #334155', borderRadius: 8, fontSize: 12 }} />
<Legend wrapperStyle={{ fontSize: 11 }} /> <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="Pod" fill={CHART_COLORS[0]} radius={[3, 3, 0, 0]} />
<Bar dataKey="Deployment" fill={CHART_COLORS[2]} 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]} /> <Bar dataKey="Service" fill={CHART_COLORS[5]} radius={[3, 3, 0, 0]} />
@@ -191,7 +193,7 @@ export default function ClusterComparePage() {
<CardContent className="p-5"> <CardContent className="p-5">
<div className="flex items-center gap-2 mb-4"> <div className="flex items-center gap-2 mb-4">
<Activity className="h-4 w-4 dg-text-green" /> <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> </div>
<ResponsiveContainer width="100%" height={280}> <ResponsiveContainer width="100%" height={280}>
<BarChart data={usageBarData} margin={{ top: 5, right: 10, left: -15, bottom: 5 }}> <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 }} /> <Tooltip contentStyle={{ background: '#0f172a', border: '1px solid #334155', borderRadius: 8, fontSize: 12 }} />
<Legend wrapperStyle={{ fontSize: 11 }} /> <Legend wrapperStyle={{ fontSize: 11 }} />
<Bar dataKey="CPU %" fill={CHART_COLORS[0]} radius={[3, 3, 0, 0]} /> <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> </BarChart>
</ResponsiveContainer> </ResponsiveContainer>
</CardContent> </CardContent>
@@ -215,7 +217,7 @@ export default function ClusterComparePage() {
<CardContent className="p-5"> <CardContent className="p-5">
<div className="flex items-center gap-2 mb-4"> <div className="flex items-center gap-2 mb-4">
<TrendingUp className="h-4 w-4 dg-text-purple" /> <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> </div>
<ResponsiveContainer width="100%" height={320}> <ResponsiveContainer width="100%" height={320}>
<RadarChart data={radarData}> <RadarChart data={radarData}>
@@ -242,7 +244,7 @@ export default function ClusterComparePage() {
<CardContent className="p-5"> <CardContent className="p-5">
<div className="flex items-center gap-2 mb-4"> <div className="flex items-center gap-2 mb-4">
<Server className="h-4 w-4 dg-text-yellow" /> <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> </div>
{nodeRolePie.length > 0 ? ( {nodeRolePie.length > 0 ? (
<ResponsiveContainer width="100%" height={320}> <ResponsiveContainer width="100%" height={320}>
@@ -260,7 +262,7 @@ export default function ClusterComparePage() {
</PieChart> </PieChart>
</ResponsiveContainer> </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> </CardContent>
</Card> </Card>
@@ -272,25 +274,25 @@ export default function ClusterComparePage() {
<CardContent className="p-5"> <CardContent className="p-5">
<div className="flex items-center gap-2 mb-4"> <div className="flex items-center gap-2 mb-4">
<HardDrive className="h-4 w-4 dg-text-cyan" /> <HardDrive className="h-4 w-4 dg-text-cyan" />
<h3 className="text-sm font-semibold">详细对比</h3> <h3 className="text-sm font-semibold">{t('kubernetes.clustercomparepage.s3e920c')}</h3>
<span className="text-xs dg-text-muted ml-2">点击行可进入集群概览</span> <span className="text-xs dg-text-muted ml-2">{t('kubernetes.clustercomparepage.sbcb4f0')}</span>
</div> </div>
<div className="overflow-x-auto"> <div className="overflow-x-auto">
<Table> <Table>
<TableHeader> <TableHeader>
<TableRow className="border-[var(--dg-border)] hover:bg-transparent"> <TableRow className="border-[var(--dg-border)] hover:bg-transparent">
<TableHead className="dg-text-secondary">集群</TableHead> <TableHead className="dg-text-secondary">{t('kubernetes.clustercomparepage.s85fe50')}</TableHead>
<TableHead className="dg-text-secondary">状态</TableHead> <TableHead className="dg-text-secondary">{t('common.status')}</TableHead>
<TableHead className="dg-text-secondary text-right">节点</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">Pod</TableHead>
<TableHead className="dg-text-secondary text-right">Deployment</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">Service</TableHead>
<TableHead className="dg-text-secondary text-right">CPU 核数</TableHead> <TableHead className="dg-text-secondary text-right">{t('kubernetes.clustercomparepage.s2e32ab')}</TableHead>
<TableHead className="dg-text-secondary text-right">内存</TableHead> <TableHead className="dg-text-secondary text-right">{t('k8s.pods.memory')}</TableHead>
<TableHead className="dg-text-secondary text-right">CPU 使用率</TableHead> <TableHead className="dg-text-secondary text-right">{t('monitor.hostCpu')}</TableHead>
<TableHead className="dg-text-secondary text-right">内存使用率</TableHead> <TableHead className="dg-text-secondary text-right">{t('monitor.hostMemory')}</TableHead>
<TableHead className="dg-text-secondary">角色</TableHead> <TableHead className="dg-text-secondary">{t('pipeline.role')}</TableHead>
<TableHead className="dg-text-secondary">同步时间</TableHead> <TableHead className="dg-text-secondary">{t('cloud.syncTime')}</TableHead>
</TableRow> </TableRow>
</TableHeader> </TableHeader>
<TableBody> <TableBody>
@@ -305,7 +307,7 @@ export default function ClusterComparePage() {
</TableCell> </TableCell>
<TableCell> <TableCell>
<Badge variant="outline" className={`text-xs ${statusColorMap[c.status] || statusColorMap.error}`}> <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> </Badge>
</TableCell> </TableCell>
<TableCell className="text-right font-mono text-[var(--dg-text-secondary)]">{c.node_count}</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 { ContentPanel } from '@/components/layout/ContentPanel';
import { StatStrip } from '@/components/ui/stat-strip'; import { StatStrip } from '@/components/ui/stat-strip';
import type { JsonData } from '@/types/common'; import type { JsonData } from '@/types/common';
import { useTranslation } from 'react-i18next';
const NAMESPACE_ICON: Record<string, React.ComponentType<Record<string, unknown>>> = { const NAMESPACE_ICON: Record<string, React.ComponentType<Record<string, unknown>>> = {
'kube-system': Server, 'kube-system': Server,
@@ -34,6 +35,7 @@ const NAMESPACE_ICON: Record<string, React.ComponentType<Record<string, unknown>
}; };
export default function ClusterOverviewPage() { export default function ClusterOverviewPage() {
const { t } = useTranslation();
const { clusterCode } = useParams<{ clusterCode: string }>(); const { clusterCode } = useParams<{ clusterCode: string }>();
const navigate = useNavigate(); const navigate = useNavigate();
const { toast } = useToast(); const { toast } = useToast();
@@ -53,7 +55,7 @@ export default function ClusterOverviewPage() {
const current = list.find((c: JsonData) => (c.code || String(c.id)) === clusterCode); const current = list.find((c: JsonData) => (c.code || String(c.id)) === clusterCode);
setClusterInfo(current || null); setClusterInfo(current || null);
if (!current && list.length > 0 && clusterCode) { 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([]); } } catch { setClusters([]); }
}, [clusterCode]); }, [clusterCode]);
@@ -83,15 +85,15 @@ export default function ClusterOverviewPage() {
return ( return (
<PageShell <PageShell
variant="default" variant="default"
title={clusterCode || '集群概览'} title={clusterCode || t('kubernetes.clusteroverviewpage.s066c0a')}
subtitle={clusterInfo?.version ? `集群概览 · Kubernetes ${clusterInfo.version}` : '集群概览'} subtitle={clusterInfo?.version ? t('kubernetes.clusteroverviewpage.s966b2d', { clusterInfo.version: clusterInfo.version }) : t('kubernetes.clusteroverviewpage.s066c0a')}
icon={<Server className="h-5 w-5" />} icon={<Server className="h-5 w-5" />}
metrics={!loading ? ( metrics={!loading ? (
<StatStrip <StatStrip
items={[ items={[
{ label: '节点', value: nodes.length, color: 'blue' }, { label: t('k8s.tab.nodes'), value: nodes.length, color: 'blue' },
{ label: '命名空间', value: namespaces.length, color: 'green' }, { label: t('k8s.column.namespace'), value: namespaces.length, color: 'green' },
{ label: '版本', value: clusterInfo?.version || '-', color: 'muted' }, { label: t('common.version'), value: clusterInfo?.version || '-', color: 'muted' },
]} ]}
/> />
) : undefined} ) : undefined}
@@ -111,21 +113,21 @@ export default function ClusterOverviewPage() {
<Table> <Table>
<TableHeader> <TableHeader>
<TableRow className="border-[var(--dg-border)] hover:bg-transparent"> <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('common.name')}</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)]">状态</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)]">IP</TableHead>
<TableHead className="text-[var(--dg-text-secondary)]">OS</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)]">Kubelet</TableHead>
<TableHead className="text-[var(--dg-text-secondary)]">CPU</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> </TableRow>
</TableHeader> </TableHeader>
<TableBody> <TableBody>
{loading ? ( {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 ? ( ) : 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) => { nodes.map((n: JsonData) => {
const cpuCores = n.cpu || 0; const cpuCores = n.cpu || 0;
@@ -16,8 +16,10 @@ import { DeploymentHpaTab } from './deployment-detail/DeploymentHpaTab';
import { DeploymentPodModals } from './deployment-detail/DeploymentPodModals'; import { DeploymentPodModals } from './deployment-detail/DeploymentPodModals';
import { YamlViewer } from './YamlViewer'; import { YamlViewer } from './YamlViewer';
import type { JsonData } from '@/types/common'; import type { JsonData } from '@/types/common';
import { useTranslation } from 'react-i18next';
export function DeploymentDetail({ clusterCode, namespace, deploymentName, onBack }: DeploymentDetailProps) { export function DeploymentDetail({ clusterCode, namespace, deploymentName, onBack }: DeploymentDetailProps) {
const { t } = useTranslation();
const { toast } = useToast(); const { toast } = useToast();
const confirm = useConfirm(); const confirm = useConfirm();
const [deployment, setDeployment] = useState<JsonData>(null); 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))); setPods(allPods.filter((p: JsonData) => p.namespace === namespace && p.name.startsWith(deploymentName)));
setHpas(allHpas.filter((h: JsonData) => h.target_name === deploymentName && h.namespace === namespace)); setHpas(allHpas.filter((h: JsonData) => h.target_name === deploymentName && h.namespace === namespace));
} catch (e) { } catch (e) {
console.error('加载详情失败:', e); console.error(t('kubernetes.deploymentdetail.sb46ea9'), e);
} finally { } finally {
setLoading(false); setLoading(false);
} }
@@ -74,10 +76,10 @@ export function DeploymentDetail({ clusterCode, namespace, deploymentName, onBac
setActionLoading('scale'); setActionLoading('scale');
try { try {
await kubernetesApi.scaleDeployment(clusterCode, namespace, deploymentName, newReplicas); 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(); loadData();
} catch (e) { } 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(''); } } finally { setActionLoading(''); }
}; };
@@ -85,9 +87,9 @@ export function DeploymentDetail({ clusterCode, namespace, deploymentName, onBac
setActionLoading('restart'); setActionLoading('restart');
try { try {
await kubernetesApi.restartDeployment(clusterCode, namespace, deploymentName); await kubernetesApi.restartDeployment(clusterCode, namespace, deploymentName);
toast({ title: '重启指令已下发', description: 'Deployment 正在滚动重启' }); toast({ title: t('kubernetes.deploymentdetail.s68a700'), description: t('kubernetes.deploymentdetail.sd18761') });
} catch (e) { } 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(''); } } finally { setActionLoading(''); }
}; };
@@ -96,28 +98,28 @@ export function DeploymentDetail({ clusterCode, namespace, deploymentName, onBac
setActionLoading('image'); setActionLoading('image');
try { try {
await kubernetesApi.updateDeploymentImage(clusterCode, namespace, deploymentName, newImage); 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); setShowImageUpdate(false);
loadData(); loadData();
} catch (e) { } 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(''); } } finally { setActionLoading(''); }
}; };
const handleHpaToggle = async (hpa: JsonData) => { const handleHpaToggle = async (hpa: JsonData) => {
const ok = await confirm({ const ok = await confirm({
title: '删除 HPA', title: t('kubernetes.hpa.deleteHpa'),
description: `确定删除 HPA "${hpa.name}"?`, description: t('kubernetes.deploymentdetail.s209f7e', { hpa.name: hpa.name }),
confirmText: '删除', confirmText: t('common.delete'),
variant: 'destructive', variant: 'destructive',
}); });
if (!ok) return; if (!ok) return;
try { try {
await kubernetesApi.deleteHPA(clusterCode, namespace, hpa.name); await kubernetesApi.deleteHPA(clusterCode, namespace, hpa.name);
toast({ title: 'HPA 已删除' }); toast({ title: t('kubernetes.deploymentdetail.s0f958f') });
loadData(); loadData();
} catch (e) { } 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"> <Card className="dg-card">
<CardContent className="p-12 text-center"> <CardContent className="p-12 text-center">
<Loader2 className="h-6 w-6 animate-spin mx-auto dg-text-muted" /> <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> </CardContent>
</Card> </Card>
); );
@@ -138,7 +140,7 @@ export function DeploymentDetail({ clusterCode, namespace, deploymentName, onBac
<CardContent className="p-12 text-center"> <CardContent className="p-12 text-center">
<XCircle className="h-8 w-8 mx-auto dg-text-red" /> <XCircle className="h-8 w-8 mx-auto dg-text-red" />
<p className="dg-text-secondary mt-3">未找到 Deployment: {deploymentName}</p> <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> </CardContent>
</Card> </Card>
); );
@@ -15,6 +15,7 @@ import { saveDeploymentManifest } from './deployment-manifest-save';
import { SchedulingSection, type ScheduleMode } from './deployment-edit-advanced/SchedulingSection'; import { SchedulingSection, type ScheduleMode } from './deployment-edit-advanced/SchedulingSection';
import { DnsHostSection } from './deployment-edit-advanced/DnsHostSection'; import { DnsHostSection } from './deployment-edit-advanced/DnsHostSection';
import type { JsonData } from '@/types/common'; import type { JsonData } from '@/types/common';
import { useTranslation } from 'react-i18next';
interface Props { interface Props {
clusterCode: string; clusterCode: string;
@@ -34,6 +35,7 @@ interface Toleration {
} }
export function DeploymentEditAdvanced({ clusterCode, namespace, deploymentName, manifest, onSaved, onCancel }: Props) { export function DeploymentEditAdvanced({ clusterCode, namespace, deploymentName, manifest, onSaved, onCancel }: Props) {
const { t } = useTranslation();
const { toast } = useToast(); const { toast } = useToast();
const [saving, setSaving] = useState(false); const [saving, setSaving] = useState(false);
const [loading, setLoading] = useState(!manifest); const [loading, setLoading] = useState(!manifest);
@@ -311,10 +313,10 @@ export function DeploymentEditAdvanced({ clusterCode, namespace, deploymentName,
else delete podSpec.dnsConfig; else delete podSpec.dnsConfig;
await saveDeploymentManifest(clusterCode, namespace, deploymentName, base); 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); onSaved(base);
} catch (e) { } 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); } } finally { setSaving(false); }
}; };
@@ -323,7 +325,7 @@ export function DeploymentEditAdvanced({ clusterCode, namespace, deploymentName,
<Card className="dg-card"> <Card className="dg-card">
<CardContent className="p-12 text-center"> <CardContent className="p-12 text-center">
<Loader2 className="h-6 w-6 animate-spin mx-auto dg-text-muted" /> <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> </CardContent>
</Card> </Card>
); );
@@ -364,12 +366,12 @@ export function DeploymentEditAdvanced({ clusterCode, namespace, deploymentName,
{strategyType === 'RollingUpdate' && ( {strategyType === 'RollingUpdate' && (
<div className="grid grid-cols-2 gap-3"> <div className="grid grid-cols-2 gap-3">
<div> <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)} <Input value={maxSurge} onChange={e => setMaxSurge(e.target.value)}
placeholder="25%" className="h-8 mt-1 dg-input text-sm font-mono" /> placeholder="25%" className="h-8 mt-1 dg-input text-sm font-mono" />
</div> </div>
<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)} <Input value={maxUnavailable} onChange={e => setMaxUnavailable(e.target.value)}
placeholder="25%" className="h-8 mt-1 dg-input text-sm font-mono" /> placeholder="25%" className="h-8 mt-1 dg-input text-sm font-mono" />
</div> </div>
@@ -387,12 +389,12 @@ export function DeploymentEditAdvanced({ clusterCode, namespace, deploymentName,
</CardHeader> </CardHeader>
<CardContent className="pt-0 grid grid-cols-2 gap-3"> <CardContent className="pt-0 grid grid-cols-2 gap-3">
<div> <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)} <Input type="number" value={revisionHistoryLimit} onChange={e => setRevisionHistoryLimit(e.target.value)}
className="h-8 mt-1 dg-input text-sm font-mono" /> className="h-8 mt-1 dg-input text-sm font-mono" />
</div> </div>
<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)} <Input type="number" value={progressDeadlineSeconds} onChange={e => setProgressDeadlineSeconds(e.target.value)}
className="h-8 mt-1 dg-input text-sm font-mono" /> className="h-8 mt-1 dg-input text-sm font-mono" />
</div> </div>
@@ -403,7 +405,7 @@ export function DeploymentEditAdvanced({ clusterCode, namespace, deploymentName,
<Card className="dg-card"> <Card className="dg-card">
<CardHeader className="pb-3"> <CardHeader className="pb-3">
<div className="flex items-center justify-between"> <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" <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: '' }])}> onClick={() => setTolerations(prev => [...prev, { key: '', operator: 'Equal', value: '', effect: 'NoSchedule', tolerationSeconds: '' }])}>
<Plus className="h-3 w-3 mr-1" />添加 <Plus className="h-3 w-3 mr-1" />添加
@@ -411,7 +413,7 @@ export function DeploymentEditAdvanced({ clusterCode, namespace, deploymentName,
</div> </div>
</CardHeader> </CardHeader>
<CardContent className="pt-0 space-y-2"> <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) => ( {tolerations.map((t, i) => (
<div key={i} className="grid grid-cols-[1fr_80px_1fr_100px_80px_auto] gap-2 items-center"> <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))} <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" /> 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))} <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"> 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="NoSchedule">NoSchedule</option>
<option value="PreferNoSchedule">PreferNoSchedule</option> <option value="PreferNoSchedule">PreferNoSchedule</option>
<option value="NoExecute">NoExecute</option> <option value="NoExecute">NoExecute</option>
</select> </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))} 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" /> 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))}> <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"> <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}> <Button className="bg-blue-600 hover:bg-blue-700" disabled={saving} onClick={save}>
{saving ? <Loader2 className="h-4 w-4 animate-spin mr-1" /> : <Save className="h-4 w-4 mr-1" />} {saving ? <Loader2 className="h-4 w-4 animate-spin mr-1" /> : <Save className="h-4 w-4 mr-1" />}
保存 保存
@@ -10,6 +10,7 @@ import { Badge } from '@/components/ui/badge';
import { Plus, Trash2, Save, Loader2, Tags, FileText, Hash, Lock } from 'lucide-react'; import { Plus, Trash2, Save, Loader2, Tags, FileText, Hash, Lock } from 'lucide-react';
import { useToast } from '@/hooks/use-toast'; import { useToast } from '@/hooks/use-toast';
import { saveDeploymentManifest } from './deployment-manifest-save'; import { saveDeploymentManifest } from './deployment-manifest-save';
import { useTranslation } from 'react-i18next';
interface DeploymentEditBasicProps { interface DeploymentEditBasicProps {
clusterCode: string; 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) { export function DeploymentEditBasic({ clusterCode, namespace, deploymentName, manifest, onSaved, onCancel, isCreate = false }: DeploymentEditBasicProps) {
const { t } = useTranslation();
const { toast } = useToast(); const { toast } = useToast();
const [saving, setSaving] = useState(false); const [saving, setSaving] = useState(false);
const [loading, setLoading] = useState(!manifest); const [loading, setLoading] = useState(!manifest);
@@ -93,7 +95,7 @@ export function DeploymentEditBasic({ clusterCode, namespace, deploymentName, ma
const merged = { ...kvToObj(prev), ...sel }; const merged = { ...kvToObj(prev), ...sel };
return Object.entries(merged).map(([key, value]) => ({ key, value })); 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 () => { const save = async () => {
@@ -106,7 +108,7 @@ export function DeploymentEditBasic({ clusterCode, namespace, deploymentName, ma
base.metadata = base.metadata || {}; base.metadata = base.metadata || {};
if (isCreate) { if (isCreate) {
const trimmed = resName.trim(); const trimmed = resName.trim();
if (!trimmed) throw new Error('名称不能为空'); if (!trimmed) throw new Error(t('kubernetes.deploymenteditbasic.sdf09ff'));
base.metadata.name = trimmed; base.metadata.name = trimmed;
base.metadata.namespace = namespace; base.metadata.namespace = namespace;
} }
@@ -127,10 +129,10 @@ export function DeploymentEditBasic({ clusterCode, namespace, deploymentName, ma
delete base.spec.template.metadata.labels; delete base.spec.template.metadata.labels;
} }
const savedName = await saveDeploymentManifest(clusterCode, namespace, deploymentName, base); 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); onSaved(base);
} catch (e) { } 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); } } finally { setSaving(false); }
}; };
@@ -139,7 +141,7 @@ export function DeploymentEditBasic({ clusterCode, namespace, deploymentName, ma
<Card className="dg-card"> <Card className="dg-card">
<CardContent className="p-12 text-center"> <CardContent className="p-12 text-center">
<Loader2 className="h-6 w-6 animate-spin mx-auto dg-text-muted" /> <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> </CardContent>
</Card> </Card>
); );
@@ -174,7 +176,7 @@ export function DeploymentEditBasic({ clusterCode, namespace, deploymentName, ma
onChange={e => setReplicas(Math.max(0, Number(e.target.value) || 0))} onChange={e => setReplicas(Math.max(0, Number(e.target.value) || 0))}
className="w-32 dg-input" 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> </div>
</CardContent> </CardContent>
</Card> </Card>
@@ -184,12 +186,12 @@ export function DeploymentEditBasic({ clusterCode, namespace, deploymentName, ma
<CardHeader className="pb-3"> <CardHeader className="pb-3">
<CardTitle className="text-sm text-[var(--dg-text-primary)] flex items-center gap-2"> <CardTitle className="text-sm text-[var(--dg-text-primary)] flex items-center gap-2">
<Lock className="h-4 w-4 dg-text-muted" /> <Lock className="h-4 w-4 dg-text-muted" />
{isCreate ? '基本标识' : '基本标识(只读)'} {isCreate ? t('kubernetes.deploymenteditbasic.sc8de32') : t('kubernetes.deploymenteditbasic.sc4d9eb')}
</CardTitle> </CardTitle>
</CardHeader> </CardHeader>
<CardContent className="pt-0 grid grid-cols-2 gap-4"> <CardContent className="pt-0 grid grid-cols-2 gap-4">
<div> <div>
<Label className="dg-text-secondary text-xs">名称 (name)</Label> <Label className="dg-text-secondary text-xs">{t('kubernetes.deploymenteditbasic.sab7247')}</Label>
<Input <Input
value={isCreate ? resName : deploymentName} value={isCreate ? resName : deploymentName}
readOnly={!isCreate} readOnly={!isCreate}
@@ -198,7 +200,7 @@ export function DeploymentEditBasic({ clusterCode, namespace, deploymentName, ma
/> />
</div> </div>
<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 <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" /> className="mt-1 bg-[var(--dg-bg-primary)] border-[var(--dg-border)] dg-text-muted font-mono text-sm cursor-not-allowed" />
</div> </div>
@@ -220,7 +222,7 @@ export function DeploymentEditBasic({ clusterCode, namespace, deploymentName, ma
</div> </div>
</CardHeader> </CardHeader>
<CardContent className="pt-0 space-y-1.5"> <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) => ( {labels.map((l, i) => (
<div key={i} className="grid grid-cols-[1fr_1.4fr_auto] gap-2"> <div key={i} className="grid grid-cols-[1fr_1.4fr_auto] gap-2">
<Input value={l.key} placeholder="app" <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"> <CardTitle className="text-sm text-[var(--dg-text-primary)] flex items-center gap-2">
<Tags className="h-4 w-4 dg-text-yellow" /> <Tags className="h-4 w-4 dg-text-yellow" />
选择器 (Selector) 选择器 (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> </CardTitle>
<Button size="sm" variant="outline" className="h-7 border-[var(--dg-border)] text-[var(--dg-text-secondary)] text-xs" onClick={addSelector}> <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" />新增 <Plus className="h-3 w-3 mr-1" />新增
@@ -251,8 +253,8 @@ export function DeploymentEditBasic({ clusterCode, namespace, deploymentName, ma
</div> </div>
</CardHeader> </CardHeader>
<CardContent className="pt-0 space-y-1.5"> <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> <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">无选择器</p>} {selectorLabels.length === 0 && <p className="text-[11px] dg-text-muted">{t('kubernetes.service.noSelector')}</p>}
{selectorLabels.map((s, i) => ( {selectorLabels.map((s, i) => (
<div key={i} className="grid grid-cols-[1fr_1.4fr_auto] gap-2"> <div key={i} className="grid grid-cols-[1fr_1.4fr_auto] gap-2">
<Input value={s.key} placeholder="app" <Input value={s.key} placeholder="app"
@@ -287,8 +289,8 @@ export function DeploymentEditBasic({ clusterCode, namespace, deploymentName, ma
</div> </div>
</CardHeader> </CardHeader>
<CardContent className="pt-0 space-y-1.5"> <CardContent className="pt-0 space-y-1.5">
<p className="text-[11px] dg-text-muted mb-1">Pod 模板标签必须包含 Selector 全部键值,否则 Deployment 无法管理 Pod</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">无模板标签</p>} {templateLabels.length === 0 && <p className="text-[11px] dg-text-muted">{t('kubernetes.deploymenteditbasic.se9c9f6')}</p>}
{templateLabels.map((l, i) => ( {templateLabels.map((l, i) => (
<div key={i} className="grid grid-cols-[1fr_1.4fr_auto] gap-2"> <div key={i} className="grid grid-cols-[1fr_1.4fr_auto] gap-2">
<Input value={l.key} placeholder="app" <Input value={l.key} placeholder="app"
@@ -319,7 +321,7 @@ export function DeploymentEditBasic({ clusterCode, namespace, deploymentName, ma
</div> </div>
</CardHeader> </CardHeader>
<CardContent className="pt-0 space-y-1.5"> <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) => ( {annotations.map((a, i) => (
<div key={i} className="grid grid-cols-[1fr_1.4fr_auto] gap-2"> <div key={i} className="grid grid-cols-[1fr_1.4fr_auto] gap-2">
<Input value={a.key} placeholder="deployment.kubernetes.io/revision" <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 等只读字段) 保存将通过 <code className="dg-text-secondary">PUT application/yaml</code> 提交(自动剥离 status/managedFields 等只读字段)
</p> </p>
<div className="flex gap-2"> <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}> <Button className="bg-blue-600 hover:bg-blue-700" disabled={saving} onClick={save}>
{saving ? <Loader2 className="h-4 w-4 animate-spin mr-1" /> : <Save className="h-4 w-4 mr-1" />} {saving ? <Loader2 className="h-4 w-4 animate-spin mr-1" /> : <Save className="h-4 w-4 mr-1" />}
保存 保存
@@ -26,8 +26,10 @@ import {
} from './deployment-edit/container-utils'; } from './deployment-edit/container-utils';
import type { ContainerForm, DeploymentEditContainersProps } from './deployment-edit/types'; import type { ContainerForm, DeploymentEditContainersProps } from './deployment-edit/types';
import type { JsonData } from '@/types/common'; import type { JsonData } from '@/types/common';
import { useTranslation } from 'react-i18next';
export function DeploymentEditContainers({ clusterCode, namespace, deploymentName, manifest, onSaved, onCancel }: DeploymentEditContainersProps) { export function DeploymentEditContainers({ clusterCode, namespace, deploymentName, manifest, onSaved, onCancel }: DeploymentEditContainersProps) {
const { t } = useTranslation();
const { toast } = useToast(); const { toast } = useToast();
const [saving, setSaving] = useState(false); const [saving, setSaving] = useState(false);
const [loading, setLoading] = useState(!manifest); const [loading, setLoading] = useState(!manifest);
@@ -81,11 +83,11 @@ export function DeploymentEditContainers({ clusterCode, namespace, deploymentNam
// validate // validate
for (const c of [...initContainers, ...containers]) { for (const c of [...initContainers, ...containers]) {
if (!c.name.trim()) { if (!c.name.trim()) {
toast({ title: '保存失败', description: '容器名称不能为空', variant: 'destructive' }); toast({ title: t('common.saveFailed'), description: t('kubernetes.deploymenteditcontainers.s14b12c'), variant: 'destructive' });
return; return;
} }
if (!c.image.trim()) { 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; return;
} }
} }
@@ -101,10 +103,10 @@ export function DeploymentEditContainers({ clusterCode, namespace, deploymentNam
? imagePullSecrets.filter(s => s.trim()).map((s: string) => ({ name: s })) ? imagePullSecrets.filter(s => s.trim()).map((s: string) => ({ name: s }))
: undefined; : undefined;
await saveDeploymentManifest(clusterCode, namespace, deploymentName, base); 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); onSaved(base);
} catch (e) { } 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); } } finally { setSaving(false); }
}; };
@@ -113,7 +115,7 @@ export function DeploymentEditContainers({ clusterCode, namespace, deploymentNam
<Card className="dg-card"> <Card className="dg-card">
<CardContent className="p-12 text-center"> <CardContent className="p-12 text-center">
<Loader2 className="h-6 w-6 animate-spin mx-auto dg-text-muted" /> <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> </CardContent>
</Card> </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"> <CardTitle className="text-sm text-[var(--dg-text-primary)] flex items-center gap-2">
<KeyRound className="h-4 w-4 dg-text-yellow" /> <KeyRound className="h-4 w-4 dg-text-yellow" />
镜像拉取凭证 (imagePullSecrets) 镜像拉取凭证 (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> </CardTitle>
</CardHeader> </CardHeader>
<CardContent className="pt-0 space-y-2"> <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> className="dg-text-red hover:dg-text-red ml-1"><Trash2 className="h-3 w-3" /></button>
</div> </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>
<div className="flex gap-2"> <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) => { onKeyDown={(e) => {
if (e.key === 'Enter') { if (e.key === 'Enter') {
const val = (e.target as HTMLInputElement).value.trim(); const val = (e.target as HTMLInputElement).value.trim();
@@ -168,8 +170,8 @@ export function DeploymentEditContainers({ clusterCode, namespace, deploymentNam
{/* 初始化容器 */} {/* 初始化容器 */}
<ContainerGroupSection <ContainerGroupSection
title="初始化容器" title=t('kubernetes.pod.initContainer')
description="在主容器启动前按顺序执行的容器,用于初始化环境" description=t('kubernetes.deploymenteditcontainers.s883e09')
icon={<Play className="h-4 w-4 dg-text-purple" />} icon={<Play className="h-4 w-4 dg-text-purple" />}
containers={initContainers} containers={initContainers}
accentColor="purple" accentColor="purple"
@@ -180,8 +182,8 @@ export function DeploymentEditContainers({ clusterCode, namespace, deploymentNam
{/* 工作容器 */} {/* 工作容器 */}
<ContainerGroupSection <ContainerGroupSection
title="工作容器" title=t('kubernetes.deploymenteditcontainers.sc61b83')
description="Deployment 运行的主容器,定义应用进程及其运行时配置" description=t('kubernetes.deploymenteditcontainers.s43eebd')
icon={<Container className="h-4 w-4 dg-text-blue" />} icon={<Container className="h-4 w-4 dg-text-blue" />}
containers={containers} containers={containers}
accentColor="blue" 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> 个工作容器 <span className="text-[var(--dg-text-secondary)] font-semibold ml-1">{containers.length}</span> 个工作容器
</div> </div>
<div className="flex gap-2"> <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}> <Button className="bg-blue-600 hover:bg-blue-700" disabled={saving} onClick={save}>
{saving ? <Loader2 className="h-4 w-4 animate-spin mr-1" /> : <Save className="h-4 w-4 mr-1" />} {saving ? <Loader2 className="h-4 w-4 animate-spin mr-1" /> : <Save className="h-4 w-4 mr-1" />}
保存 保存
@@ -28,6 +28,7 @@ import { useConfirm } from '@/components/ui/confirm-dialog';
import { kubernetesApi } from '@/api'; import { kubernetesApi } from '@/api';
import { dumpManifest } from './k8s-manifest-utils'; import { dumpManifest } from './k8s-manifest-utils';
import { ResourceVisualEditor } from './ResourceVisualEditor'; import { ResourceVisualEditor } from './ResourceVisualEditor';
import { useTranslation } from 'react-i18next';
interface Props { interface Props {
clusterCode: string; clusterCode: string;
@@ -75,6 +76,7 @@ interface _SvcPortForm {
const toArray = ( v: any) => (Array.isArray(v) ? v : (v?.list || v?.items || v?.data || [])); const toArray = ( v: any) => (Array.isArray(v) ? v : (v?.list || v?.items || v?.data || []));
export function DeploymentEditService({ clusterCode, namespace, deploymentName, manifest, onCancel }: Props) { export function DeploymentEditService({ clusterCode, namespace, deploymentName, manifest, onCancel }: Props) {
const { t } = useTranslation();
const { toast } = useToast(); const { toast } = useToast();
const confirm = useConfirm(); const confirm = useConfirm();
const [loading, setLoading] = useState(true); const [loading, setLoading] = useState(true);
@@ -225,11 +227,11 @@ export function DeploymentEditService({ clusterCode, namespace, deploymentName,
try { try {
const yaml = await dumpManifest(svcManifest); const yaml = await dumpManifest(svcManifest);
await kubernetesApi.applyYAML(clusterCode, yaml); await kubernetesApi.applyYAML(clusterCode, yaml);
toast({ title: 'Service 已创建', description: name }); toast({ title: t('kubernetes.deploymenteditservice.sabd7e0'), description: name });
setShowCreate(null); setShowCreate(null);
load(); load();
} catch (e) { } 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 { try {
const yaml = await dumpManifest(manifest); const yaml = await dumpManifest(manifest);
await kubernetesApi.applyYAML(clusterCode, yaml); await kubernetesApi.applyYAML(clusterCode, yaml);
toast({ title: 'Ingress 已创建', description: name }); toast({ title: t('kubernetes.deploymenteditservice.se356fb'), description: name });
setShowCreate(null); setShowCreate(null);
load(); load();
} catch (e) { } 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 deleteResource = async (kind: 'service' | 'ingress', name: string) => {
const ok = await confirm({ const ok = await confirm({
title: '删除资源', title: t('kubernetes.deploymenteditservice.s8a2a35'),
description: `确认删除 ${kind === 'service' ? 'Service' : 'Ingress'} 「${name}」?此操作不可撤销。`, description: t('kubernetes.deploymenteditservice.s4742c2', { kind === 'service' ? 'Service' : 'Ingress': kind === 'service' ? 'Service' : 'Ingress', name: name }),
confirmText: '删除', confirmText: t('common.delete'),
variant: 'destructive', variant: 'destructive',
}); });
if (!ok) return; if (!ok) return;
try { try {
const resource = kind === 'service' ? 'services' : 'ingresses'; const resource = kind === 'service' ? 'services' : 'ingresses';
await kubernetesApi.deleteResourceYaml(clusterCode, namespace, resource, name); 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(); load();
} catch (e) { } 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"> <Card className="dg-card">
<CardContent className="p-12 text-center"> <CardContent className="p-12 text-center">
<Loader2 className="h-6 w-6 animate-spin mx-auto dg-text-muted" /> <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> </CardContent>
</Card> </Card>
); );
@@ -305,13 +307,13 @@ export function DeploymentEditService({ clusterCode, namespace, deploymentName,
<CardContent className="p-3"> <CardContent className="p-3">
<div className="flex items-center gap-2 text-xs dg-text-secondary"> <div className="flex items-center gap-2 text-xs dg-text-secondary">
<Network className="h-3.5 w-3.5 dg-text-blue" /> <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"> <div className="flex flex-wrap gap-1">
{Object.entries(selectorLabels).map(([k, v]) => ( {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> <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 && ( {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> </div>
<Button size="sm" variant="ghost" className="h-6 ml-auto text-xs dg-text-secondary" onClick={load}> <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 <Plus className="h-3 w-3 mr-1" />创建 Service
</Button> </Button>
</div> </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> </CardHeader>
<CardContent className="pt-0"> <CardContent className="pt-0">
{matchedSvcs.length === 0 && showCreate !== 'service' ? ( {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" />} {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> <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> <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> <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" <Button size="sm" variant="ghost" className="h-6 text-xs dg-text-green"
onClick={() => setVisualEditor({ resource: 'services', name: svc.name })}> onClick={() => setVisualEditor({ resource: 'services', name: svc.name })}>
<Pencil className="h-3 w-3 mr-1" />编辑 <Pencil className="h-3 w-3 mr-1" />编辑
</Button> </Button>
<Button size="sm" variant="ghost" className="h-6 w-6 p-0 dg-text-red hover:dg-text-red" <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" /> <Trash2 className="h-3 w-3" />
</Button> </Button>
</div> </div>
@@ -399,13 +401,13 @@ export function DeploymentEditService({ clusterCode, namespace, deploymentName,
{/* 基本信息 */} {/* 基本信息 */}
<div className="grid grid-cols-2 gap-2"> <div className="grid grid-cols-2 gap-2">
<div> <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 }))} <Input value={svcForm.name} onChange={e => setSvcForm(s => ({ ...s, name: e.target.value }))}
placeholder={`${deploymentName}-svc`} placeholder={`${deploymentName}-svc`}
className="h-7 mt-0.5 dg-input text-[var(--dg-text-secondary)] text-xs font-mono" /> className="h-7 mt-0.5 dg-input text-[var(--dg-text-secondary)] text-xs font-mono" />
</div> </div>
<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 }))} <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"> 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> <option value="ClusterIP">ClusterIP</option>
@@ -416,7 +418,7 @@ export function DeploymentEditService({ clusterCode, namespace, deploymentName,
{/* 快速预设 */} {/* 快速预设 */}
<div> <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"> <div className="flex gap-1.5">
{PORT_PRESETS.map(p => ( {PORT_PRESETS.map(p => (
<button key={p.name} onClick={() => addPort(p)} <button key={p.name} onClick={() => addPort(p)}
@@ -477,19 +479,19 @@ export function DeploymentEditService({ clusterCode, namespace, deploymentName,
{/* Selector 预览 */} {/* Selector 预览 */}
<div className="text-[10px] dg-text-muted border-t border-[var(--dg-border)]/50 pt-2"> <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.keys(selectorLabels).length > 0 ? (
Object.entries(selectorLabels).map(([k, v]) => ( 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> <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>
<div className="flex justify-end gap-2 pt-1"> <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" 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}>创建</Button> <Button size="sm" className="h-7 bg-blue-600 hover:bg-blue-700 text-xs" onClick={createService}>{t('common.create')}</Button>
</div> </div>
</div> </div>
)} )}
@@ -513,7 +515,7 @@ export function DeploymentEditService({ clusterCode, namespace, deploymentName,
<Plus className="h-3 w-3 mr-1" />创建 Ingress <Plus className="h-3 w-3 mr-1" />创建 Ingress
</Button> </Button>
</div> </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> </CardHeader>
<CardContent className="pt-0"> <CardContent className="pt-0">
{ingresses.length === 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" />} {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> <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> <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" <Button size="sm" variant="ghost" className="h-6 text-xs dg-text-green ml-auto"
onClick={() => setVisualEditor({ resource: 'ingresses', name: ing.name })}> onClick={() => setVisualEditor({ resource: 'ingresses', name: ing.name })}>
<Pencil className="h-3 w-3 mr-1" />编辑 <Pencil className="h-3 w-3 mr-1" />编辑
</Button> </Button>
<Button size="sm" variant="ghost" className="h-6 w-6 p-0 dg-text-red hover:dg-text-red" <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" /> <Trash2 className="h-3 w-3" />
</Button> </Button>
</div> </div>
@@ -569,7 +571,7 @@ export function DeploymentEditService({ clusterCode, namespace, deploymentName,
</div> </div>
<div className="grid grid-cols-2 gap-2"> <div className="grid grid-cols-2 gap-2">
<div> <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 }))} <Input value={ingForm.name} onChange={e => setIngForm(s => ({ ...s, name: e.target.value }))}
placeholder={`${deploymentName}-ingress`} placeholder={`${deploymentName}-ingress`}
className="h-7 mt-0.5 dg-input text-[var(--dg-text-secondary)] text-xs font-mono" /> 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" /> className="h-7 mt-0.5 dg-input text-[var(--dg-text-secondary)] text-xs font-mono" />
</div> </div>
<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 }))} <Input value={ingForm.host} onChange={e => setIngForm(s => ({ ...s, host: e.target.value }))}
placeholder="app.example.com" placeholder="app.example.com"
className="h-7 mt-0.5 dg-input text-[var(--dg-text-secondary)] text-xs font-mono" /> 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" /> className="h-7 mt-0.5 dg-input text-[var(--dg-text-secondary)] text-xs font-mono" />
</div> </div>
<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 }))} <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" /> className="h-7 mt-0.5 dg-input text-[var(--dg-text-secondary)] text-xs font-mono" />
</div> </div>
</div> </div>
<div className="flex justify-end gap-2 pt-1"> <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" 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}>创建</Button> <Button size="sm" className="h-7 bg-purple-600 hover:bg-purple-700 text-xs" onClick={createIngress}>{t('common.create')}</Button>
</div> </div>
</div> </div>
)} )}
@@ -619,7 +621,7 @@ export function DeploymentEditService({ clusterCode, namespace, deploymentName,
)} )}
<div className="flex justify-end gap-2 pt-2"> <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>
</div> </div>
); );
@@ -28,6 +28,8 @@ import {
emptyMountRow, emptyMountRow,
} from './deployment-volume-utils'; } from './deployment-volume-utils';
import type { JsonData } from '@/types/common'; import type { JsonData } from '@/types/common';
import { useTranslation } from 'react-i18next';
import i18n from '@/i18n';
interface Props { interface Props {
clusterCode: string; clusterCode: string;
@@ -39,12 +41,12 @@ interface Props {
} }
const VOLUME_TYPES: { key: VolumeForm['type']; label: string; icon: typeof HardDrive; color: string }[] = [ const VOLUME_TYPES: { key: VolumeForm['type']; label: string; icon: typeof HardDrive; color: string }[] = [
{ key: 'persistentVolumeClaim', label: '存储卷声明', icon: Database, color: 'dg-text-green' }, { key: 'persistentVolumeClaim', label: i18n.t('kubernetes.deploymenteditstorage.s18c900'), icon: Database, color: 'dg-text-green' },
{ key: 'emptyDir', label: '临时目录(EmptyDir)', icon: Disc, color: 'dg-text-secondary' }, { 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: 'hostPath', label: 'HostPath', icon: HardDrive, color: 'dg-text-yellow' },
{ key: 'nfs', label: 'NFS', icon: Server, color: 'dg-text-purple' }, { key: 'nfs', label: 'NFS', icon: Server, color: 'dg-text-purple' },
{ key: 'configMap', label: '配置字典', icon: File, color: 'dg-text-blue' }, { key: 'configMap', label: i18n.t('kubernetes.deploymenteditstorage.s0986a6'), icon: File, color: 'dg-text-blue' },
{ key: 'secret', label: '密文', icon: Lock, color: 'text-rose-400' }, { 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)); 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'; type CreateResourceKind = 'configmaps' | 'secrets' | 'pvcs';
export function DeploymentEditStorage({ clusterCode, namespace, deploymentName, manifest, onSaved, onCancel }: Props) { export function DeploymentEditStorage({ clusterCode, namespace, deploymentName, manifest, onSaved, onCancel }: Props) {
const { t } = useTranslation();
const { toast } = useToast(); const { toast } = useToast();
const [saving, setSaving] = useState(false); const [saving, setSaving] = useState(false);
const [loading, setLoading] = useState(!manifest); const [loading, setLoading] = useState(!manifest);
@@ -128,20 +131,20 @@ export function DeploymentEditStorage({ clusterCode, namespace, deploymentName,
const save = async () => { const save = async () => {
for (const entry of entries) { for (const entry of entries) {
if (!entry.volume.name.trim()) { if (!entry.volume.name.trim()) {
toast({ title: '请填写数据卷名称', variant: 'destructive' }); toast({ title: t('kubernetes.deploymenteditstorage.s5b59d2'), variant: 'destructive' });
return; return;
} }
if (!formToVolume(entry.volume)) { if (!formToVolume(entry.volume)) {
const hint = entry.volume.type === 'configMap' ? '请选择 ConfigMap' const hint = entry.volume.type === 'configMap' ? t('kubernetes.deploymenteditstorage.s2a6856')
: entry.volume.type === 'secret' ? '请选择 Secret' : entry.volume.type === 'secret' ? t('kubernetes.deploymenteditstorage.s1f31e4')
: entry.volume.type === 'persistentVolumeClaim' ? '请选择 PVC' : entry.volume.type === 'persistentVolumeClaim' ? t('kubernetes.deploymenteditstorage.sba9fc6')
: '的类型必填项'; : t('kubernetes.deploymenteditstorage.s03480a');
toast({ title: '数据卷配置不完整', description: `请为「${entry.volume.name}」${hint}`, variant: 'destructive' }); toast({ title: t('kubernetes.deploymenteditstorage.se542a6'), description: t('kubernetes.deploymenteditstorage.s3152b4', { entry.volume.name: entry.volume.name, hint: hint }), variant: 'destructive' });
return; return;
} }
const validMounts = entry.mounts.filter((m) => m.mountPath.trim()); const validMounts = entry.mounts.filter((m) => m.mountPath.trim());
if (validMounts.length === 0) { 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; return;
} }
} }
@@ -150,10 +153,10 @@ export function DeploymentEditStorage({ clusterCode, namespace, deploymentName,
const { volumes, mounts } = volumeEntriesToStorage(entries); const { volumes, mounts } = volumeEntriesToStorage(entries);
const base = applyStorageToManifest(rawManifest, volumes, mounts, passthroughVolumes); const base = applyStorageToManifest(rawManifest, volumes, mounts, passthroughVolumes);
await saveDeploymentManifest(clusterCode, namespace, deploymentName, base); 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); onSaved(base);
} catch (e) { } 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); } } finally { setSaving(false); }
}; };
@@ -162,7 +165,7 @@ export function DeploymentEditStorage({ clusterCode, namespace, deploymentName,
<Card className="dg-card"> <Card className="dg-card">
<CardContent className="p-12 text-center"> <CardContent className="p-12 text-center">
<Loader2 className="h-6 w-6 animate-spin mx-auto dg-text-muted" /> <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> </CardContent>
</Card> </Card>
); );
@@ -171,7 +174,7 @@ export function DeploymentEditStorage({ clusterCode, namespace, deploymentName,
if (!manifest) { if (!manifest) {
return ( return (
<Card className="dg-card"> <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> </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> <Badge variant="outline" className="border-[var(--dg-border)] dg-text-secondary">{entries.length}</Badge>
</CardTitle> </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> </div>
<Button size="sm" variant="outline" className="h-7 border-[var(--dg-border)] text-[var(--dg-text-secondary)] text-xs shrink-0" onClick={addEntry}> <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" />添加数据卷 <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="p-3 space-y-2.5 border-b border-[var(--dg-border)]/80">
<div className="flex items-center gap-2 flex-wrap"> <div className="flex items-center gap-2 flex-wrap">
<VIcon className={`h-4 w-4 ${vtype?.color || 'dg-text-secondary'}`} /> <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 <Input
value={vol.name} value={vol.name}
onChange={(e) => { onChange={(e) => {
@@ -233,7 +236,7 @@ export function DeploymentEditStorage({ clusterCode, namespace, deploymentName,
if (vol.type === 'persistentVolumeClaim' && !vol.pvcName) patch.pvcName = name; if (vol.type === 'persistentVolumeClaim' && !vol.pvcName) patch.pvcName = name;
updateVolume(i, patch); 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" className="h-8 w-44 dg-input text-sm font-mono"
/> />
{/* 原生 select,避免 Radix Select 在 overflow 容器内无法下拉 // Logan.Li */} {/* 原生 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 })} 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" 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>)} {containers.map((cn) => <option key={cn} value={cn}>{cn}</option>)}
</select> </select>
<div className="flex items-center gap-1 bg-[var(--dg-bg-tertiary)] rounded-lg p-0.5 border border-[var(--dg-border)]"> <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 <Input
value={mount.mountPath} value={mount.mountPath}
onChange={(e) => updateMount(i, mi, { mountPath: e.target.value })} 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" className="h-8 flex-1 min-w-[200px] dg-input text-sm font-mono"
/> />
{entry.mounts.length > 1 && ( {entry.mounts.length > 1 && (
@@ -321,11 +324,11 @@ export function DeploymentEditStorage({ clusterCode, namespace, deploymentName,
)} )}
</div> </div>
<div className="flex items-center gap-2"> <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 <Input
value={mount.subPath} value={mount.subPath}
onChange={(e) => updateMount(i, mi, { subPath: e.target.value })} 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" className="h-7 flex-1 max-w-md dg-input text-[var(--dg-text-secondary)] text-xs font-mono"
/> />
</div> </div>
@@ -339,7 +342,7 @@ export function DeploymentEditStorage({ clusterCode, namespace, deploymentName,
</Card> </Card>
<div className="flex justify-end gap-2 pt-2"> <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}> <Button className="bg-blue-600 hover:bg-blue-700" disabled={saving} onClick={save}>
{saving ? <Loader2 className="h-4 w-4 animate-spin mr-1" /> : <Save className="h-4 w-4 mr-1" />} {saving ? <Loader2 className="h-4 w-4 animate-spin mr-1" /> : <Save className="h-4 w-4 mr-1" />}
保存 保存
@@ -25,8 +25,10 @@ import type { DeploymentViewProps, SvcItem, IngItem, EventItem } from './deploym
export type { DeploymentViewProps } from './deployment-view/types'; export type { DeploymentViewProps } from './deployment-view/types';
import type { JsonData } from '@/types/common'; import type { JsonData } from '@/types/common';
import { useTranslation } from 'react-i18next';
export function DeploymentView(props: DeploymentViewProps) { export function DeploymentView(props: DeploymentViewProps) {
const { t } = useTranslation();
const { clusterCode, namespace, deployment, pods, revisions, onRefresh } = props; const { clusterCode, namespace, deployment, pods, revisions, onRefresh } = props;
const { toast } = useToast(); const { toast } = useToast();
const confirm = useConfirm(); const confirm = useConfirm();
@@ -138,19 +140,19 @@ export function DeploymentView(props: DeploymentViewProps) {
const handleRollback = async (rev: JsonData) => { const handleRollback = async (rev: JsonData) => {
const revision = rev.revision ?? rev.revision_number ?? rev.number; const revision = rev.revision ?? rev.revision_number ?? rev.number;
const ok = await confirm({ const ok = await confirm({
title: '回滚版本', title: t('kubernetes.deploymentview.s6a374e'),
description: `确认回滚到修订版本 #${revision}?`, description: t('kubernetes.deploymentview.s01eec9', { revision: revision }),
confirmText: '回滚', confirmText: t('common.rollback'),
variant: 'destructive', variant: 'destructive',
}); });
if (!ok) return; if (!ok) return;
setRollbackLoading(revision); setRollbackLoading(revision);
try { try {
await kubernetesApi.rollbackDeployment(clusterCode, namespace, deployment.name, Number(revision)); 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(); onRefresh();
} catch (e) { } 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); } } finally { setRollbackLoading(null); }
}; };
@@ -159,19 +161,19 @@ export function DeploymentView(props: DeploymentViewProps) {
setScaleLoading(true); setScaleLoading(true);
try { try {
await kubernetesApi.scaleDeployment(clusterCode, namespace, deployment.name, scaleValue); 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(); onRefresh();
} catch (e) { } 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); } } finally { setScaleLoading(false); }
}; };
const TABS = [ const TABS = [
{ key: 'pods', label: '容器组', icon: Container, count: pods.length }, { key: 'pods', label: t('kubernetes.deploymentview.s479692'), icon: Container, count: pods.length },
{ key: 'services', label: '访问方式', icon: Network, count: services.length }, { key: 'services', label: t('kubernetes.deploymentview.s706804'), icon: Network, count: services.length },
{ key: 'events', label: '事件', icon: Activity, count: events.length }, { key: 'events', label: t('menu.events'), icon: Activity, count: events.length },
{ key: 'scale', label: '容器伸缩', icon: Plus }, { key: 'scale', label: t('kubernetes.deploymentview.s3b291d'), icon: Plus },
{ key: 'history', label: '历史版本', icon: History, count: revisions.length }, { key: 'history', label: t('kubernetes.deployment.revisions'), icon: History, count: revisions.length },
]; ];
return ( return (
@@ -180,24 +182,24 @@ export function DeploymentView(props: DeploymentViewProps) {
<Card className="dg-card"> <Card className="dg-card">
<CardContent className="p-4"> <CardContent className="p-4">
<div className="grid grid-cols-2 md:grid-cols-3 lg:grid-cols-6 gap-3 text-sm"> <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` }}> <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'} {isHealthy ? 'Running' : 'Updating'}
</Badge> </Badge>
} /> } />
<InfoItem label="副本" value={<span className="font-mono">{ready}/{total}</span>} /> <InfoItem label=t('kubernetes.deploymentview.s0428b3') value={<span className="font-mono">{ready}/{total}</span>} />
<InfoItem label="策略" value={deployment?.strategy || 'RollingUpdate'} /> <InfoItem label=t('kubernetes.deploymentview.s669145') value={deployment?.strategy || 'RollingUpdate'} />
{pods[0] && ( {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')}> <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 || '-'} {pods[0].node_name || pods[0].node || '-'}
</button> </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> </div>
{pods.length === 1 && ( {pods.length === 1 && (
<div className="mt-3 pt-3 border-t border-[var(--dg-border)]"> <div className="mt-3 pt-3 border-t border-[var(--dg-border)]">
@@ -243,7 +245,7 @@ export function DeploymentView(props: DeploymentViewProps) {
{scaleValue !== total && ( {scaleValue !== total && (
<Button size="sm" className="h-7 text-xs bg-[var(--dg-blue)] hover:bg-[var(--dg-blue-hover)]" <Button size="sm" className="h-7 text-xs bg-[var(--dg-blue)] hover:bg-[var(--dg-blue-hover)]"
disabled={scaleLoading} onClick={handleScale}> 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> </Button>
)} )}
</div> </div>
@@ -40,10 +40,12 @@ import { CREATE_DEPLOYMENT_SLUG, isCreateDeployment } from './deployment-constan
import { extractContainers } from './deployment-detail/helpers'; import { extractContainers } from './deployment-detail/helpers';
import { PageShell } from '@/components/layout/PageShell'; import { PageShell } from '@/components/layout/PageShell';
import type { ActionModal, DeploymentWorkloadProps } from './deployment-workload/types'; import type { ActionModal, DeploymentWorkloadProps } from './deployment-workload/types';
import { useTranslation } from 'react-i18next';
export type { DeploymentWorkloadProps, WorkloadMode } from './deployment-workload/types'; export type { DeploymentWorkloadProps, WorkloadMode } from './deployment-workload/types';
export function DeploymentWorkload({ clusterCode, namespace, deploymentName, mode, onBack, onModeChange }: DeploymentWorkloadProps) { export function DeploymentWorkload({ clusterCode, namespace, deploymentName, mode, onBack, onModeChange }: DeploymentWorkloadProps) {
const { t } = useTranslation();
const isCreate = isCreateDeployment(deploymentName); const isCreate = isCreateDeployment(deploymentName);
const navigate = useNavigate(); const navigate = useNavigate();
const { toast } = useToast(); const { toast } = useToast();
@@ -117,7 +119,7 @@ export function DeploymentWorkload({ clusterCode, namespace, deploymentName, mod
setRevisions(toArray(revRes)); setRevisions(toArray(revRes));
} catch (e) { } catch (e) {
console.error('加载详情失败:', e); console.error(t('kubernetes.deploymentworkload.sb46ea9'), e);
} finally { } finally {
setLoading(false); setLoading(false);
} }
@@ -132,7 +134,7 @@ export function DeploymentWorkload({ clusterCode, namespace, deploymentName, mod
const { manifest: parsed } = await parseEditableManifest(yamlText); const { manifest: parsed } = await parseEditableManifest(yamlText);
setManifest(parsed || deployment); setManifest(parsed || deployment);
} catch (e) { } catch (e) {
console.warn('加载 manifest 失败(编辑功能降级):', e); console.warn(t('kubernetes.deploymentworkload.sce123f'), e);
setManifest(deployment); setManifest(deployment);
} }
}, [clusterCode, namespace, deploymentName, deployment]); }, [clusterCode, namespace, deploymentName, deployment]);
@@ -160,10 +162,10 @@ export function DeploymentWorkload({ clusterCode, namespace, deploymentName, mod
setActionLoading('scale'); setActionLoading('scale');
try { try {
await kubernetesApi.scaleDeployment(clusterCode, namespace, deploymentName, newReplicas); 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(); loadData();
} catch (e) { } 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(''); } } finally { setActionLoading(''); }
}; };
@@ -171,37 +173,37 @@ export function DeploymentWorkload({ clusterCode, namespace, deploymentName, mod
setActionLoading('scale'); setActionLoading('scale');
try { try {
await kubernetesApi.scaleDeployment(clusterCode, namespace, deploymentName, scaleValue); 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); setModal(null);
loadData(); loadData();
} catch (e) { } 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(''); } } finally { setActionLoading(''); }
}; };
const handleRestart = async () => { const handleRestart = async () => {
const ok = await confirm({ const ok = await confirm({
title: '滚动重启', title: t('kubernetes.deployment.restart'),
description: `确认滚动重启 Deployment "${deploymentName}"?`, description: t('kubernetes.deploymentworkload.s0703ab', { deploymentName: deploymentName }),
confirmText: '重启', confirmText: t('common.reboot'),
}); });
if (!ok) return; if (!ok) return;
setActionLoading('restart'); setActionLoading('restart');
try { try {
await kubernetesApi.restartDeployment(clusterCode, namespace, deploymentName); await kubernetesApi.restartDeployment(clusterCode, namespace, deploymentName);
toast({ title: '重启指令已下发', description: 'Deployment 正在滚动重启' }); toast({ title: t('kubernetes.deploymentworkload.s68a700'), description: t('kubernetes.deploymentworkload.sd18761') });
setTimeout(loadData, 1500); setTimeout(loadData, 1500);
} catch (e) { } 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(''); } } finally { setActionLoading(''); }
}; };
const handleTogglePause = async () => { const handleTogglePause = async () => {
const isPaused = !!deployment?.paused; const isPaused = !!deployment?.paused;
const action = isPaused ? '恢复' : '暂停'; const action = isPaused ? t('common.resume') : t('common.pause');
const ok = await confirm({ const ok = await confirm({
title: `${action}滚动更新`, title: t('kubernetes.deploymentworkload.s704225', { action: action }),
description: `确认${action} Deployment "${deploymentName}" 的滚动更新?`, description: t('kubernetes.deploymentworkload.se0945f', { action: action, deploymentName: deploymentName }),
confirmText: action, confirmText: action,
}); });
if (!ok) return; if (!ok) return;
@@ -212,10 +214,10 @@ export function DeploymentWorkload({ clusterCode, namespace, deploymentName, mod
} else { } else {
await kubernetesApi.pauseDeployment(clusterCode, namespace, deploymentName); 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); setTimeout(loadData, 1000);
} catch (e) { } 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(''); } } finally { setActionLoading(''); }
}; };
@@ -232,11 +234,11 @@ export function DeploymentWorkload({ clusterCode, namespace, deploymentName, mod
await kubernetesApi.updateDeploymentImage( await kubernetesApi.updateDeploymentImage(
clusterCode, namespace, deploymentName, newImage, cicdContainerName || undefined, 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); setModal(null);
loadData(); loadData();
} catch (e) { } 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(''); } } 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 url = `${baseUrl}/api/v1/kubernetes/${clusterCode}/namespace/${namespace}/deployments/${deploymentName}`;
const resp = await fetch(url, { method: 'DELETE', headers: { Authorization: `Bearer ${tk}` } }); const resp = await fetch(url, { method: 'DELETE', headers: { Authorization: `Bearer ${tk}` } });
if (!resp.ok) throw new Error(`HTTP ${resp.status}`); 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); setModal(null);
setTimeout(() => navigate(`/kubernetes/${clusterCode}/namespace/${namespace}/deployments`), 800); setTimeout(() => navigate(`/kubernetes/${clusterCode}/namespace/${namespace}/deployments`), 800);
} catch (e) { } 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(''); } } finally { setActionLoading(''); }
}; };
@@ -269,24 +271,24 @@ export function DeploymentWorkload({ clusterCode, namespace, deploymentName, mod
const handleDeletePod = async (pod: any) => { const handleDeletePod = async (pod: any) => {
const ok = await confirm({ const ok = await confirm({
title: '删除 Pod', title: t('kubernetes.pod.deletePod'),
description: `确认删除 Pod "${pod.name}"?操作不可恢复。`, description: t('kubernetes.deploymentworkload.s96e132', { pod.name: pod.name }),
confirmText: '删除', confirmText: t('common.delete'),
}); });
if (!ok) return; if (!ok) return;
try { try {
await kubernetesApi.deletePod(clusterCode, namespace, pod.name); await kubernetesApi.deletePod(clusterCode, namespace, pod.name);
toast({ title: 'Pod 已删除' }); toast({ title: t('kubernetes.pod.deleted') });
loadData(); loadData();
} catch (e) { } 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 ============ // ============ 渲染 // Logan.Li ============
if (loading) { if (loading) {
return ( 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} {null}
</PageShell> </PageShell>
); );
@@ -294,7 +296,7 @@ export function DeploymentWorkload({ clusterCode, namespace, deploymentName, mod
if (!deployment && !isCreate) { if (!deployment && !isCreate) {
return ( 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> <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> </PageShell>
); );
@@ -306,7 +308,7 @@ export function DeploymentWorkload({ clusterCode, namespace, deploymentName, mod
if (name) navigate(`/kubernetes/${clusterCode}/namespace/${namespace}/workload/view/Deployment/${name}`); if (name) navigate(`/kubernetes/${clusterCode}/namespace/${namespace}/workload/view/Deployment/${name}`);
}; };
return ( 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} /> <EditModeContainer clusterCode={clusterCode} namespace={namespace} deploymentName={CREATE_DEPLOYMENT_SLUG} manifest={manifest} isCreate onSaved={handleCreated} onCancel={onBack} />
</PageShell> </PageShell>
); );
@@ -318,8 +320,8 @@ export function DeploymentWorkload({ clusterCode, namespace, deploymentName, mod
const modeTabs = ( const modeTabs = (
<div className="inline-flex rounded-md border border-[var(--dg-border)] overflow-hidden"> <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 === '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')}>编辑</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> <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> </div>
); );
@@ -328,19 +330,19 @@ export function DeploymentWorkload({ clusterCode, namespace, deploymentName, mod
<PageShell <PageShell
variant="workspace" variant="workspace"
title={deploymentName} title={deploymentName}
subtitle={`${clusterCode} / ${namespace} · Deployment · 镜像: ${deployment?.image || '-'}`} subtitle={t('kubernetes.deploymentworkload.s804752', { clusterCode: clusterCode, namespace: namespace, deployment?.image || '-': deployment?.image || '-' })}
actions={( 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} {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={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={() => { 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" />重启</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}> <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>
<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-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'}> <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} {isHealthy ? <CheckCircle className="h-3 w-3 mr-1" /> : <AlertTriangle className="h-3 w-3 mr-1" />}{ready}/{total}
</Badge> </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> </div>
{/* ============ 主体:view / edit / yaml ============ */} {/* ============ 主体:view / edit / yaml ============ */}
@@ -377,7 +379,7 @@ export function DeploymentWorkload({ clusterCode, namespace, deploymentName, mod
resource="deployments" resource="deployments"
name={deploymentName} name={deploymentName}
inline inline
resourceHint="含关联 Service" resourceHint=t('kubernetes.deploymentworkload.s239604')
loadYamlFn={loadBundleYaml} loadYamlFn={loadBundleYaml}
saveYamlFn={saveBundleYaml} saveYamlFn={saveBundleYaml}
onSaved={loadData} onSaved={loadData}
@@ -402,7 +404,7 @@ export function DeploymentWorkload({ clusterCode, namespace, deploymentName, mod
namespace={namespace} namespace={namespace}
resource="deployments" resource="deployments"
name={deploymentName} name={deploymentName}
resourceHint="含关联 Service" resourceHint=t('kubernetes.deploymentworkload.s239604')
loadYamlFn={loadBundleYaml} loadYamlFn={loadBundleYaml}
saveYamlFn={saveBundleYaml} saveYamlFn={saveBundleYaml}
onClose={() => setModal(null)} onClose={() => setModal(null)}
@@ -5,6 +5,8 @@ import { useVirtualizer } from '@tanstack/react-virtual';
import { Badge } from '@/components/ui/badge'; import { Badge } from '@/components/ui/badge';
import { Loader2 } from 'lucide-react'; import { Loader2 } from 'lucide-react';
import { import {
import { useTranslation } from 'react-i18next';
import i18n from '@/i18n';
type NormalizedEvent, type NormalizedEvent,
formatEventRepeatSpan, formatEventRepeatSpan,
formatEventTimeCell, formatEventTimeCell,
@@ -30,10 +32,11 @@ const MIN_W = '980px';
export function EventTable({ export function EventTable({
events, events,
loading = false, loading = false,
emptyText = '暂无事件', emptyText = i18n.t('k8s.empty.events'),
showNamespace = false, showNamespace = false,
scrollHeight = 600, scrollHeight = 600,
}: EventTableProps) { }: EventTableProps) {
const { t } = useTranslation();
const [expandedRow, setExpandedRow] = useState<string | null>(null); const [expandedRow, setExpandedRow] = useState<string | null>(null);
const isLoading = loading === true || loading === 'events'; const isLoading = loading === true || loading === 'events';
const scrollRef = useRef<HTMLDivElement>(null); const scrollRef = useRef<HTMLDivElement>(null);
@@ -41,8 +44,8 @@ export function EventTable({
const gridCols = showNamespace ? COLS_NS : COLS; const gridCols = showNamespace ? COLS_NS : COLS;
const minWidth = showNamespace ? MIN_W_NS : MIN_W; const minWidth = showNamespace ? MIN_W_NS : MIN_W;
const headers = showNamespace 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({ const virtualizer = useVirtualizer({
count: events.length, count: events.length,
@@ -163,7 +166,7 @@ export function EventTable({
{/* 行数统计 */} {/* 行数统计 */}
{events.length > 0 && ( {events.length > 0 && (
<div className="text-center py-2 text-xs text-[var(--dg-text-muted)] border-t border-[var(--dg-border)]"> <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>
)} )}
</div> </div>
@@ -13,6 +13,7 @@ import { PageShell } from '@/components/layout/PageShell';
import { ContentPanel } from '@/components/layout/ContentPanel'; import { ContentPanel } from '@/components/layout/ContentPanel';
import { StatStrip } from '@/components/ui/stat-strip'; import { StatStrip } from '@/components/ui/stat-strip';
import type { JsonData } from '@/types/common'; import type { JsonData } from '@/types/common';
import { useTranslation } from 'react-i18next';
interface RankItem { name: string; count: number } interface RankItem { name: string; count: number }
@@ -26,13 +27,14 @@ function RankPanel({
onSelect?: (name: string) => void; onSelect?: (name: string) => void;
emptyText?: string; emptyText?: string;
}) { }) {
const { t } = useTranslation();
const max = Math.max(...items.map((i) => i.count), 1); const max = Math.max(...items.map((i) => i.count), 1);
return ( return (
<Card className="bg-[var(--dg-bg-secondary)] border-[var(--dg-border)]"> <Card className="bg-[var(--dg-bg-secondary)] border-[var(--dg-border)]">
<CardContent className="p-4"> <CardContent className="p-4">
<h3 className="text-sm font-medium text-[var(--dg-text-primary)] mb-3">{title}</h3> <h3 className="text-sm font-medium text-[var(--dg-text-primary)] mb-3">{title}</h3>
{items.length === 0 ? ( {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"> <div className="space-y-1.5 max-h-[220px] overflow-y-auto pr-1">
{items.map((item) => { {items.map((item) => {
@@ -67,6 +69,7 @@ function RankPanel({
} }
export default function EventsPage() { export default function EventsPage() {
const { t } = useTranslation();
const { clusterCode } = useParams<{ clusterCode: string }>(); const { clusterCode } = useParams<{ clusterCode: string }>();
const navigate = useNavigate(); const navigate = useNavigate();
const [loading, setLoading] = useState(false); const [loading, setLoading] = useState(false);
@@ -160,7 +163,7 @@ export default function EventsPage() {
const filterToolbar = (selectedReason || selectedKind) ? ( const filterToolbar = (selectedReason || selectedKind) ? (
<div className="flex items-center gap-2 text-xs"> <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 && ( {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('')}> <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" /> 原因 {selectedReason} <X className="h-3 w-3" />
@@ -177,16 +180,16 @@ export default function EventsPage() {
return ( return (
<PageShell <PageShell
variant="list" variant="list"
title="事件中心" title=t('kubernetes.eventspage.s08bf79')
subtitle={clusterName ? `${clusterName} · 集群事件与告警` : '集群事件与告警'} subtitle={clusterName ? t('kubernetes.eventspage.s49c5d1', { clusterName: clusterName }) : t('kubernetes.eventspage.s6bef2b')}
icon={<Bell className="h-5 w-5" />} icon={<Bell className="h-5 w-5" />}
metrics={!loading ? ( metrics={!loading ? (
<StatStrip <StatStrip
items={[ items={[
{ label: '事件总数', value: summary?.total ?? events.length, color: 'muted' }, { label: t('kubernetes.eventspage.s0d3047'), value: summary?.total ?? events.length, color: 'muted' },
{ label: '告警事件', value: summary?.warning_count ?? warningCount, color: 'amber' }, { label: t('kubernetes.eventspage.s0e5b83'), value: summary?.warning_count ?? warningCount, color: 'amber' },
{ label: '正常事件', value: summary?.normal_count ?? normalCount, color: 'green' }, { label: t('kubernetes.eventspage.s349c62'), value: summary?.normal_count ?? normalCount, color: 'green' },
{ label: '告警类型', value: reasonData.length, color: 'red' }, { label: t('kubernetes.eventspage.sc62e34'), value: reasonData.length, color: 'red' },
]} ]}
/> />
) : undefined} ) : undefined}
@@ -202,20 +205,20 @@ export default function EventsPage() {
</SelectContent> </SelectContent>
</Select> </Select>
<Select value={selectedNs} onValueChange={(v) => { setSelectedNs(v); setSelectedReason(''); setSelectedKind(''); }}> <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> <SelectContent>
<SelectItem value="all">所有命名空间</SelectItem> <SelectItem value="all">{t('kubernetes.eventspage.s58173b')}</SelectItem>
{namespaces.map((n) => <SelectItem key={n} value={n}>{n}</SelectItem>)} {namespaces.map((n) => <SelectItem key={n} value={n}>{n}</SelectItem>)}
</SelectContent> </SelectContent>
</Select> </Select>
<Select value={timeWindow} onValueChange={setTimeWindow}> <Select value={timeWindow} onValueChange={setTimeWindow}>
<SelectTrigger className="w-32 h-9 dg-input"><SelectValue /></SelectTrigger> <SelectTrigger className="w-32 h-9 dg-input"><SelectValue /></SelectTrigger>
<SelectContent> <SelectContent>
<SelectItem value="0">全部时间</SelectItem> <SelectItem value="0">{t('kubernetes.eventspage.s98c99f')}</SelectItem>
<SelectItem value="1">近 1 小时</SelectItem> <SelectItem value="1">{t('kubernetes.eventspage.sf972b7')}</SelectItem>
<SelectItem value="6">近 6 小时</SelectItem> <SelectItem value="6">{t('monitor.siteProtocol.rangeDefault')}</SelectItem>
<SelectItem value="24">近 24 小时</SelectItem> <SelectItem value="24">{t('kubernetes.eventspage.s6e99b7')}</SelectItem>
<SelectItem value="168">近 7 天</SelectItem> <SelectItem value="168">{t('kubernetes.eventspage.sd765ef')}</SelectItem>
</SelectContent> </SelectContent>
</Select> </Select>
<Button variant="outline" size="sm" className="dg-btn-secondary" onClick={() => { loadEvents(); loadSummary(); }} disabled={loading}> <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 && ( {reasonData.length > 0 && (
<div className="grid grid-cols-1 lg:grid-cols-3 gap-4"> <div className="grid grid-cols-1 lg:grid-cols-3 gap-4">
<RankPanel title="告警原因" items={reasonData} selected={selectedReason} onSelect={setSelectedReason} /> <RankPanel title=t('kubernetes.eventspage.s8c894f') items={reasonData} selected={selectedReason} onSelect={setSelectedReason} />
{nsData.length > 0 && <RankPanel title="命名空间" items={nsData} />} {nsData.length > 0 && <RankPanel title=t('k8s.column.namespace') items={nsData} />}
{kindData.length > 0 && ( {kindData.length > 0 && (
<RankPanel title="资源类型" items={kindData} selected={selectedKind} onSelect={setSelectedKind} /> <RankPanel title=t('kubernetes.eventspage.s14871a') items={kindData} selected={selectedKind} onSelect={setSelectedKind} />
)} )}
</div> </div>
)} )}
@@ -268,7 +271,7 @@ export default function EventsPage() {
<Select value={filterType} onValueChange={setFilterType}> <Select value={filterType} onValueChange={setFilterType}>
<SelectTrigger className="w-28 h-8 dg-input text-xs"><SelectValue /></SelectTrigger> <SelectTrigger className="w-28 h-8 dg-input text-xs"><SelectValue /></SelectTrigger>
<SelectContent> <SelectContent>
<SelectItem value="all">所有类型</SelectItem> <SelectItem value="all">{t('kubernetes.eventspage.sfb9951')}</SelectItem>
<SelectItem value="Warning">Warning</SelectItem> <SelectItem value="Warning">Warning</SelectItem>
<SelectItem value="Normal">Normal</SelectItem> <SelectItem value="Normal">Normal</SelectItem>
</SelectContent> </SelectContent>
@@ -4,6 +4,7 @@ import { useNavigate } from 'react-router-dom';
import { Loader2 } from 'lucide-react'; import { Loader2 } from 'lucide-react';
import { kubernetesApi } from '@/api'; import { kubernetesApi } from '@/api';
import type { JsonData } from '@/types/common'; import type { JsonData } from '@/types/common';
import { useTranslation } from 'react-i18next';
interface Props { interface Props {
/** 集群下路径,如 events、namespace/default/deployments */ /** 集群下路径,如 events、namespace/default/deployments */
@@ -11,6 +12,7 @@ interface Props {
} }
export default function K8sShortcutRedirect({ target }: Props) { export default function K8sShortcutRedirect({ target }: Props) {
const { t } = useTranslation();
const navigate = useNavigate(); const navigate = useNavigate();
useEffect(() => { useEffect(() => {
@@ -30,7 +32,7 @@ export default function K8sShortcutRedirect({ target }: Props) {
return ( return (
<div className="flex flex-col items-center justify-center py-24 dg-text-muted gap-2"> <div className="flex flex-col items-center justify-center py-24 dg-text-muted gap-2">
<Loader2 className="h-6 w-6 animate-spin" /> <Loader2 className="h-6 w-6 animate-spin" />
<span className="text-sm">正在跳转...</span> <span className="text-sm">{t('kubernetes.k8sshortcutredirect.s9d1aae')}</span>
</div> </div>
); );
} }
@@ -11,6 +11,7 @@ import 'xterm/css/xterm.css';
import { Terminal, Maximize2, Minimize2, X, Loader2 } from 'lucide-react'; import { Terminal, Maximize2, Minimize2, X, Loader2 } from 'lucide-react';
import { cn } from '@/lib/utils'; import { cn } from '@/lib/utils';
import { useUserStore } from '@/store'; import { useUserStore } from '@/store';
import { useTranslation } from 'react-i18next';
interface KubectlTerminalProps { interface KubectlTerminalProps {
open: boolean; open: boolean;
@@ -20,6 +21,7 @@ interface KubectlTerminalProps {
} }
export function KubectlTerminal({ open, onOpenChange, clusterId, clusterName }: KubectlTerminalProps) { export function KubectlTerminal({ open, onOpenChange, clusterId, clusterName }: KubectlTerminalProps) {
const { t } = useTranslation();
const containerRef = useRef<HTMLDivElement>(null); const containerRef = useRef<HTMLDivElement>(null);
const termRef = useRef<XTerm | null>(null); const termRef = useRef<XTerm | null>(null);
const wsRef = useRef<WebSocket | null>(null); const wsRef = useRef<WebSocket | null>(null);
@@ -106,12 +108,12 @@ export function KubectlTerminal({ open, onOpenChange, clusterId, clusterName }:
ws.onclose = () => { ws.onclose = () => {
setConnected(false); setConnected(false);
term.write('\r\n\x1b[31m[连接已断开]\x1b[0m\r\n'); term.write(t('kubernetes.kubectlterminal.sf4ee00'));
}; };
ws.onerror = () => { ws.onerror = () => {
setError('WebSocket 连接失败'); setError(t('kubernetes.kubectlterminal.s5b4a67'));
term.write('\r\n\x1b[31m[连接发生错误]\x1b[0m\r\n'); term.write(t('kubernetes.kubectlterminal.sc81077'));
}; };
return () => { return () => {
@@ -174,7 +176,7 @@ export function KubectlTerminal({ open, onOpenChange, clusterId, clusterName }:
style={fullscreen ? { maxWidth: '100vw', width: '100vw', height: '100vh' } : { maxWidth: '900px', width: '90vw' }} style={fullscreen ? { maxWidth: '100vw', width: '100vw', height: '100vh' } : { maxWidth: '900px', width: '90vw' }}
> >
<DialogTitle className="sr-only">kubectl — {clusterName}</DialogTitle> <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)]"> <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 { kubernetesApi } from '@/api';
import { toast } from 'sonner'; import { toast } from 'sonner';
import type { JsonData } from '@/types/common'; import type { JsonData } from '@/types/common';
import { useTranslation } from 'react-i18next';
// 名称即 code,只允许英文/数字/连字符 // 名称即 code,只允许英文/数字/连字符
const NAME_RE = /^[a-zA-Z0-9]([a-zA-Z0-9-]*[a-zA-Z0-9])?$/; const NAME_RE = /^[a-zA-Z0-9]([a-zA-Z0-9-]*[a-zA-Z0-9])?$/;
@@ -40,6 +41,7 @@ export function KubernetesClusterDialog({
editingCluster?: JsonData; editingCluster?: JsonData;
onSaved: () => void; onSaved: () => void;
}) { }) {
const { t } = useTranslation();
const [formData, setFormData] = useState({ ...emptyForm }); const [formData, setFormData] = useState({ ...emptyForm });
const [submitting, setSubmitting] = useState(false); const [submitting, setSubmitting] = useState(false);
const [hasToken, setHasToken] = useState(false); const [hasToken, setHasToken] = useState(false);
@@ -88,7 +90,7 @@ export function KubernetesClusterDialog({
if (!value.trim()) { if (!value.trim()) {
setNameError(''); setNameError('');
} else if (!NAME_RE.test(value)) { } else if (!NAME_RE.test(value)) {
setNameError('只允许英文、数字和连字符(-),首尾不能是连字符'); setNameError(t('kubernetes.kubernetesclusterdialog.sc7ec6c'));
} else { } else {
setNameError(''); setNameError('');
} }
@@ -110,7 +112,7 @@ export function KubernetesClusterDialog({
const handleSubmit = async () => { const handleSubmit = async () => {
if (!formData.name.trim() || !NAME_RE.test(formData.name.trim())) { if (!formData.name.trim() || !NAME_RE.test(formData.name.trim())) {
toast.error('请输入有效的集群名称(英文/数字/连字符)'); return; toast.error(t('kubernetes.kubernetesclusterdialog.s38bbfe')); return;
} }
try { try {
setSubmitting(true); setSubmitting(true);
@@ -132,7 +134,7 @@ export function KubernetesClusterDialog({
onOpenChange(false); onOpenChange(false);
onSaved(); onSaved();
} catch (e) { } catch (e) {
console.error('保存集群失败:', e); console.error(t('kubernetes.kubernetesclusterdialog.s7aa44b'), e);
} finally { } finally {
setSubmitting(false); setSubmitting(false);
} }
@@ -145,20 +147,20 @@ export function KubernetesClusterDialog({
<DialogContent className="bg-[var(--dg-bg-secondary)] border-[var(--dg-border)] max-w-2xl"> <DialogContent className="bg-[var(--dg-bg-secondary)] border-[var(--dg-border)] max-w-2xl">
<DialogHeader> <DialogHeader>
<DialogTitle className="text-[var(--dg-text-primary)]"> <DialogTitle className="text-[var(--dg-text-primary)]">
{editingCluster ? '编辑集群' : '添加集群'} {editingCluster ? t('kubernetes.cluster.editCluster') : t('kubernetes.cluster.addCluster')}
</DialogTitle> </DialogTitle>
<DialogDescription className="text-[var(--dg-text-secondary)]"> <DialogDescription className="text-[var(--dg-text-secondary)]">
{editingCluster ? '修改集群接入配置' : '配置新的 Kubernetes 集群接入信息'} {editingCluster ? t('kubernetes.kubernetesclusterdialog.s2d42f2') : t('kubernetes.kubernetesclusterdialog.sfe6c79')}
</DialogDescription> </DialogDescription>
</DialogHeader> </DialogHeader>
<div className="space-y-4 py-2 max-h-[60vh] overflow-y-auto pr-1"> <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="grid grid-cols-2 gap-4">
<div className="space-y-2"> <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 <Input
value={formData.name} value={formData.name}
onChange={(e) => handleNameChange(e.target.value)} 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' : ''}`} 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>} {nameError && <p className="text-xs dg-text-red">{nameError}</p>}
@@ -167,28 +169,28 @@ export function KubernetesClusterDialog({
</p> </p>
</div> </div>
<div className="space-y-2"> <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 <Input
value={formData.version} value={formData.version}
onChange={(e) => setFormData({ ...formData, version: e.target.value })} 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)]" className="bg-[var(--dg-bg-tertiary)] border-[var(--dg-border)] text-[var(--dg-text-primary)] placeholder:text-[var(--dg-text-muted)]"
/> />
</div> </div>
</div> </div>
<div className="space-y-2"> <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 <Input
value={formData.description} value={formData.description}
onChange={(e) => setFormData({ ...formData, description: e.target.value })} 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)]" 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"> <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 <RadioGroup
value={String(formData.config_type)} value={String(formData.config_type)}
onValueChange={(v) => setFormData({ ...formData, config_type: Number(v) })} onValueChange={(v) => setFormData({ ...formData, config_type: Number(v) })}
@@ -218,12 +220,12 @@ export function KubernetesClusterDialog({
{formData.config_type === 0 ? ( {formData.config_type === 0 ? (
<div className="space-y-2"> <div className="space-y-2">
<Label className="text-[var(--dg-text-secondary)]"> <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> </Label>
<Textarea <Textarea
value={formData.token} value={formData.token}
onChange={(e) => setFormData({ ...formData, token: e.target.value })} 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} 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" 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"> <div className="space-y-2">
<Label className="text-[var(--dg-text-secondary)]"> <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> </Label>
<Textarea <Textarea
value={formData.kube_config} value={formData.kube_config}
onChange={(e) => handleKubeConfigChange(e.target.value)} 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} 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" 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} disabled={canSubmit}
className="bg-[var(--dg-blue)] hover:opacity-90 text-white" 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> </Button>
</DialogFooter> </DialogFooter>
</DialogContent> </DialogContent>
@@ -36,8 +36,10 @@ import { KubernetesClusterDialog } from './KubernetesClusterDialog';
import { KubectlTerminal } from './KubectlTerminal'; import { KubectlTerminal } from './KubectlTerminal';
import { PageShell } from '@/components/layout/PageShell'; import { PageShell } from '@/components/layout/PageShell';
import type { JsonData } from '@/types/common'; import type { JsonData } from '@/types/common';
import { useTranslation } from 'react-i18next';
export function KubernetesClusters() { export function KubernetesClusters() {
const { t } = useTranslation();
const [clusters, setClusters] = useState<JsonData[]>([]); const [clusters, setClusters] = useState<JsonData[]>([]);
const [loading, setLoading] = useState(true); const [loading, setLoading] = useState(true);
const [selectedCluster, setSelectedCluster] = useState<string | null>(null); const [selectedCluster, setSelectedCluster] = useState<string | null>(null);
@@ -61,7 +63,7 @@ export function KubernetesClusters() {
const res: JsonData = await kubernetesApi.getClusters(); const res: JsonData = await kubernetesApi.getClusters();
setClusters(res?.list || []); setClusters(res?.list || []);
} catch (e) { } catch (e) {
console.error('加载集群列表失败:', e); console.error(t('kubernetes.kubernetesclusters.s64090a'), e);
setClusters([]); setClusters([]);
} finally { } finally {
setLoading(false); setLoading(false);
@@ -95,18 +97,18 @@ export function KubernetesClusters() {
await kubernetesApi.deleteCluster(id); await kubernetesApi.deleteCluster(id);
loadData(); loadData();
} catch (e) { } catch (e) {
console.error('删除集群失败:', e); console.error(t('kubernetes.kubernetesclusters.s3d78e3'), e);
} }
}; };
const handleSync = async (id: number | string, silent?: boolean) => { const handleSync = async (id: number | string, silent?: boolean) => {
try { try {
if (!silent) toast.info('正在同步集群资源...'); if (!silent) toast.info(t('kubernetes.kubernetesclusters.sf31179'));
const res: JsonData = await kubernetesApi.syncCluster(id); const res: JsonData = await kubernetesApi.syncCluster(id);
if (!silent) toast.success(res?.message || '同步完成'); if (!silent) toast.success(res?.message || t('kubernetes.kubernetesclusters.s02f667'));
loadData(); loadData();
} catch (e) { } 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); const code = exportCluster.code || String(exportCluster.id);
try { try {
setExporting(true); setExporting(true);
toast.info(`正在导出 ${exportCluster.name} 所有命名空间的资源...`); toast.info(t('kubernetes.kubernetesclusters.s1d9a60', { exportCluster.name: exportCluster.name }));
await kubernetesApi.exportAllResources(code); await kubernetesApi.exportAllResources(code);
toast.success('导出完成,已开始下载'); toast.success(t('kubernetes.kubernetesclusters.s10a4f7'));
setExportCluster(null); setExportCluster(null);
} catch (e) { } catch (e) {
toast.error(e?.message || '导出失败'); toast.error(e?.message || t('common.exportFailed'));
} finally { } finally {
setExporting(false); setExporting(false);
} }
@@ -166,7 +168,7 @@ export function KubernetesClusters() {
<div className="relative w-80"> <div className="relative w-80">
<Search className="absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 dg-text-muted" /> <Search className="absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 dg-text-muted" />
<Input <Input
placeholder="搜索集群名称或版本..." placeholder=t('kubernetes.kubernetesclusters.s317554')
value={searchQuery} value={searchQuery}
onChange={(e) => setSearchQuery(e.target.value)} onChange={(e) => setSearchQuery(e.target.value)}
className="pl-9 h-9 dg-input" className="pl-9 h-9 dg-input"
@@ -177,12 +179,12 @@ export function KubernetesClusters() {
return ( return (
<PageShell <PageShell
variant="list" variant="list"
title="集群列表" title=t('menu.clusterList')
subtitle="管理 Kubernetes 集群资源" subtitle=t('kubernetes.kubernetesclusters.sb0fcb9')
icon={<Cloud className="h-5 w-5" />} icon={<Cloud className="h-5 w-5" />}
toolbar={searchToolbar} toolbar={searchToolbar}
loading={loading} loading={loading}
loadingLabel="加载集群..." loadingLabel=t('kubernetes.kubernetesclusters.se5a067')
actions={( actions={(
<> <>
<Button variant="outline" size="sm" className="dg-btn-secondary" onClick={loadData}> <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"> <div className="grid grid-cols-1 lg:grid-cols-2 xl:grid-cols-3 gap-4">
{!loading && filteredClusters.length === 0 ? ( {!loading && filteredClusters.length === 0 ? (
<Card className="bg-[var(--dg-bg-secondary)] border-[var(--dg-border)] col-span-full"> <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> </Card>
) : ( ) : (
filteredClusters.map((cluster) => { filteredClusters.map((cluster) => {
@@ -243,7 +245,7 @@ export function KubernetesClusters() {
</Button> </Button>
</DropdownMenuTrigger> </DropdownMenuTrigger>
<DropdownMenuContent align="end" className="w-48 bg-[var(--dg-bg-tertiary)] border-[var(--dg-border)]"> <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)]" /> <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)]"> <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" /> <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> <span className="text-xs text-[var(--dg-text-secondary)] w-10 text-right">{cpuUsage.toFixed(1)}%</span>
</div> </div>
<div className="flex items-center gap-2"> <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="flex-1 h-1.5 bg-[var(--dg-bg-tertiary)] rounded-full overflow-hidden">
<div <div
className={cn( className={cn(
@@ -402,7 +404,7 @@ export function KubernetesClusters() {
onClick={() => { if (!exporting) setExportCluster(null); }} 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()}> <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 ? ( {exporting ? (
<div className="flex flex-col items-center py-6 gap-3"> <div className="flex flex-col items-center py-6 gap-3">
<Loader2 className="h-9 w-9 animate-spin text-[var(--dg-blue)]" /> <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 Deployment、Service、Ingress、ConfigMap、Secret 为 tar.gz
</p> </p>
<div className="flex justify-end gap-2"> <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}> <Button className="bg-[var(--dg-blue)] hover:opacity-90 text-white" onClick={handleExport}>
<Download className="h-4 w-4 mr-1.5" /> <Download className="h-4 w-4 mr-1.5" />
确认导出 确认导出
@@ -13,8 +13,10 @@ import { kubernetesApi } from '@/api';
import { PageShell } from '@/components/layout/PageShell'; import { PageShell } from '@/components/layout/PageShell';
import { ContentPanel } from '@/components/layout/ContentPanel'; import { ContentPanel } from '@/components/layout/ContentPanel';
import type { JsonData } from '@/types/common'; import type { JsonData } from '@/types/common';
import { useTranslation } from 'react-i18next';
export function KubernetesNodes() { export function KubernetesNodes() {
const { t } = useTranslation();
const [clusters, setClusters] = useState<JsonData[]>([]); const [clusters, setClusters] = useState<JsonData[]>([]);
const [selectedCluster, setSelectedCluster] = useState(''); const [selectedCluster, setSelectedCluster] = useState('');
const [nodes, setNodes] = useState<JsonData[]>([]); const [nodes, setNodes] = useState<JsonData[]>([]);
@@ -63,14 +65,14 @@ export function KubernetesNodes() {
<div className="flex items-center gap-3 flex-wrap"> <div className="flex items-center gap-3 flex-wrap">
<div className="relative w-56"> <div className="relative w-56">
<Search className="absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 dg-text-muted" /> <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> </div>
<Select value={roleFilter} onValueChange={setRoleFilter}> <Select value={roleFilter} onValueChange={setRoleFilter}>
<SelectTrigger className="w-32 h-9 dg-input"> <SelectTrigger className="w-32 h-9 dg-input">
<SelectValue /> <SelectValue />
</SelectTrigger> </SelectTrigger>
<SelectContent> <SelectContent>
<SelectItem value="all">全部角色</SelectItem> <SelectItem value="all">{t('kubernetes.kubernetesnodes.s5bcc10')}</SelectItem>
<SelectItem value="master">Master</SelectItem> <SelectItem value="master">Master</SelectItem>
<SelectItem value="worker">Worker</SelectItem> <SelectItem value="worker">Worker</SelectItem>
</SelectContent> </SelectContent>
@@ -83,14 +85,14 @@ export function KubernetesNodes() {
return ( return (
<PageShell <PageShell
variant="list" variant="list"
title="节点管理" title=t('menu.nodeManagement')
subtitle={clusterLabel ? `${clusterLabel} · 工作节点状态与资源` : 'Kubernetes 集群工作节点状态与资源'} subtitle={clusterLabel ? t('kubernetes.kubernetesnodes.s055d95', { clusterLabel: clusterLabel }) : t('kubernetes.kubernetesnodes.s01b441')}
icon={<Server className="h-5 w-5" />} icon={<Server className="h-5 w-5" />}
actions={( actions={(
<> <>
<Select value={selectedCluster} onValueChange={setSelectedCluster}> <Select value={selectedCluster} onValueChange={setSelectedCluster}>
<SelectTrigger className="w-48 h-9 dg-input"> <SelectTrigger className="w-48 h-9 dg-input">
<SelectValue placeholder="选择集群" /> <SelectValue placeholder=t('k8s.topology.selectCluster') />
</SelectTrigger> </SelectTrigger>
<SelectContent> <SelectContent>
{clusters.map((c) => ( {clusters.map((c) => (
@@ -109,21 +111,21 @@ export function KubernetesNodes() {
<Table> <Table>
<TableHeader> <TableHeader>
<TableRow className="border-[var(--dg-border)] hover:bg-transparent"> <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)]">IP</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)]">状态</TableHead> <TableHead className="text-[var(--dg-text-secondary)]">{t('common.status')}</TableHead>
<TableHead className="text-[var(--dg-text-secondary)]">配置</TableHead> <TableHead className="text-[var(--dg-text-secondary)]">{t('common.config')}</TableHead>
<TableHead className="text-[var(--dg-text-secondary)]">使用率</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)]">Pods</TableHead>
<TableHead className="text-[var(--dg-text-secondary)]">Kubelet</TableHead> <TableHead className="text-[var(--dg-text-secondary)]">Kubelet</TableHead>
</TableRow> </TableRow>
</TableHeader> </TableHeader>
<TableBody> <TableBody>
{loading ? ( {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 ? ( ) : 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) => ( filtered.map((n) => (
<TableRow key={n.id} className="border-[var(--dg-border)] hover:bg-[var(--dg-bg-tertiary)]/30"> <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>{getRoleBadge(n.role)}</TableCell>
<TableCell>{getStatusBadge(n.status)}</TableCell> <TableCell>{getStatusBadge(n.status)}</TableCell>
<TableCell className="text-sm text-[var(--dg-text-secondary)]"> <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>
<TableCell> <TableCell>
{(() => { {(() => {
@@ -26,8 +26,10 @@ import { kubernetesApi } from '@/api';
import { useToast } from '@/hooks/use-toast'; import { useToast } from '@/hooks/use-toast';
import { DeploymentDetail } from './DeploymentDetail'; import { DeploymentDetail } from './DeploymentDetail';
import type { JsonData } from '@/types/common'; import type { JsonData } from '@/types/common';
import { useTranslation } from 'react-i18next';
export function KubernetesWorkloads() { export function KubernetesWorkloads() {
const { t } = useTranslation();
const { toast } = useToast(); const { toast } = useToast();
const [clusters, setClusters] = useState<JsonData[]>([]); const [clusters, setClusters] = useState<JsonData[]>([]);
const [selectedCluster, setSelectedCluster] = useState(''); const [selectedCluster, setSelectedCluster] = useState('');
@@ -119,10 +121,10 @@ export function KubernetesWorkloads() {
const newReplicas = (dep.replicas || 0) + delta; const newReplicas = (dep.replicas || 0) + delta;
if (newReplicas < 0) return; if (newReplicas < 0) return;
await kubernetesApi.scaleDeployment(selectedCluster, dep.namespace, dep.name, newReplicas); 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(); loadData();
} catch (e) { } catch (e) {
toast({ title: '操作失败', description: e?.message || String(e), variant: 'destructive' }); toast({ title: t('common.operationFailed'), description: e?.message || String(e), variant: 'destructive' });
} finally { } finally {
setActionLoading((prev) => { const n = { ...prev }; delete n[key]; return n; }); setActionLoading((prev) => { const n = { ...prev }; delete n[key]; return n; });
} }
@@ -144,13 +146,13 @@ export function KubernetesWorkloads() {
<div className="space-y-6"> <div className="space-y-6">
<div className="flex items-center justify-between"> <div className="flex items-center justify-between">
<div> <div>
<h1 className="text-2xl font-bold text-[var(--dg-text-primary)]">工作负载</h1> <h1 className="text-2xl font-bold text-[var(--dg-text-primary)]">{t('menu.workloads')}</h1>
<p className="text-sm dg-text-muted mt-1">Deployment 与 Pod 运行状态</p> <p className="text-sm dg-text-muted mt-1">{t('kubernetes.kubernetesworkloads.sf90ced')}</p>
</div> </div>
<div className="flex items-center gap-2"> <div className="flex items-center gap-2">
<Select value={selectedCluster} onValueChange={(v) => { setSelectedCluster(v); setSelectedNamespace('all'); }}> <Select value={selectedCluster} onValueChange={(v) => { setSelectedCluster(v); setSelectedNamespace('all'); }}>
<SelectTrigger className="w-48 h-9 dg-input"> <SelectTrigger className="w-48 h-9 dg-input">
<SelectValue placeholder="选择集群" /> <SelectValue placeholder=t('k8s.topology.selectCluster') />
</SelectTrigger> </SelectTrigger>
<SelectContent className="dg-input"> <SelectContent className="dg-input">
{clusters.map((c) => ( {clusters.map((c) => (
@@ -160,10 +162,10 @@ export function KubernetesWorkloads() {
</Select> </Select>
<Select value={selectedNamespace} onValueChange={setSelectedNamespace}> <Select value={selectedNamespace} onValueChange={setSelectedNamespace}>
<SelectTrigger className="w-40 h-9 dg-input"> <SelectTrigger className="w-40 h-9 dg-input">
<SelectValue placeholder="命名空间" /> <SelectValue placeholder=t('k8s.column.namespace') />
</SelectTrigger> </SelectTrigger>
<SelectContent className="dg-input max-h-[300px]"> <SelectContent className="dg-input max-h-[300px]">
<SelectItem value="all">全部命名空间</SelectItem> <SelectItem value="all">{t('kubernetes.namespace.allNamespaces')}</SelectItem>
{namespaces.map((ns) => ( {namespaces.map((ns) => (
<SelectItem key={ns} value={ns}>{ns}</SelectItem> <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"> <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: '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: '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) => ( ].map((s) => (
<Card key={s.label} className="dg-card"> <Card key={s.label} className="dg-card">
<CardContent className="p-4"> <CardContent className="p-4">
@@ -198,7 +200,7 @@ export function KubernetesWorkloads() {
<div className="relative w-56"> <div className="relative w-56">
<Search className="absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 dg-text-muted" /> <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> </div>
<Tabs value={activeTab} onValueChange={setActiveTab}> <Tabs value={activeTab} onValueChange={setActiveTab}>
@@ -213,18 +215,18 @@ export function KubernetesWorkloads() {
<Table> <Table>
<TableHeader> <TableHeader>
<TableRow className="border-[var(--dg-border)] hover:bg-transparent"> <TableRow className="border-[var(--dg-border)] hover:bg-transparent">
<TableHead className="dg-text-secondary">名称</TableHead> <TableHead className="dg-text-secondary">{t('common.name')}</TableHead>
<TableHead className="dg-text-secondary">命名空间</TableHead> <TableHead className="dg-text-secondary">{t('k8s.column.namespace')}</TableHead>
<TableHead className="dg-text-secondary">副本</TableHead> <TableHead className="dg-text-secondary">{t('kubernetes.kubernetesworkloads.s0428b3')}</TableHead>
<TableHead className="dg-text-secondary">镜像</TableHead> <TableHead className="dg-text-secondary">{t('k8s.column.image')}</TableHead>
<TableHead className="dg-text-secondary w-[140px]">操作</TableHead> <TableHead className="dg-text-secondary w-[140px]">{t('common.actions')}</TableHead>
</TableRow> </TableRow>
</TableHeader> </TableHeader>
<TableBody> <TableBody>
{loading ? ( {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 ? ( ) : 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) => ( filteredDeps.map((d) => (
<TableRow key={d.id || d.name} className="border-[var(--dg-border)] hover:bg-[var(--dg-bg-hover)] cursor-pointer" <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()}> <TableCell onClick={(e) => e.stopPropagation()}>
<div className="flex items-center gap-0.5"> <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)]" <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)}> onClick={() => handleQuickScale(d, -1)}>
<Minus className="h-3.5 w-3.5" /> <Minus className="h-3.5 w-3.5" />
</Button> </Button>
<Button variant="ghost" size="icon" className="h-7 w-7 dg-text-secondary hover:text-[var(--dg-text-primary)]" <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" /> <Plus className="h-3.5 w-3.5" />
</Button> </Button>
<Button variant="ghost" size="icon" className="h-7 w-7 dg-text-secondary hover:dg-text-blue" <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" /> <Eye className="h-3.5 w-3.5" />
</Button> </Button>
</div> </div>
@@ -280,21 +282,21 @@ export function KubernetesWorkloads() {
<Table> <Table>
<TableHeader> <TableHeader>
<TableRow className="border-[var(--dg-border)] hover:bg-transparent"> <TableRow className="border-[var(--dg-border)] hover:bg-transparent">
<TableHead className="dg-text-secondary">名称</TableHead> <TableHead className="dg-text-secondary">{t('common.name')}</TableHead>
<TableHead className="dg-text-secondary">命名空间</TableHead> <TableHead className="dg-text-secondary">{t('k8s.column.namespace')}</TableHead>
<TableHead className="dg-text-secondary">状态</TableHead> <TableHead className="dg-text-secondary">{t('common.status')}</TableHead>
<TableHead className="dg-text-secondary">节点</TableHead> <TableHead className="dg-text-secondary">{t('k8s.tab.nodes')}</TableHead>
<TableHead className="dg-text-secondary">CPU</TableHead> <TableHead className="dg-text-secondary">CPU</TableHead>
<TableHead className="dg-text-secondary">内存</TableHead> <TableHead className="dg-text-secondary">{t('k8s.pods.memory')}</TableHead>
<TableHead className="dg-text-secondary">重启</TableHead> <TableHead className="dg-text-secondary">{t('common.reboot')}</TableHead>
<TableHead className="dg-text-secondary">镜像</TableHead> <TableHead className="dg-text-secondary">{t('k8s.column.image')}</TableHead>
</TableRow> </TableRow>
</TableHeader> </TableHeader>
<TableBody> <TableBody>
{loading ? ( {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 ? ( ) : 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) => ( filteredPods.map((p) => (
<TableRow key={p.id} className="border-[var(--dg-border)] hover:bg-[var(--dg-bg-hover)]"> <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 { PageShell } from '@/components/layout/PageShell';
import { ContentPanel } from '@/components/layout/ContentPanel'; import { ContentPanel } from '@/components/layout/ContentPanel';
import { StatStrip } from '@/components/ui/stat-strip'; import { StatStrip } from '@/components/ui/stat-strip';
import { useTranslation } from 'react-i18next';
interface NamespaceDetail { interface NamespaceDetail {
name: string; name: string;
@@ -39,6 +40,7 @@ const SYSTEM_NAMESPACES = new Set([
]); ]);
export default function NamespaceManagementPage() { export default function NamespaceManagementPage() {
const { t } = useTranslation();
const { clusterCode } = useParams<{ clusterCode: string }>(); const { clusterCode } = useParams<{ clusterCode: string }>();
const navigate = useNavigate(); const navigate = useNavigate();
const [namespaces, setNamespaces] = useState<NamespaceDetail[]>([]); const [namespaces, setNamespaces] = useState<NamespaceDetail[]>([]);
@@ -78,7 +80,7 @@ export default function NamespaceManagementPage() {
setCreateOpen(false); setCreateOpen(false);
await loadData(); await loadData();
} catch (err) { } catch (err) {
toast.error(err?.message || '创建失败'); toast.error(err?.message || t('monitor.quickSetupFailed'));
} finally { } finally {
setCreating(false); setCreating(false);
} }
@@ -92,7 +94,7 @@ export default function NamespaceManagementPage() {
setDeleteTarget(null); setDeleteTarget(null);
await loadData(); await loadData();
} catch (err) { } catch (err) {
toast.error(err?.message || '删除失败'); toast.error(err?.message || t('common.deleteFailed'));
} finally { } finally {
setDeleting(false); setDeleting(false);
} }
@@ -111,7 +113,7 @@ export default function NamespaceManagementPage() {
<Input <Input
value={searchQuery} value={searchQuery}
onChange={(e) => setSearchQuery(e.target.value)} onChange={(e) => setSearchQuery(e.target.value)}
placeholder="搜索命名空间..." placeholder=t('kubernetes.namespacemanagementpage.se91247')
className="max-w-xs dg-input" className="max-w-xs dg-input"
/> />
); );
@@ -119,17 +121,17 @@ export default function NamespaceManagementPage() {
return ( return (
<PageShell <PageShell
variant="list" variant="list"
title="命名空间管理" title=t('kubernetes.namespacemanagementpage.se935a3')
subtitle={`${clusterCode} · 资源配额与生命周期管理`} subtitle={t('kubernetes.namespacemanagementpage.s81e4b3', { clusterCode: clusterCode })}
icon={<Boxes className="h-5 w-5" />} icon={<Boxes className="h-5 w-5" />}
metrics={!loading ? ( metrics={!loading ? (
<StatStrip <StatStrip
items={[ items={[
{ label: '命名空间', value: namespaces.length, color: 'green' }, { label: t('k8s.column.namespace'), value: namespaces.length, color: 'green' },
{ label: 'Deployments', value: totalDeploys, color: 'blue' }, { label: 'Deployments', value: totalDeploys, color: 'blue' },
{ label: 'Pods', value: totalPods, color: 'purple' }, { label: 'Pods', value: totalPods, color: 'purple' },
{ label: 'Services', value: totalSvcs, color: 'cyan' }, { label: 'Services', value: totalSvcs, color: 'cyan' },
{ label: '配额限制', value: quotaCount, color: 'amber' }, { label: t('kubernetes.namespacemanagementpage.s47c3ae'), value: quotaCount, color: 'amber' },
]} ]}
/> />
) : undefined} ) : undefined}
@@ -147,15 +149,15 @@ export default function NamespaceManagementPage() {
</DialogTrigger> </DialogTrigger>
<DialogContent> <DialogContent>
<DialogHeader> <DialogHeader>
<DialogTitle>创建命名空间</DialogTitle> <DialogTitle>{t('kubernetes.namespacemanagementpage.s737f41')}</DialogTitle>
</DialogHeader> </DialogHeader>
<div className="space-y-4 py-4"> <div className="space-y-4 py-4">
<div className="space-y-2"> <div className="space-y-2">
<Label>命名空间名称</Label> <Label>{t('kubernetes.namespace.namespaceName')}</Label>
<Input <Input
value={newName} value={newName}
onChange={(e) => setNewName(e.target.value)} onChange={(e) => setNewName(e.target.value)}
placeholder="例如: my-app" placeholder=t('kubernetes.namespacemanagementpage.scba008')
onKeyDown={(e) => e.key === 'Enter' && handleCreate()} onKeyDown={(e) => e.key === 'Enter' && handleCreate()}
/> />
<p className="text-xs text-[var(--dg-text-muted)]"> <p className="text-xs text-[var(--dg-text-muted)]">
@@ -164,7 +166,7 @@ export default function NamespaceManagementPage() {
</div> </div>
</div> </div>
<DialogFooter> <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()}> <Button onClick={handleCreate} disabled={creating || !newName.trim()}>
{creating ? <Loader2 className="h-4 w-4 animate-spin mr-1" /> : null} {creating ? <Loader2 className="h-4 w-4 animate-spin mr-1" /> : null}
创建 创建
@@ -179,15 +181,15 @@ export default function NamespaceManagementPage() {
<Table> <Table>
<TableHeader> <TableHeader>
<TableRow className="border-[var(--dg-border)] hover:bg-transparent"> <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('common.name')}</TableHead>
<TableHead className="text-[var(--dg-text-secondary)]">状态</TableHead> <TableHead className="text-[var(--dg-text-secondary)]">{t('common.status')}</TableHead>
<TableHead className="text-[var(--dg-text-secondary)]">年龄</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">Deploy</TableHead>
<TableHead className="text-[var(--dg-text-secondary)] text-center">Pods</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">Svc</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)]">标签</TableHead> <TableHead className="text-[var(--dg-text-secondary)]">{t('common.tag')}</TableHead>
<TableHead className="text-[var(--dg-text-secondary)] text-center">操作</TableHead> <TableHead className="text-[var(--dg-text-secondary)] text-center">{t('common.actions')}</TableHead>
</TableRow> </TableRow>
</TableHeader> </TableHeader>
<TableBody> <TableBody>
@@ -247,13 +249,13 @@ export default function NamespaceManagementPage() {
</TableCell> </TableCell>
<TableCell className="text-center"> <TableCell className="text-center">
{isSystem ? ( {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 <Button
variant="ghost" size="icon" variant="ghost" size="icon"
className="h-7 w-7 text-[var(--dg-red)] hover:text-[var(--dg-red)] hover:bg-[var(--dg-red)]/10" className="h-7 w-7 text-[var(--dg-red)] hover:text-[var(--dg-red)] hover:bg-[var(--dg-red)]/10"
onClick={() => setDeleteTarget(ns.name)} onClick={() => setDeleteTarget(ns.name)}
title="删除命名空间" title=t('kubernetes.namespace.deleteNamespace')
> >
<Trash2 className="h-3.5 w-3.5" /> <Trash2 className="h-3.5 w-3.5" />
</Button> </Button>
@@ -286,7 +288,7 @@ export default function NamespaceManagementPage() {
</div> </div>
</div> </div>
<DialogFooter> <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}> <Button variant="destructive" onClick={handleDelete} disabled={deleting}>
{deleting ? <Loader2 className="h-4 w-4 animate-spin mr-1" /> : null} {deleting ? <Loader2 className="h-4 w-4 animate-spin mr-1" /> : null}
确认删除 确认删除
@@ -16,19 +16,22 @@ import {
import { kubernetesApi } from '@/api'; import { kubernetesApi } from '@/api';
import { PageShell } from '@/components/layout/PageShell'; import { PageShell } from '@/components/layout/PageShell';
import type { JsonData } from '@/types/common'; import type { JsonData } from '@/types/common';
import { useTranslation } from 'react-i18next';
import i18n from '@/i18n';
const RESOURCE_LINKS = [ const RESOURCE_LINKS = [
{ type: 'deployments', label: 'Deployments', icon: Boxes, desc: '工作负载副本管理' }, { type: 'deployments', label: 'Deployments', icon: Boxes, desc: i18n.t('kubernetes.namespaceoverviewpage.sb68c63') },
{ type: 'pods', label: 'Pods', icon: Container, desc: '容器实例运行状态' }, { type: 'pods', label: 'Pods', icon: Container, desc: i18n.t('kubernetes.namespaceoverviewpage.sfdac25') },
{ type: 'cronjobs', label: 'CronJobs', icon: Clock, desc: '定时任务管理' }, { type: 'cronjobs', label: 'CronJobs', icon: Clock, desc: i18n.t('kubernetes.namespaceoverviewpage.s9c9fc5') },
{ type: 'services', label: 'Services', icon: Network, desc: '服务发现与负载均衡' }, { type: 'services', label: 'Services', icon: Network, desc: i18n.t('kubernetes.namespaceoverviewpage.s3a3f6d') },
{ type: 'ingresses', label: 'Ingresses', icon: Network, desc: '外部流量路由规则' }, { type: 'ingresses', label: 'Ingresses', icon: Network, desc: i18n.t('kubernetes.namespaceoverviewpage.scc6971') },
{ type: 'configmaps', label: 'ConfigMaps', icon: FileText, desc: '配置字典' }, { type: 'configmaps', label: 'ConfigMaps', icon: FileText, desc: i18n.t('kubernetes.namespaceoverviewpage.s0986a6') },
{ type: 'secrets', label: 'Secrets', icon: Shield, desc: '密钥与凭证' }, { type: 'secrets', label: 'Secrets', icon: Shield, desc: i18n.t('kubernetes.namespaceoverviewpage.sb3fb72') },
{ type: 'hpas', label: 'HPAs', icon: Activity, desc: '水平自动伸缩策略' }, { type: 'hpas', label: 'HPAs', icon: Activity, desc: i18n.t('kubernetes.namespaceoverviewpage.sa84da2') },
]; ];
export default function NamespaceOverviewPage() { export default function NamespaceOverviewPage() {
const { t } = useTranslation();
const { clusterCode, namespace } = useParams<{ clusterCode: string; namespace: string }>(); const { clusterCode, namespace } = useParams<{ clusterCode: string; namespace: string }>();
const [counts, setCounts] = useState<Record<string, number>>({}); const [counts, setCounts] = useState<Record<string, number>>({});
const [loading, setLoading] = useState(false); const [loading, setLoading] = useState(false);
@@ -66,11 +69,11 @@ export default function NamespaceOverviewPage() {
return ( return (
<PageShell <PageShell
variant="default" variant="default"
title={namespace || '命名空间'} title={namespace || t('k8s.column.namespace')}
subtitle={`${clusterCode} · 命名空间概览`} subtitle={t('kubernetes.namespaceoverviewpage.s6d60aa', { clusterCode: clusterCode })}
icon={<Cloud className="h-5 w-5" />} icon={<Cloud className="h-5 w-5" />}
loading={loading} loading={loading}
loadingLabel="加载资源统计..." loadingLabel=t('kubernetes.namespaceoverviewpage.sfa525a')
> >
<div className="grid grid-cols-2 md:grid-cols-4 gap-4"> <div className="grid grid-cols-2 md:grid-cols-4 gap-4">
{RESOURCE_LINKS.map((r) => ( {RESOURCE_LINKS.map((r) => (
@@ -25,6 +25,8 @@ import { useToast } from '@/hooks/use-toast';
import { useConfirm } from '@/components/ui/confirm-dialog'; import { useConfirm } from '@/components/ui/confirm-dialog';
import { PageShell } from '@/components/layout/PageShell'; import { PageShell } from '@/components/layout/PageShell';
import { ContentPanel } from '@/components/layout/ContentPanel'; import { ContentPanel } from '@/components/layout/ContentPanel';
import { useTranslation } from 'react-i18next';
import i18n from '@/i18n';
type ResourceType = type ResourceType =
| 'deployments' | 'pods' | 'services' | 'ingresses' | '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 } }) => ( const VisualActions = ({ name, opts }: { name: string; opts: { onYaml?: (n: string) => void; onEdit?: (n: string) => void } }) => (
<div className="flex items-center gap-0.5"> <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="可视化编辑" <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" />编辑</Button> 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" <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> onClick={() => opts.onYaml?.(name)}><FileCode className="h-3.5 w-3.5 mr-1" />YAML</Button>
</div> </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; 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: { deployments: {
title: 'Deployments', subtitle: 'Deployment 工作负载运行状态', icon: Boxes, title: 'Deployments', subtitle: i18n.t('kubernetes.namespaceresourcepage.s35c744'), icon: Boxes,
columns: ['名称', '命名空间', '副本', '镜像'], columns: [i18n.t('common.name'), i18n.t('k8s.column.namespace'), i18n.t('kubernetes.namespaceresourcepage.s0428b3'), i18n.t('k8s.column.image')],
renderRow: (d, opts) => ( 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)}> <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> <TableCell className="font-medium text-[var(--dg-text-primary)]">{d.name}</TableCell>
@@ -83,8 +85,8 @@ const RESOURCE_CONFIG: Record<ResourceType, {
), ),
}, },
pods: { pods: {
title: 'Pods', subtitle: 'Pod 实例运行状态', icon: Container, title: 'Pods', subtitle: i18n.t('kubernetes.namespaceresourcepage.s780b7d'), icon: Container,
columns: ['名称', '命名空间', '状态', '节点', 'CPU', '内存', '重启', '镜像', '操作'], 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) => { 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' }; 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 ( 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 className="text-xs text-[var(--dg-text-muted)] max-w-[200px] truncate">{p.image || '-'}</TableCell>
<TableCell> <TableCell>
<div className="flex items-center gap-0.5"> <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> 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> 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" <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> 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> onClick={() => opts.onDeletePod?.(p)}><Trash2 className="h-3.5 w-3.5" /></Button>
</div> </div>
</TableCell> </TableCell>
@@ -119,8 +121,8 @@ const RESOURCE_CONFIG: Record<ResourceType, {
}, },
}, },
services: { services: {
title: 'Services', subtitle: 'Service 网络服务', icon: Network, title: 'Services', subtitle: i18n.t('kubernetes.namespaceresourcepage.s5e76b6'), icon: Network,
columns: ['名称', '命名空间', '类型', 'Cluster IP', '端口', '操作'], 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) => ( renderRow: (s, opts) => (
<TableRow key={s.name} className="border-[var(--dg-border)] hover:bg-[var(--dg-bg-tertiary)]/30"> <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> <TableCell className="font-medium text-[var(--dg-text-primary)]">{s.name}</TableCell>
@@ -133,8 +135,8 @@ const RESOURCE_CONFIG: Record<ResourceType, {
), ),
}, },
ingresses: { ingresses: {
title: 'Ingresses', subtitle: 'Ingress 路由规则', icon: Network, title: 'Ingresses', subtitle: i18n.t('kubernetes.namespaceresourcepage.s8d5014'), icon: Network,
columns: ['名称', '命名空间', 'Hosts', 'TLS', '操作'], columns: [i18n.t('common.name'), i18n.t('k8s.column.namespace'), 'Hosts', 'TLS', i18n.t('common.actions')],
renderRow: (i, opts) => { renderRow: (i, opts) => {
const hosts = i.hosts || []; const hosts = i.hosts || [];
return ( return (
@@ -149,8 +151,8 @@ const RESOURCE_CONFIG: Record<ResourceType, {
}, },
}, },
configmaps: { configmaps: {
title: 'ConfigMaps', subtitle: '配置字典', icon: FileText, title: 'ConfigMaps', subtitle: i18n.t('kubernetes.namespaceresourcepage.s0986a6'), icon: FileText,
columns: ['名称', '命名空间', '键数量', '操作'], columns: [i18n.t('common.name'), i18n.t('k8s.column.namespace'), i18n.t('kubernetes.namespaceresourcepage.sbd1fa0'), i18n.t('common.actions')],
renderRow: (c, opts) => ( renderRow: (c, opts) => (
<TableRow key={c.name} className="border-[var(--dg-border)] hover:bg-[var(--dg-bg-tertiary)]/30"> <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> <TableCell className="font-medium text-[var(--dg-text-primary)]">{c.name}</TableCell>
@@ -161,8 +163,8 @@ const RESOURCE_CONFIG: Record<ResourceType, {
), ),
}, },
secrets: { secrets: {
title: 'Secrets', subtitle: '密钥管理(仅名称与类型)', icon: Shield, title: 'Secrets', subtitle: i18n.t('kubernetes.namespaceresourcepage.sd1424a'), icon: Shield,
columns: ['名称', '命名空间', '类型', '操作'], columns: [i18n.t('common.name'), i18n.t('k8s.column.namespace'), i18n.t('common.type'), i18n.t('common.actions')],
renderRow: (s, opts) => ( renderRow: (s, opts) => (
<TableRow key={s.name} className="border-[var(--dg-border)] hover:bg-[var(--dg-bg-tertiary)]/30"> <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> <TableCell className="font-medium text-[var(--dg-text-primary)]">{s.name}</TableCell>
@@ -173,8 +175,8 @@ const RESOURCE_CONFIG: Record<ResourceType, {
), ),
}, },
hpas: { hpas: {
title: 'HPAs', subtitle: '水平自动伸缩', icon: Activity, title: 'HPAs', subtitle: i18n.t('kubernetes.namespaceresourcepage.s9abc8d'), icon: Activity,
columns: ['名称', '命名空间', '目标', '最小/最大', 'CPU%', 'Mem%'], 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) => ( renderRow: (h, _opts) => (
<TableRow key={h.name} className="border-[var(--dg-border)] hover:bg-[var(--dg-bg-tertiary)]/30"> <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> <TableCell className="font-medium text-[var(--dg-text-primary)]">{h.name}</TableCell>
@@ -187,21 +189,21 @@ const RESOURCE_CONFIG: Record<ResourceType, {
), ),
}, },
cronjobs: { cronjobs: {
title: 'CronJobs', subtitle: '定时任务', icon: Clock, title: 'CronJobs', subtitle: i18n.t('menu.cronJobs'), icon: Clock,
columns: ['名称', '命名空间', '调度', '状态', '上次执行'], 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) => ( renderRow: (cj) => (
<TableRow key={cj.name} className="border-[var(--dg-border)] hover:bg-[var(--dg-bg-tertiary)]/30"> <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 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><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 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> <TableCell className="text-sm text-[var(--dg-text-secondary)]">{cj.last_schedule || '-'}</TableCell>
</TableRow> </TableRow>
), ),
}, },
pvcs: { pvcs: {
title: '存储卷声明', subtitle: 'PersistentVolumeClaim', icon: Boxes, title: i18n.t('kubernetes.namespaceresourcepage.s18c900'), subtitle: 'PersistentVolumeClaim', icon: Boxes,
columns: ['名称', '命名空间', '状态', '大小', 'StorageClass', '操作'], 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) => ( renderRow: (p, opts) => (
<TableRow key={p.name} className="border-[var(--dg-border)] hover:bg-[var(--dg-bg-tertiary)]/30"> <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> <TableCell className="font-medium text-[var(--dg-text-primary)]">{p.name}</TableCell>
@@ -214,8 +216,8 @@ const RESOURCE_CONFIG: Record<ResourceType, {
), ),
}, },
statefulsets: { statefulsets: {
title: 'StatefulSets', subtitle: '有状态应用', icon: Boxes, title: 'StatefulSets', subtitle: i18n.t('kubernetes.namespaceresourcepage.sbfeb44'), icon: Boxes,
columns: ['名称', '命名空间', '副本', '就绪', '镜像'], 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) => ( 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)}> <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> <TableCell className="font-medium text-[var(--dg-text-primary)]">{s.name}</TableCell>
@@ -227,8 +229,8 @@ const RESOURCE_CONFIG: Record<ResourceType, {
), ),
}, },
daemonsets: { daemonsets: {
title: 'DaemonSets', subtitle: '守护进程集', icon: Boxes, title: 'DaemonSets', subtitle: i18n.t('kubernetes.namespaceresourcepage.se1c074'), icon: Boxes,
columns: ['名称', '命名空间', '期望', '当前', '就绪', '镜像'], 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) => ( 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)}> <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> <TableCell className="font-medium text-[var(--dg-text-primary)]">{d.name}</TableCell>
@@ -241,8 +243,8 @@ const RESOURCE_CONFIG: Record<ResourceType, {
), ),
}, },
serviceaccounts: { serviceaccounts: {
title: 'ServiceAccounts', subtitle: '服务账号(RBAC 身份标识)', icon: Shield, title: 'ServiceAccounts', subtitle: i18n.t('kubernetes.namespaceresourcepage.s645c9a'), icon: Shield,
columns: ['名称', '命名空间', 'Secret数', '镜像拉取凭证', '创建时间', '操作'], 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) => ( renderRow: (sa, opts) => (
<TableRow key={sa.name} className="border-[var(--dg-border)] hover:bg-[var(--dg-bg-tertiary)]/30"> <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> <TableCell className="font-medium text-[var(--dg-text-primary)]">{sa.name}</TableCell>
@@ -253,15 +255,15 @@ const RESOURCE_CONFIG: Record<ResourceType, {
</TableCell> </TableCell>
<TableCell className="text-xs text-[var(--dg-text-muted)]">{sa.age || '-'}</TableCell> <TableCell className="text-xs text-[var(--dg-text-muted)]">{sa.age || '-'}</TableCell>
<TableCell onClick={(e) => e.stopPropagation()}> <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> onClick={() => opts.onYaml?.(sa.name)}><FileCode className="h-3.5 w-3.5" /></Button>
</TableCell> </TableCell>
</TableRow> </TableRow>
), ),
}, },
roles: { roles: {
title: 'Roles', subtitle: '命名空间级角色权限(RBAC)', icon: Shield, title: 'Roles', subtitle: i18n.t('kubernetes.namespaceresourcepage.s8905a6'), icon: Shield,
columns: ['名称', '命名空间', '规则数', '权限范围', '创建时间', '操作'], 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) => { renderRow: (r, opts) => {
const verbs = r.verbs || []; const verbs = r.verbs || [];
const resources = r.resources || []; 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 className="text-xs text-[var(--dg-text-muted)]">{r.age || '-'}</TableCell>
<TableCell onClick={(e) => e.stopPropagation()}> <TableCell onClick={(e) => e.stopPropagation()}>
<div className="flex items-center gap-0.5"> <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> 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> onClick={() => opts.onEdit?.(r.name)}><Pencil className="h-3.5 w-3.5" /></Button>
</div> </div>
</TableCell> </TableCell>
@@ -292,8 +294,8 @@ const RESOURCE_CONFIG: Record<ResourceType, {
}, },
}, },
rolebindings: { rolebindings: {
title: 'RoleBindings', subtitle: '角色绑定关系(RBAC 授权)', icon: Shield, title: 'RoleBindings', subtitle: i18n.t('kubernetes.namespaceresourcepage.sca10fe'), icon: Shield,
columns: ['名称', '命名空间', '角色引用', '绑定主体', '创建时间', '操作'], 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) => { renderRow: (rb, opts) => {
const subjects = rb.subjects || []; const subjects = rb.subjects || [];
const subjStr = subjects.length > 3 ? subjects.slice(0, 3).join(', ') + ` +${subjects.length - 3}` : subjects.join(', '); 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 className="text-xs text-[var(--dg-text-muted)]">{rb.age || '-'}</TableCell>
<TableCell onClick={(e) => e.stopPropagation()}> <TableCell onClick={(e) => e.stopPropagation()}>
<div className="flex items-center gap-0.5"> <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> 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> onClick={() => opts.onEdit?.(rb.name)}><Pencil className="h-3.5 w-3.5" /></Button>
</div> </div>
</TableCell> </TableCell>
@@ -325,6 +327,7 @@ const RESOURCE_CONFIG: Record<ResourceType, {
}; };
export default function NamespaceResourcePage() { export default function NamespaceResourcePage() {
const { t } = useTranslation();
const { clusterCode, namespace } = useParams<{ clusterCode: string; namespace: string }>(); const { clusterCode, namespace } = useParams<{ clusterCode: string; namespace: string }>();
const location = useLocation(); const location = useLocation();
const navigate = useNavigate(); const navigate = useNavigate();
@@ -439,26 +442,26 @@ export default function NamespaceResourcePage() {
if (!clusterCode || !namespace) return; if (!clusterCode || !namespace) return;
try { try {
await kubernetesApi.exportNamespaceResources(clusterCode, namespace); await kubernetesApi.exportNamespaceResources(clusterCode, namespace);
toast({ title: '导出完成', description: `${namespace} 资源 YAML 已开始下载` }); toast({ title: t('common.exportComplete'), description: t('kubernetes.namespaceresourcepage.sadafd4', { namespace: namespace }) });
} catch (e) { } 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 // Pod 删除 // Logan.Li
const handleDeletePod = async (p: any) => { const handleDeletePod = async (p: any) => {
const ok = await confirm({ const ok = await confirm({
title: '删除 Pod', title: t('kubernetes.pod.deletePod'),
description: '确认删除 Pod "' + (p.name || '') + '"?操作不可恢复。', description: t('kubernetes.namespaceresourcepage.sc5bb25') + (p.name || '') + t('kubernetes.namespaceresourcepage.s3ec1f4'),
confirmText: '删除', confirmText: t('common.delete'),
}); });
if (!ok) return; if (!ok) return;
try { try {
await kubernetesApi.deletePod(clusterCode || '', namespace || '', p.name); await kubernetesApi.deletePod(clusterCode || '', namespace || '', p.name);
toast({ title: 'Pod 已删除' }); toast({ title: t('kubernetes.pod.deleted') });
loadData(); loadData();
} catch (e) { } 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 = ( const searchToolbar = (
<div className="relative w-56 flex-1 min-w-[200px] max-w-xs"> <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" /> <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> </div>
); );
@@ -482,11 +485,11 @@ export default function NamespaceResourcePage() {
actions={( actions={(
<> <>
<Select value={clusterCode || ''} onValueChange={(v) => navigate(`/kubernetes/${v}/namespace/${namespace || 'default'}/${type}`)}> <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> <SelectContent>{clusters.map((c) => <SelectItem key={c.id} value={c.code || String(c.id)}>{c.name}</SelectItem>)}</SelectContent>
</Select> </Select>
<Select value={namespace || ''} onValueChange={(v) => navigate(`/kubernetes/${clusterCode}/namespace/${v}/${type}`)}> <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> <SelectContent className="max-h-[300px]">{namespaces.map((ns) => <SelectItem key={ns} value={ns}>{ns}</SelectItem>)}</SelectContent>
</Select> </Select>
<Button variant="outline" size="sm" className="dg-btn-secondary" onClick={loadData} disabled={loading}> <Button variant="outline" size="sm" className="dg-btn-secondary" onClick={loadData} disabled={loading}>
@@ -495,16 +498,16 @@ export default function NamespaceResourcePage() {
</Button> </Button>
{BULK_EXPORT_TYPES.includes(type) && ( {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 <Download className="h-3 w-3 mr-1" />CSV
</Button> </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 <Download className="h-3 w-3 mr-1" />JSON
</Button> </Button>
</> </>
)} )}
{EXPORT_YAML_TYPES.includes(type) && ( {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 <Download className="h-3 w-3 mr-1" />导出YAML
</Button> </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> <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> <TableBody>
{loading ? ( {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 ? ( ) : 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> <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 className="p-5 space-y-5">
{/* 基本信息 */} {/* 基本信息 */}
<div> <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 p = podDetail;
const labels = p.labels || p.metadata?.labels || {}; const labels = p.labels || p.metadata?.labels || {};
@@ -609,23 +612,23 @@ export default function NamespaceResourcePage() {
return ( return (
<div className="grid grid-cols-2 gap-x-6 gap-y-2.5"> <div className="grid grid-cols-2 gap-x-6 gap-y-2.5">
<div> <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> <p className="text-sm text-[var(--dg-text-primary)] font-mono">{p.name || '-'}</p>
</div> </div>
<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> <p className="text-sm text-[var(--dg-text-primary)]">{p.namespace || '-'}</p>
</div> </div>
<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><Badge className={statusMap[st] || 'bg-[var(--dg-text-muted)]/20 text-[var(--dg-text-secondary)]'}>{st}</Badge></div>
</div> </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> <p className="text-sm text-[var(--dg-text-primary)]">{created ? new Date(created).toLocaleString('zh-CN') : '-'}</p>
</div> </div>
<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> <p className="text-sm text-[var(--dg-text-primary)]">{p.node_name || p.node || '-'}</p>
</div> </div>
<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> <p className="text-sm text-[var(--dg-text-primary)] font-mono">{p.ip || p.pod_ip || '-'}</p>
</div> </div>
<div className="col-span-2"> <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"> <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.keys(labels).length === 0 ? <span className="text-xs text-[var(--dg-text-muted)]">-</span>
: Object.entries(labels).map(([k, v]) => ( : Object.entries(labels).map(([k, v]) => (
@@ -643,7 +646,7 @@ export default function NamespaceResourcePage() {
</div> </div>
</div> </div>
<div className="col-span-2"> <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"> <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.keys(annotations).length === 0 ? <span className="text-xs text-[var(--dg-text-muted)]">-</span>
: Object.entries(annotations).slice(0, 6).map(([k, v]) => ( : Object.entries(annotations).slice(0, 6).map(([k, v]) => (
@@ -659,19 +662,19 @@ export default function NamespaceResourcePage() {
{/* 现状详情(Conditions) */} {/* 现状详情(Conditions) */}
<div> <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 || []; 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 ( return (
<Table> <Table>
<TableHeader> <TableHeader>
<TableRow className="border-[var(--dg-border)] hover:bg-transparent"> <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">{t('common.type')}</TableHead>
<TableHead className="text-[var(--dg-text-muted)] text-xs">状态</TableHead> <TableHead className="text-[var(--dg-text-muted)] text-xs">{t('common.status')}</TableHead>
<TableHead className="text-[var(--dg-text-muted)] text-xs">更新时间</TableHead> <TableHead className="text-[var(--dg-text-muted)] text-xs">{t('common.updatedAt')}</TableHead>
<TableHead className="text-[var(--dg-text-muted)] text-xs">原因</TableHead> <TableHead className="text-[var(--dg-text-muted)] text-xs">{t('kubernetes.event.eventReason')}</TableHead>
<TableHead className="text-[var(--dg-text-muted)] text-xs">消息</TableHead> <TableHead className="text-[var(--dg-text-muted)] text-xs">{t('kubernetes.event.eventMessage')}</TableHead>
</TableRow> </TableRow>
</TableHeader> </TableHeader>
<TableBody> <TableBody>
@@ -702,7 +705,7 @@ export default function NamespaceResourcePage() {
</div> </div>
</div> </div>
<div className="flex justify-end px-5 py-3 border-t border-[var(--dg-border)]"> <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> </div>
</div> </div>
@@ -22,8 +22,10 @@ import {
import { kubernetesApi } from '@/api'; import { kubernetesApi } from '@/api';
import { PageShell } from '@/components/layout/PageShell'; import { PageShell } from '@/components/layout/PageShell';
import { useTranslation } from 'react-i18next';
export default function NodeDetailPage() { export default function NodeDetailPage() {
const { t } = useTranslation();
const { clusterCode, nodeName } = useParams<{ clusterCode: string; nodeName: string }>(); const { clusterCode, nodeName } = useParams<{ clusterCode: string; nodeName: string }>();
const navigate = useNavigate(); const navigate = useNavigate();
const [data, setData] = useState<any>(null); const [data, setData] = useState<any>(null);
@@ -95,11 +97,11 @@ export default function NodeDetailPage() {
return ( return (
<PageShell <PageShell
variant="default" variant="default"
title={nodeName || '节点详情'} title={nodeName || t('kubernetes.nodedetailpage.sb88b98')}
subtitle={nodeSubtitle || clusterCode} subtitle={nodeSubtitle || clusterCode}
icon={<Server className="h-5 w-5" />} icon={<Server className="h-5 w-5" />}
loading={loading && !data} loading={loading && !data}
loadingLabel="加载节点详情..." loadingLabel=t('kubernetes.nodedetailpage.sfdff61')
actions={( actions={(
<> <>
<Button variant="outline" size="sm" className="dg-btn-secondary" onClick={() => navigate(-1)}> <Button variant="outline" size="sm" className="dg-btn-secondary" onClick={() => navigate(-1)}>
@@ -143,7 +145,7 @@ export default function NodeDetailPage() {
</h2> </h2>
<div className="space-y-2 text-xs"> <div className="space-y-2 text-xs">
<div className="flex items-center justify-between py-1.5 border-b border-[var(--dg-border)]/50"> <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> <span className="text-[var(--dg-text-secondary)] font-mono">{data.container_runtime || '-'}</span>
</div> </div>
<div className="flex items-center justify-between py-1.5 border-b border-[var(--dg-border)]/50"> <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> <span className="text-[var(--dg-text-secondary)] font-mono">{data.kubelet_version || '-'}</span>
</div> </div>
<div className="flex items-center justify-between py-1.5 border-b border-[var(--dg-border)]/50"> <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> <span className="text-[var(--dg-text-secondary)]">{data.os_image || '-'}</span>
</div> </div>
<div className="flex items-center justify-between py-1.5 border-b border-[var(--dg-border)]/50"> <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> <span className="text-[var(--dg-text-secondary)] font-mono">{data.kernel_version || '-'}</span>
</div> </div>
<div className="flex items-center justify-between py-1.5 border-b border-[var(--dg-border)]/50"> <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> <span className="text-[var(--dg-text-secondary)] font-mono">{data.architecture || '-'}</span>
</div> </div>
<div className="flex items-center justify-between py-1.5 border-b border-[var(--dg-border)]/50"> <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> <span className="text-[var(--dg-text-secondary)]">{data.creation_time ? new Date(data.creation_time).toLocaleString('zh-CN') : '-'}</span>
</div> </div>
<div className="flex items-center justify-between py-1.5"> <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"> <div className="space-y-4 mt-4">
{/* CPU allocation (requested vs allocatable) */} {/* CPU allocation (requested vs allocatable) */}
<ResourceBar <ResourceBar
label="CPU 已分配" label=t('kubernetes.nodedetailpage.s7c3900')
used={`${(data.cpu_request_m / 1000).toFixed(2)} 核`} used={t('kubernetes.nodedetailpage.s8c635b', { (data.cpu_request_m / 1000).toFixed(2): (data.cpu_request_m / 1000).toFixed(2) })}
total={`${data.cpu_allocatable} 核`} total={t('kubernetes.nodedetailpage.s3523f6', { data.cpu_allocatable: data.cpu_allocatable })}
unit="" unit=""
pct={data.cpu_alloc_pct} pct={data.cpu_alloc_pct}
color="dg-text-green" color="dg-text-green"
@@ -193,9 +195,9 @@ export default function NodeDetailPage() {
{/* CPU real usage (from metrics) */} {/* CPU real usage (from metrics) */}
{data.cpu_usage_m && ( {data.cpu_usage_m && (
<ResourceBar <ResourceBar
label="CPU 实时使用" label=t('kubernetes.nodedetailpage.s1ce996')
used={data.cpu_usage_m} used={data.cpu_usage_m}
total={`${data.cpu_capacity} 核`} total={t('kubernetes.nodedetailpage.s2d6586', { data.cpu_capacity: data.cpu_capacity })}
unit="" unit=""
pct={(parseFloat(data.cpu_usage_m.replace('m', '')) / (data.cpu_capacity * 1000)) * 100} pct={(parseFloat(data.cpu_usage_m.replace('m', '')) / (data.cpu_capacity * 1000)) * 100}
color="dg-text-blue" color="dg-text-blue"
@@ -203,7 +205,7 @@ export default function NodeDetailPage() {
)} )}
{/* Memory allocation */} {/* Memory allocation */}
<ResourceBar <ResourceBar
label="内存已分配" label=t('kubernetes.nodedetailpage.sccf1cf')
used={`${data.mem_request_mi} Mi`} used={`${data.mem_request_mi} Mi`}
total={`${data.mem_allocatable_mb} Mi`} total={`${data.mem_allocatable_mb} Mi`}
unit="" unit=""
@@ -213,7 +215,7 @@ export default function NodeDetailPage() {
{/* Memory real usage */} {/* Memory real usage */}
{data.mem_usage_mi && ( {data.mem_usage_mi && (
<ResourceBar <ResourceBar
label="内存实时使用" label=t('kubernetes.nodedetailpage.s841b8a')
used={data.mem_usage_mi} used={data.mem_usage_mi}
total={`${data.mem_capacity_mb} Mi`} total={`${data.mem_capacity_mb} Mi`}
unit="" unit=""
@@ -223,7 +225,7 @@ export default function NodeDetailPage() {
)} )}
{/* Pod allocation */} {/* Pod allocation */}
<ResourceBar <ResourceBar
label="Pod 数量" label=t('kubernetes.nodedetailpage.s55edf2')
used={`${data.pod_count}`} used={`${data.pod_count}`}
total={`${data.pod_allocatable}`} total={`${data.pod_allocatable}`}
unit="" unit=""
@@ -234,15 +236,15 @@ export default function NodeDetailPage() {
{/* Capacity vs Allocatable raw */} {/* 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="mt-4 pt-3 border-t border-[var(--dg-border)]/50 space-y-1 text-[11px] dg-text-muted">
<div className="flex justify-between"> <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> <span className="font-mono">{data.cpu_capacity} / {data.cpu_allocatable} 核</span>
</div> </div>
<div className="flex justify-between"> <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> <span className="font-mono">{data.mem_capacity_mb} / {data.mem_allocatable_mb} Mi</span>
</div> </div>
<div className="flex justify-between"> <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> <span className="font-mono">{data.pod_capacity} / {data.pod_allocatable}</span>
</div> </div>
</div> </div>
@@ -259,7 +261,7 @@ export default function NodeDetailPage() {
<CheckCircle2 className="h-4 w-4 dg-text-blue" />节点条件 <CheckCircle2 className="h-4 w-4 dg-text-blue" />节点条件
</h2> </h2>
{(!data.conditions || data.conditions.length === 0) ? ( {(!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"> <div className="space-y-2">
{data.conditions.map(( cond: any, i: number) => ( {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) <AlertTriangle className="h-4 w-4 dg-text-yellow" />污点 (Taints)
</h2> </h2>
{(!data.taints || data.taints.length === 0) ? ( {(!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"> <div className="space-y-2">
{data.taints.map(( t: any, i: number) => ( {data.taints.map(( t: any, i: number) => (
@@ -333,18 +335,18 @@ export default function NodeDetailPage() {
</h2> </h2>
</div> </div>
{(!data.pods || data.pods.length === 0) ? ( {(!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> <Table>
<TableHeader> <TableHeader>
<TableRow className="border-[var(--dg-border)] hover:bg-transparent"> <TableRow className="border-[var(--dg-border)] hover:bg-transparent">
<TableHead className="dg-text-secondary">命名空间</TableHead> <TableHead className="dg-text-secondary">{t('k8s.column.namespace')}</TableHead>
<TableHead className="dg-text-secondary">名称</TableHead> <TableHead className="dg-text-secondary">{t('common.name')}</TableHead>
<TableHead className="dg-text-secondary">状态</TableHead> <TableHead className="dg-text-secondary">{t('common.status')}</TableHead>
<TableHead className="dg-text-secondary">IP</TableHead> <TableHead className="dg-text-secondary">IP</TableHead>
<TableHead className="dg-text-secondary">CPU 请求</TableHead> <TableHead className="dg-text-secondary">{t('kubernetes.node.cpuRequests')}</TableHead>
<TableHead className="dg-text-secondary">内存请求</TableHead> <TableHead className="dg-text-secondary">{t('kubernetes.node.memoryRequests')}</TableHead>
<TableHead className="dg-text-secondary">重启次数</TableHead> <TableHead className="dg-text-secondary">{t('k8s.column.restartCount')}</TableHead>
</TableRow> </TableRow>
</TableHeader> </TableHeader>
<TableBody> <TableBody>
@@ -22,6 +22,7 @@ import {
import { cn } from '@/lib/utils'; import { cn } from '@/lib/utils';
import { kubernetesApi } from '@/api'; import { kubernetesApi } from '@/api';
import { useToast } from '@/hooks/use-toast'; import { useToast } from '@/hooks/use-toast';
import { useTranslation } from 'react-i18next';
export interface PodExecTerminalProps { export interface PodExecTerminalProps {
open: boolean; open: boolean;
@@ -49,6 +50,7 @@ export function PodExecTerminal({
containers = [], containers = [],
initialContainer, initialContainer,
}: PodExecTerminalProps) { }: PodExecTerminalProps) {
const { t } = useTranslation();
const { toast } = useToast(); const { toast } = useToast();
const containerRef = useRef<HTMLDivElement>(null); const containerRef = useRef<HTMLDivElement>(null);
const termRef = useRef<XTerm | null>(null); const termRef = useRef<XTerm | null>(null);
@@ -92,7 +94,7 @@ export function PodExecTerminal({
setConnState('connecting'); setConnState('connecting');
term.clear(); 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); 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') { if (msg.status === 0 && typeof msg.data === 'string') {
term.write(msg.data); term.write(msg.data);
} else if (msg.status === 2 || msg.error) { } 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') { 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; errorShownRef.current = true;
return; return;
} }
@@ -132,14 +134,14 @@ export function PodExecTerminal({
ws.onclose = (_ev) => { ws.onclose = (_ev) => {
setConnState((s) => (s === 'error' ? s : 'closed')); setConnState((s) => (s === 'error' ? s : 'closed'));
if (!errorShownRef.current) { if (!errorShownRef.current) {
term.write('\r\n\x1b[33m[连接已关闭]\x1b[0m\r\n'); term.write(t('kubernetes.podexecterminal.s123d94'));
} }
}; };
ws.onerror = (ev) => { ws.onerror = (ev) => {
console.error('[PodExec:connect] WS error event fired, readyState=', ws.readyState, 'type=', ev.type); console.error('[PodExec:connect] WS error event fired, readyState=', ws.readyState, 'type=', ev.type);
setConnState('error'); setConnState('error');
term.write('\r\n\x1b[31m[连接发生错误]\x1b[0m\r\n'); term.write(t('kubernetes.podexecterminal.sc81077'));
}; };
}, [clusterId, namespace, podName, container, shell]); }, [clusterId, namespace, podName, container, shell]);
@@ -266,10 +268,10 @@ export function PodExecTerminal({
const statusColor = connState === 'connected' ? 'bg-emerald-400' const statusColor = connState === 'connected' ? 'bg-emerald-400'
: connState === 'error' ? 'bg-red-400' : connState === 'error' ? 'bg-red-400'
: connState === 'closed' ? 'bg-[var(--dg-bg-active)]' : 'bg-amber-400'; : connState === 'closed' ? 'bg-[var(--dg-bg-active)]' : 'bg-amber-400';
const statusText = connState === 'connected' ? '已连接' const statusText = connState === 'connected' ? t('common.connected')
: connState === 'connecting' ? '连接中' : connState === 'connecting' ? t('common.connecting')
: connState === 'error' ? '连接错误' : connState === 'error' ? t('kubernetes.podexecterminal.sd52359')
: connState === 'closed' ? '已断开' : '空闲'; : connState === 'closed' ? t('common.disconnected') : t('common.idle');
const handleTerminalClick = useCallback(() => { const handleTerminalClick = useCallback(() => {
try { termRef.current?.focus(); } catch { /* noop */ } 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' }} style={fullscreen ? { maxWidth: '100vw', width: '100vw', height: '100vh' } : { maxWidth: '960px', width: '92vw' }}
> >
<DialogTitle className="sr-only">exec — {podName}</DialogTitle> <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"> <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}> <Select value={container} onValueChange={setContainer}>
<SelectTrigger className="h-8 w-[150px] text-xs bg-[var(--dg-bg-hover)] border-[var(--dg-border)]"> <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)]" /> <Box className="h-3 w-3 mr-1 text-[var(--dg-text-muted)]" />
<SelectValue placeholder="容器" /> <SelectValue placeholder=t('k8s.pods.containers') />
</SelectTrigger> </SelectTrigger>
<SelectContent>{containers.map((c) => <SelectItem key={c} value={c}>{c}</SelectItem>)}</SelectContent> <SelectContent>{containers.map((c) => <SelectItem key={c} value={c}>{c}</SelectItem>)}</SelectContent>
</Select> </Select>
@@ -317,13 +319,13 @@ export function PodExecTerminal({
<SelectContent>{SHELLS.map(s => <SelectItem key={s.value} value={s.value}>{s.label}</SelectItem>)}</SelectContent> <SelectContent>{SHELLS.map(s => <SelectItem key={s.value} value={s.value}>{s.label}</SelectItem>)}</SelectContent>
</Select> </Select>
<Button variant="ghost" size="sm" className="h-8 px-2 text-[var(--dg-text-secondary)] hover:text-[var(--dg-text-primary)]" <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" /> <RotateCw className="h-3.5 w-3.5" />
</Button> </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" />} {fullscreen ? <Minimize2 className="h-4 w-4" /> : <Maximize2 className="h-4 w-4" />}
</button> </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" /> <X className="h-4 w-4" />
</button> </button>
</div> </div>
@@ -18,6 +18,7 @@ import {
HardDrive, HardDrive,
} from 'lucide-react'; } from 'lucide-react';
import type { JsonData } from '@/types/common'; import type { JsonData } from '@/types/common';
import { useTranslation } from 'react-i18next';
export interface PodFileBrowserProps { export interface PodFileBrowserProps {
@@ -40,6 +41,7 @@ interface FileEntry {
export function PodFileBrowser({ export function PodFileBrowser({
open, onOpenChange, clusterCode, namespace, podName, containers = [], initialContainer, open, onOpenChange, clusterCode, namespace, podName, containers = [], initialContainer,
}: PodFileBrowserProps) { }: PodFileBrowserProps) {
const { t } = useTranslation();
const [container, setContainer] = useState(initialContainer || containers[0] || ''); const [container, setContainer] = useState(initialContainer || containers[0] || '');
const [currentPath, setCurrentPath] = useState('/'); const [currentPath, setCurrentPath] = useState('/');
const [entries, setEntries] = useState<FileEntry[]>([]); const [entries, setEntries] = useState<FileEntry[]>([]);
@@ -67,7 +69,7 @@ export function PodFileBrowser({
setEntries(list); setEntries(list);
setCurrentPath(path); setCurrentPath(path);
} catch (e) { } catch (e) {
setError((e as JsonData).message || '加载文件列表失败'); setError((e as JsonData).message || t('kubernetes.podfilebrowser.s78d4a7'));
setEntries([]); setEntries([]);
} finally { } finally {
setLoading(false); setLoading(false);
@@ -117,7 +119,7 @@ export function PodFileBrowser({
const text = await kubernetesApi.readPodFileText(clusterCode, namespace, podName, filePath, container || undefined); const text = await kubernetesApi.readPodFileText(clusterCode, namespace, podName, filePath, container || undefined);
setPreview({ file: fileName, content: text }); setPreview({ file: fileName, content: text });
} catch (e) { } 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); await kubernetesApi.uploadPodFile(clusterCode, namespace, podName, currentPath, file, container || undefined);
loadFiles(currentPath); loadFiles(currentPath);
} catch (err) { } catch (err) {
setError(`上传失败: ${(err as JsonData).message}`); setError(t('kubernetes.podfilebrowser.s560770', { (err as JsonData).message: (err as JsonData).message }));
} finally { } finally {
setUploading(false); setUploading(false);
if (fileInputRef.current) fileInputRef.current.value = ''; if (fileInputRef.current) fileInputRef.current.value = '';
@@ -225,7 +227,7 @@ export function PodFileBrowser({
{loading ? ( {loading ? (
<div className="flex items-center justify-center h-32"><Loader2 className="h-5 w-5 animate-spin dg-text-muted" /></div> <div className="flex items-center justify-center h-32"><Loader2 className="h-5 w-5 animate-spin dg-text-muted" /></div>
) : entries.length === 0 ? ( ) : 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"> <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) => ( {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 <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" 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); }} onClick={(e) => { e.stopPropagation(); handleDownload(entry.name); }}
title="下载" title=t('common.download')
> >
<Download className="h-3 w-3" /> <Download className="h-3 w-3" />
</Button> </Button>
@@ -271,7 +273,7 @@ export function PodFileBrowser({
</div> </div>
<div className="flex-1 overflow-auto p-3"> <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"> <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> </pre>
</div> </div>
</div> </div>
@@ -22,6 +22,8 @@ import { cn } from '@/lib/utils';
import { kubernetesApi } from '@/api'; import { kubernetesApi } from '@/api';
import { useToast } from '@/hooks/use-toast'; import { useToast } from '@/hooks/use-toast';
import type { JsonData } from '@/types/common'; import type { JsonData } from '@/types/common';
import { useTranslation } from 'react-i18next';
import i18n from '@/i18n';
/** /**
* 增强版 Pod 日志查看器 — 增强 DeploymentDetail 的日志体验 * 增强版 Pod 日志查看器 — 增强 DeploymentDetail 的日志体验
@@ -51,10 +53,10 @@ interface PodLogsViewerProps {
} }
const TAIL_OPTIONS = [ const TAIL_OPTIONS = [
{ value: '100', label: '最近 100 行' }, { value: '100', label: i18n.t('kubernetes.podlogsviewer.s58b02a') },
{ value: '500', label: '最近 500 行' }, { value: '500', label: i18n.t('kubernetes.podlogsviewer.s9a0368') },
{ value: '1000', label: '最近 1000 行' }, { value: '1000', label: i18n.t('kubernetes.podlogsviewer.sf89a33') },
{ value: '0', label: '全部' }, { value: '0', label: i18n.t('common.all') },
]; ];
// 环形缓冲大小(借鉴 opsx-agent) // 环形缓冲大小(借鉴 opsx-agent)
@@ -74,6 +76,7 @@ export function PodLogsViewer({
containers = [], containers = [],
initialContainer, initialContainer,
}: PodLogsViewerProps) { }: PodLogsViewerProps) {
const { t } = useTranslation();
const { toast } = useToast(); const { toast } = useToast();
const [fullscreen, setFullscreen] = useState(false); 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')); const arr = typeof raw === 'string' ? raw.split('\n') : (Array.isArray(raw) ? raw : String(raw).split('\n'));
appendLines(arr); appendLines(arr);
} catch (e) { } catch (e) {
appendLines([`\x1b[31m[获取日志失败: ${e?.message || String(e)}]\x1b[0m`]); appendLines([t('kubernetes.podlogsviewer.s69828a', { e?.message || String(e): e?.message || String(e) })]);
toast({ title: '获取日志失败', description: e?.message || String(e), variant: 'destructive' }); toast({ title: t('kubernetes.podlogsviewer.sc93f33'), description: e?.message || String(e), variant: 'destructive' });
} finally { } finally {
setLoading(false); setLoading(false);
} }
@@ -225,12 +228,12 @@ export function PodLogsViewer({
} }
} }
flush(); // 收尾 flush(); // 收尾
appendLines(['\x1b[33m— 流式结束 —\x1b[0m']); appendLines([t('kubernetes.podlogsviewer.s4f0e17')]);
} catch (e) { } catch (e) {
if (e?.name === 'AbortError') { if (e?.name === 'AbortError') {
appendLines(['\x1b[33m— 已停止 —\x1b[0m']); appendLines([t('kubernetes.podlogsviewer.s1ca901')]);
} else { } else {
appendLines([`\x1b[31m[流式连接中断: ${e?.message || String(e)}]\x1b[0m`]); appendLines([t('kubernetes.podlogsviewer.s11530d', { e?.message || String(e): e?.message || String(e) })]);
} }
} finally { } finally {
setStreaming(false); setStreaming(false);
@@ -275,7 +278,7 @@ export function PodLogsViewer({
a.download = filename; a.download = filename;
a.click(); a.click();
URL.revokeObjectURL(a.href); URL.revokeObjectURL(a.href);
toast({ title: '已导出', description: filename }); toast({ title: t('kubernetes.podlogsviewer.s5c51c3'), description: filename });
}, [podName, container, previous, toast]); }, [podName, container, previous, toast]);
// 关键字过滤 // 关键字过滤
@@ -330,7 +333,7 @@ export function PodLogsViewer({
style={fullscreen ? { maxWidth: '100vw', width: '100vw', height: '100vh' } : { maxWidth: '1100px', width: '94vw' }} style={fullscreen ? { maxWidth: '100vw', width: '100vw', height: '100vh' } : { maxWidth: '1100px', width: '94vw' }}
> >
<DialogTitle className="sr-only">日志 — {podName}</DialogTitle> <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"> <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> <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)]" />} {loading && <Loader2 className="h-3 w-3 animate-spin text-[var(--dg-text-muted)]" />}
<span className="text-xs text-[var(--dg-text-muted)]"> <span className="text-xs text-[var(--dg-text-muted)]">
{streaming ? (paused ? '已暂停' : '实时跟踪') : '已停止'} · {matchedCount}{keyword ? `/${lineCount}` : ''} 行 {streaming ? (paused ? t('kubernetes.deployment.paused') : t('kubernetes.podlogsviewer.sd9c71f')) : t('common.stopped')} · {matchedCount}{keyword ? `/${lineCount}` : ''} 行
{lineCount >= RING_BUFFER_MAX && ' (缓冲已满)'} {lineCount >= RING_BUFFER_MAX && t('kubernetes.podlogsviewer.sf3280b')}
</span> </span>
</div> </div>
@@ -352,14 +355,14 @@ export function PodLogsViewer({
<button <button
onClick={() => setFullscreen(!fullscreen)} onClick={() => setFullscreen(!fullscreen)}
className="p-1.5 rounded hover:bg-[var(--dg-bg-hover)] text-[var(--dg-text-secondary)]" 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" />} {fullscreen ? <Minimize2 className="h-4 w-4" /> : <Maximize2 className="h-4 w-4" />}
</button> </button>
<button <button
onClick={handleClose} onClick={handleClose}
className="p-1.5 rounded hover:bg-[var(--dg-bg-hover)] text-[var(--dg-text-secondary)]" 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" /> <X className="h-4 w-4" />
</button> </button>
@@ -373,7 +376,7 @@ export function PodLogsViewer({
<Select value={container} onValueChange={setContainer}> <Select value={container} onValueChange={setContainer}>
<SelectTrigger className="h-8 w-[150px] text-xs bg-[var(--dg-bg-hover)] border-[var(--dg-border)]"> <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)]" /> <Box className="h-3 w-3 mr-1 text-[var(--dg-text-muted)]" />
<SelectValue placeholder="容器" /> <SelectValue placeholder=t('k8s.pods.containers') />
</SelectTrigger> </SelectTrigger>
<SelectContent> <SelectContent>
{containers.map((c) => ( {containers.map((c) => (
@@ -401,7 +404,7 @@ export function PodLogsViewer({
size="sm" 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)]')} 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)} onClick={() => setPrevious(!previous)}
title="查看上一次(崩溃)容器的日志" title=t('kubernetes.podlogsviewer.s76a2e6')
> >
<History className="h-3.5 w-3.5 mr-1" /> <History className="h-3.5 w-3.5 mr-1" />
previous previous
@@ -418,7 +421,7 @@ export function PodLogsViewer({
setSinceTime(v ? new Date(v).toISOString() : ''); 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)]" 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> </div>
@@ -430,7 +433,7 @@ export function PodLogsViewer({
<Input <Input
value={keyword} value={keyword}
onChange={(e) => setKeyword(e.target.value)} 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)]" className="h-8 w-[160px] pl-7 text-xs bg-[var(--dg-bg-hover)] border-[var(--dg-border)] text-[var(--dg-text-primary)]"
/> />
</div> </div>
@@ -440,7 +443,7 @@ export function PodLogsViewer({
variant="outline" size="sm" variant="outline" size="sm"
className="h-8 text-xs border-[var(--dg-border)] text-[var(--dg-text-secondary)]" className="h-8 text-xs border-[var(--dg-border)] text-[var(--dg-text-secondary)]"
onClick={handleDownload} onClick={handleDownload}
title="导出当前日志" title=t('kubernetes.podlogsviewer.s1a023d')
disabled={filteredLines.length === 0} disabled={filteredLines.length === 0}
> >
<Download className="h-3.5 w-3.5 mr-1" />导出 <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)]" className="h-8 text-xs border-[var(--dg-border)] text-[var(--dg-text-secondary)]"
onClick={fetchLogs} onClick={fetchLogs}
disabled={loading} disabled={loading}
title="重新拉取" title=t('kubernetes.podlogsviewer.s930b4e')
> >
<RefreshCw className={cn('h-3.5 w-3.5 mr-1', loading && 'animate-spin')} />刷新 <RefreshCw className={cn('h-3.5 w-3.5 mr-1', loading && 'animate-spin')} />刷新
</Button> </Button>
@@ -464,7 +467,7 @@ export function PodLogsViewer({
className="h-8 text-xs bg-emerald-600 hover:bg-emerald-700" className="h-8 text-xs bg-emerald-600 hover:bg-emerald-700"
onClick={startStream} onClick={startStream}
disabled={loading} disabled={loading}
title="实时跟踪(tail -f)" title=t('kubernetes.podlogsviewer.s0d519c')
> >
<Play className="h-3.5 w-3.5 mr-1" />实时 <Play className="h-3.5 w-3.5 mr-1" />实时
</Button> </Button>
@@ -474,16 +477,16 @@ export function PodLogsViewer({
variant="outline" size="sm" variant="outline" size="sm"
className={cn('h-8 text-xs', paused ? 'border-emerald-500 dg-text-green' : 'border-amber-500 dg-text-yellow')} className={cn('h-8 text-xs', paused ? 'border-emerald-500 dg-text-green' : 'border-amber-500 dg-text-yellow')}
onClick={() => setPaused(!paused)} 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 ? <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>
<Button <Button
variant="outline" size="sm" variant="outline" size="sm"
className="h-8 text-xs border-red-500 dg-text-red" className="h-8 text-xs border-red-500 dg-text-red"
onClick={stopStream} onClick={stopStream}
title="停止" title=t('common.stop')
> >
<Pause className="h-3.5 w-3.5 mr-1" />停止 <Pause className="h-3.5 w-3.5 mr-1" />停止
</Button> </Button>
@@ -510,7 +513,7 @@ export function PodLogsViewer({
{lineCount === 0 && !loading && ( {lineCount === 0 && !loading && (
<div className="flex flex-col items-center justify-center h-full text-[var(--dg-text-muted)]"> <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" /> <AlertCircle className="h-8 w-8 mb-2 opacity-50" />
<span>暂无日志</span> <span>{t('pipeline.noLog')}</span>
</div> </div>
)} )}
{loading && lineCount === 0 && ( {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> </button>
</div> </div>
</DialogContent> </DialogContent>
@@ -14,8 +14,10 @@ import { PageShell } from '@/components/layout/PageShell';
import { ContentPanel } from '@/components/layout/ContentPanel'; import { ContentPanel } from '@/components/layout/ContentPanel';
import { StatStrip } from '@/components/ui/stat-strip'; import { StatStrip } from '@/components/ui/stat-strip';
import type { JsonData } from '@/types/common'; import type { JsonData } from '@/types/common';
import { useTranslation } from 'react-i18next';
export default function PodMetricsPage() { export default function PodMetricsPage() {
const { t } = useTranslation();
const { clusterCode } = useParams<{ clusterCode: string }>(); const { clusterCode } = useParams<{ clusterCode: string }>();
const navigate = useNavigate(); const navigate = useNavigate();
const [loading, setLoading] = useState(false); const [loading, setLoading] = useState(false);
@@ -85,15 +87,15 @@ export default function PodMetricsPage() {
return ( return (
<PageShell <PageShell
variant="list" variant="list"
title="Pod 资源用量" title=t('kubernetes.podmetricspage.s94c067')
subtitle={clusterName ? `${clusterName} · 容器 CPU/内存实时指标` : '容器 CPU/内存实时指标'} subtitle={clusterName ? t('kubernetes.podmetricspage.sc3a5a8', { clusterName: clusterName }) : t('kubernetes.podmetricspage.s6dbb5e')}
icon={<Activity className="h-5 w-5" />} icon={<Activity className="h-5 w-5" />}
metrics={!loading ? ( metrics={!loading ? (
<StatStrip <StatStrip
items={[ items={[
{ label: 'Pod 数', value: metrics.length, color: 'muted' }, { label: t('kubernetes.node.podCount'), value: metrics.length, color: 'muted' },
{ label: '总 CPU', value: `${totalCPU}m`, color: 'blue' }, { label: t('kubernetes.podmetricspage.sac1fc3'), value: `${totalCPU}m`, color: 'blue' },
{ label: '总内存', value: `${totalMem.toFixed(0)}Mi`, color: 'green' }, { label: t('monitor.systemInfo.memTotal'), value: `${totalMem.toFixed(0)}Mi`, color: 'green' },
]} ]}
/> />
) : undefined} ) : undefined}
@@ -106,9 +108,9 @@ export default function PodMetricsPage() {
</SelectContent> </SelectContent>
</Select> </Select>
<Select value={selectedNs} onValueChange={setSelectedNs}> <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> <SelectContent>
<SelectItem value="all">所有命名空间</SelectItem> <SelectItem value="all">{t('kubernetes.podmetricspage.s58173b')}</SelectItem>
{namespaces.map(n => <SelectItem key={n} value={n}>{n}</SelectItem>)} {namespaces.map(n => <SelectItem key={n} value={n}>{n}</SelectItem>)}
</SelectContent> </SelectContent>
</Select> </Select>
@@ -123,8 +125,8 @@ export default function PodMetricsPage() {
<Table> <Table>
<TableHeader><TableRow className="border-[var(--dg-border)] hover:bg-transparent"> <TableHeader><TableRow className="border-[var(--dg-border)] hover:bg-transparent">
<TableHead className="dg-text-secondary">Pod</TableHead> <TableHead className="dg-text-secondary">Pod</TableHead>
<TableHead className="dg-text-secondary">命名空间</TableHead> <TableHead className="dg-text-secondary">{t('k8s.column.namespace')}</TableHead>
<TableHead className="dg-text-secondary">容器</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"><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> <TableHead className="dg-text-secondary"><HardDrive className="h-3 w-3 inline mr-1" />Memory</TableHead>
</TableRow></TableHeader> </TableRow></TableHeader>
@@ -17,6 +17,7 @@ import { YamlEditorToolbar } from './YamlEditorToolbar';
import { YamlCodeMirror } from './YamlCodeMirror'; import { YamlCodeMirror } from './YamlCodeMirror';
import { getYamlResourceConfig, yamlDownloadFilename } from './k8s-yaml-resource-config'; import { getYamlResourceConfig, yamlDownloadFilename } from './k8s-yaml-resource-config';
import { downloadYamlFile } from '@/utils/export'; import { downloadYamlFile } from '@/utils/export';
import { useTranslation } from 'react-i18next';
interface ResourceVisualEditorProps { interface ResourceVisualEditorProps {
clusterCode: string; clusterCode: string;
@@ -30,6 +31,7 @@ interface ResourceVisualEditorProps {
} }
export function ResourceVisualEditor({ clusterCode, namespace, resource, name, onClose, onSaved, isCreate = false }: ResourceVisualEditorProps) { export function ResourceVisualEditor({ clusterCode, namespace, resource, name, onClose, onSaved, isCreate = false }: ResourceVisualEditorProps) {
const { t } = useTranslation();
const { toast } = useToast(); const { toast } = useToast();
const [loading, setLoading] = useState(true); const [loading, setLoading] = useState(true);
const [saving, setSaving] = useState(false); const [saving, setSaving] = useState(false);
@@ -66,10 +68,10 @@ export function ResourceVisualEditor({ clusterCode, namespace, resource, name, o
setManifest(parsed); setManifest(parsed);
if (!parsed) { if (!parsed) {
setMode('yaml'); setMode('yaml');
toast({ title: '可视化编辑不可用', description: '无法解析资源结构,已切换到 YAML 编辑模式' }); toast({ title: t('kubernetes.resourcevisualeditor.s80ca4f'), description: t('kubernetes.resourcevisualeditor.scc94aa') });
} }
} catch (e) { } 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); } } finally { setLoading(false); }
}, [clusterCode, namespace, resource, name, isCreate]); }, [clusterCode, namespace, resource, name, isCreate]);
@@ -82,19 +84,19 @@ export function ResourceVisualEditor({ clusterCode, namespace, resource, name, o
const resName = updatedManifest?.metadata?.name || name; const resName = updatedManifest?.metadata?.name || name;
if (isCreate) { if (isCreate) {
if (!resName?.trim()) { if (!resName?.trim()) {
toast({ title: '请填写名称', variant: 'destructive' }); toast({ title: t('deploy.form.nameRequired'), variant: 'destructive' });
return; return;
} }
await kubernetesApi.applyYAML(clusterCode, yamlStr); await kubernetesApi.applyYAML(clusterCode, yamlStr);
toast({ title: '创建成功', description: `${resource}/${resName}` }); toast({ title: t('monitor.dashboard.custom.toastCreateSuccess'), description: `${resource}/${resName}` });
} else { } else {
await kubernetesApi.updateResourceYaml(clusterCode, namespace, resource, name, yamlStr); 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?.(); onSaved?.();
onClose(); onClose();
} catch (e) { } 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); } } finally { setSaving(false); }
}; };
@@ -104,10 +106,10 @@ export function ResourceVisualEditor({ clusterCode, namespace, resource, name, o
const yamlStr = await prepareYamlForSave(editYaml); const yamlStr = await prepareYamlForSave(editYaml);
if (isCreate) { if (isCreate) {
await kubernetesApi.applyYAML(clusterCode, yamlStr); await kubernetesApi.applyYAML(clusterCode, yamlStr);
toast({ title: '创建成功', description: 'YAML 已应用' }); toast({ title: t('monitor.dashboard.custom.toastCreateSuccess'), description: t('kubernetes.resourcevisualeditor.se5ff4b') });
} else { } else {
await kubernetesApi.updateResourceYaml(clusterCode, namespace, resource, name, yamlStr); 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); setYamlEditing(false);
setDisplayYaml(yamlStr); setDisplayYaml(yamlStr);
@@ -116,7 +118,7 @@ export function ResourceVisualEditor({ clusterCode, namespace, resource, name, o
onSaved?.(); onSaved?.();
onClose(); onClose();
} catch (e) { } 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); } } finally { setSaving(false); }
}; };
@@ -124,7 +126,7 @@ export function ResourceVisualEditor({ clusterCode, namespace, resource, name, o
const switchToVisual = async () => { const switchToVisual = async () => {
const parsed = await parseManifest(editYaml); const parsed = await parseManifest(editYaml);
if (!parsed) { if (!parsed) {
toast({ title: '无法解析 YAML', description: '请检查语法后继续用 YAML 模式', variant: 'destructive' }); toast({ title: t('kubernetes.resourcevisualeditor.sf53bdf'), description: t('kubernetes.resourcevisualeditor.sf2219a'), variant: 'destructive' });
return; return;
} }
setManifest(parsed); setManifest(parsed);
@@ -153,7 +155,7 @@ export function ResourceVisualEditor({ clusterCode, namespace, resource, name, o
const downloadYamlContent = () => { const downloadYamlContent = () => {
const fname = yamlDownloadFilename(resource, namespace, name || manifest?.metadata?.name || 'resource'); const fname = yamlDownloadFilename(resource, namespace, name || manifest?.metadata?.name || 'resource');
downloadYamlFile(fname, currentYamlText()); downloadYamlFile(fname, currentYamlText());
toast({ title: '已下载', description: fname }); toast({ title: t('kubernetes.resourcevisualeditor.s9719fe'), description: fname });
}; };
const resCfg = getYamlResourceConfig(resource); 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}`} /> <MetaIcon className={`h-5 w-5 shrink-0 ${meta.color}`} />
<div className="min-w-0"> <div className="min-w-0">
<h2 className="text-lg font-bold text-[var(--dg-text-primary)] truncate"> <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> </h2>
<p <p
className="text-xs text-[var(--dg-text-muted)] truncate" 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)]'}`} 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'); }} onClick={() => { if (mode === 'yaml') switchToVisual(); else setMode('visual'); }}
disabled={!manifest && mode !== 'yaml'} disabled={!manifest && mode !== 'yaml'}
>可视化编辑</button> >{t('k8s.resource.visualEditor')}</button>
<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)]'}`} 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'); }} onClick={() => { if (mode === 'visual') switchToYaml(); else setMode('yaml'); }}
>YAML 编辑</button> >{t('k8s.resource.yamlEditor')}</button>
</div> </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> <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> </div>
@@ -259,16 +261,16 @@ export function ResourceVisualEditor({ clusterCode, namespace, resource, name, o
{!['configmaps', 'secrets', 'services', 'ingresses', 'pvcs'].includes(resource) && ( {!['configmaps', 'secrets', 'services', 'ingresses', 'pvcs'].includes(resource) && (
<div className="flex-1 flex items-center justify-center text-center text-[var(--dg-text-muted)]"> <div className="flex-1 flex items-center justify-center text-center text-[var(--dg-text-muted)]">
<div> <div>
<p>该资源类型暂不支持可视化编辑</p> <p>{t('kubernetes.resourcevisualeditor.sfeb34f')}</p>
<Button variant="outline" size="sm" className="mt-4" onClick={() => setMode('yaml')}>切换到 YAML 编辑</Button> <Button variant="outline" size="sm" className="mt-4" onClick={() => setMode('yaml')}>{t('kubernetes.resourcevisualeditor.s54c78d')}</Button>
</div> </div>
</div> </div>
)} )}
</div> </div>
) : ( ) : (
<div className="text-center py-12 text-[var(--dg-text-muted)]"> <div className="text-center py-12 text-[var(--dg-text-muted)]">
<p>无法解析资源结构</p> <p>{t('kubernetes.resourcevisualeditor.s8fe0ae')}</p>
<Button variant="outline" size="sm" className="mt-4" onClick={() => setMode('yaml')}>切换到 YAML 编辑</Button> <Button variant="outline" size="sm" className="mt-4" onClick={() => setMode('yaml')}>{t('kubernetes.resourcevisualeditor.s54c78d')}</Button>
</div> </div>
)} )}
</div> </div>
@@ -281,6 +283,7 @@ export function ResourceVisualEditor({ clusterCode, namespace, resource, name, o
// ConfigMap 编辑器 — 键值对表格 // ConfigMap 编辑器 — 键值对表格
// ══════════════════════════════════════════════ // ══════════════════════════════════════════════
function ConfigMapEditor({ manifest, onSave, saving, isCreate }: { manifest: any; onSave: (m: any) => void; saving: boolean; isCreate?: boolean }) { function ConfigMapEditor({ manifest, onSave, saving, isCreate }: { manifest: any; onSave: (m: any) => void; saving: boolean; isCreate?: boolean }) {
const { t } = useTranslation();
const data = manifest?.data || {}; const data = manifest?.data || {};
const [resName, setResName] = useState(manifest?.metadata?.name || ''); const [resName, setResName] = useState(manifest?.metadata?.name || '');
const [entries, setEntries] = useState<{ key: string; value: string }[]>( const [entries, setEntries] = useState<{ key: string; value: string }[]>(
@@ -308,18 +311,18 @@ function ConfigMapEditor({ manifest, onSave, saving, isCreate }: { manifest: any
return ( return (
<div className="flex flex-col h-full"> <div className="flex flex-col h-full">
<div className="shrink-0"> <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)]" /> <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>
<div className="flex-1 min-h-0 flex flex-col mt-3"> <div className="flex-1 min-h-0 flex flex-col mt-3">
<div className="flex items-center justify-between mb-2 shrink-0"> <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"> <div className="flex gap-1">
<Button variant="outline" size="sm" className="h-7 text-xs" onClick={() => setExpandAll(!expandAll)}> <Button variant="outline" size="sm" className="h-7 text-xs" onClick={() => setExpandAll(!expandAll)}>
{expandAll ? '折叠全部' : '展开全部'} {expandAll ? t('kubernetes.resourcevisualeditor.s880e84') : t('common.expandAll')}
</Button> </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> </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"> <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 <Input
value={entry.key} value={entry.key}
onChange={e => update(i, 'key', e.target.value)} 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)]" className="flex-1 font-mono text-xs h-8 bg-[var(--dg-bg-tertiary)] border-[var(--dg-border)] text-[var(--dg-text-primary)]"
/> />
<Textarea <Textarea
value={entry.value} value={entry.value}
onChange={e => update(i, 'value', e.target.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)} 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" 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> </div>
))} ))}
{entries.length === 0 && ( {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>
</div> </div>
@@ -363,6 +366,7 @@ function ConfigMapEditor({ manifest, onSave, saving, isCreate }: { manifest: any
// Secret 编辑器 — 键值对表格 (Base64 编码/解码) // Secret 编辑器 — 键值对表格 (Base64 编码/解码)
// ══════════════════════════════════════════════ // ══════════════════════════════════════════════
function SecretEditor({ manifest, onSave, saving, isCreate }: { manifest: any; onSave: (m: any) => void; saving: boolean; isCreate?: boolean }) { function SecretEditor({ manifest, onSave, saving, isCreate }: { manifest: any; onSave: (m: any) => void; saving: boolean; isCreate?: boolean }) {
const { t } = useTranslation();
const rawData = manifest?.data || {}; const rawData = manifest?.data || {};
const [resName, setResName] = useState(manifest?.metadata?.name || ''); const [resName, setResName] = useState(manifest?.metadata?.name || '');
const [expandAll, setExpandAll] = useState(false); 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="flex flex-col h-full">
<div className="shrink-0 grid grid-cols-2 gap-4"> <div className="shrink-0 grid grid-cols-2 gap-4">
<div> <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)]" /> <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>
<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)]" /> <Input value={manifest?.type || 'Opaque'} readOnly className="mt-1 font-mono text-xs bg-[var(--dg-bg-tertiary)]" />
</div> </div>
</div> </div>
<div className="flex-1 min-h-0 flex flex-col mt-3"> <div className="flex-1 min-h-0 flex flex-col mt-3">
<div className="flex items-center justify-between mb-2 shrink-0"> <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"> <div className="flex gap-1">
<Button variant="outline" size="sm" className="h-7 text-xs" onClick={() => setExpandAll(!expandAll)}> <Button variant="outline" size="sm" className="h-7 text-xs" onClick={() => setExpandAll(!expandAll)}>
{expandAll ? '折叠全部' : '展开全部'} {expandAll ? t('kubernetes.resourcevisualeditor.s880e84') : t('common.expandAll')}
</Button> </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> </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"> <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 <Input
value={entry.key} value={entry.key}
onChange={e => update(i, 'key', e.target.value)} 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)]" className="flex-1 font-mono text-xs h-8 bg-[var(--dg-bg-tertiary)] border-[var(--dg-border)] text-[var(--dg-text-primary)]"
/> />
<Textarea <Textarea
value={entry.value} value={entry.value}
onChange={e => update(i, 'value', e.target.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)} 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" 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> </div>
))} ))}
{entries.length === 0 && ( {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>
</div> </div>
@@ -464,6 +468,7 @@ function SecretEditor({ manifest, onSave, saving, isCreate }: { manifest: any; o
// Service 编辑器 — 端口配置 + 类型 + 选择器 // Service 编辑器 — 端口配置 + 类型 + 选择器
// ══════════════════════════════════════════════ // ══════════════════════════════════════════════
function ServiceEditor({ manifest, onSave, saving, isCreate }: { manifest: any; onSave: (m: any) => void; saving: boolean; isCreate?: boolean }) { function ServiceEditor({ manifest, onSave, saving, isCreate }: { manifest: any; onSave: (m: any) => void; saving: boolean; isCreate?: boolean }) {
const { t } = useTranslation();
const spec = manifest?.spec || {}; const spec = manifest?.spec || {};
const [resName, setResName] = useState(manifest?.metadata?.name || ''); const [resName, setResName] = useState(manifest?.metadata?.name || '');
const [svcType, setSvcType] = useState(spec.type || 'ClusterIP'); const [svcType, setSvcType] = useState(spec.type || 'ClusterIP');
@@ -524,11 +529,11 @@ function ServiceEditor({ manifest, onSave, saving, isCreate }: { manifest: any;
return ( return (
<div className="flex flex-col h-full"> <div className="flex flex-col h-full">
<div className="shrink-0"> <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)]" /> <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>
<div className="shrink-0 mt-3"> <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"> <div className="flex rounded-lg border border-[var(--dg-border)] overflow-hidden w-fit">
{svcTypes.map((t) => ( {svcTypes.map((t) => (
<button <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 className="flex-1 min-h-0 overflow-y-auto mt-3 pr-1 space-y-3">
<div> <div>
<div className="flex items-center justify-between mb-2"> <div className="flex items-center justify-between mb-2">
<Label className="text-[var(--dg-text-secondary)] text-sm">端口映射</Label> <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" />添加端口</Button> <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>
<div className="space-y-2 border border-[var(--dg-border)] rounded-lg p-2 bg-[var(--dg-bg-secondary)]"> <div className="space-y-2 border border-[var(--dg-border)] rounded-lg p-2 bg-[var(--dg-bg-secondary)]">
{ports.map((p, i) => ( {ports.map((p, i) => (
<div key={i} className="overflow-x-auto"> <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]"> <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.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="端口" 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.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="目标" 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)}> <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> <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> <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>
</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>
</div> </div>
{/* Selector */} {/* Selector */}
<div> <div>
<div className="flex items-center justify-between mb-2"> <div className="flex items-center justify-between mb-2">
<Label className="text-[var(--dg-text-secondary)] text-sm">选择器 (Selector)</Label> <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" />添加标签</Button> <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>
<div className="space-y-2"> <div className="space-y-2">
{selector.map((s, i) => ( {selector.map((s, i) => (
<div key={i} className="flex items-center gap-2 min-w-0"> <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> <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> <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> </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> </div>
</div> </div>
@@ -606,6 +611,7 @@ function ServiceEditor({ manifest, onSave, saving, isCreate }: { manifest: any;
// Ingress 编辑器 — Host/Path 路由规则 // Ingress 编辑器 — Host/Path 路由规则
// ══════════════════════════════════════════════ // ══════════════════════════════════════════════
function IngressEditor({ manifest, clusterCode, onSave, saving, isCreate }: { manifest: any; clusterCode: string; onSave: (m: any) => void; saving: boolean; isCreate?: boolean }) { 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 spec = manifest?.spec || {};
const [resName, setResName] = useState(manifest?.metadata?.name || ''); const [resName, setResName] = useState(manifest?.metadata?.name || '');
const [ingressClass, setIngressClass] = useState(spec.ingressClassName || 'nginx'); 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="flex flex-col h-full min-h-0">
<div className="shrink-0 grid grid-cols-1 sm:grid-cols-2 gap-4"> <div className="shrink-0 grid grid-cols-1 sm:grid-cols-2 gap-4">
<div className="min-w-0"> <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)]" /> <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>
<div className="min-w-0"> <div className="min-w-0">
<Label className="text-[var(--dg-text-secondary)] text-xs flex items-center gap-1"> <Label className="text-[var(--dg-text-secondary)] text-xs flex items-center gap-1">
Ingress Class 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> </Label>
{/* IngressClass 下拉 + 手工输入支持 // Logan.Li */} {/* IngressClass 下拉 + 手工输入支持 // Logan.Li */}
<div className="space-y-1 mt-1"> <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)]"> <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> </SelectTrigger>
<SelectContent> <SelectContent>
{ingressClasses.length > 0 ? ( {ingressClasses.length > 0 ? (
@@ -718,13 +724,13 @@ function IngressEditor({ manifest, clusterCode, onSave, saving, isCreate }: { ma
</SelectItem> </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) && ( {ingressClass && !ingressClasses.some((ic) => ic.name === ingressClass) && (
<SelectItem value={ingressClass}>{ingressClass} (手动输入)</SelectItem> <SelectItem value={ingressClass}>{ingressClass} (手动输入)</SelectItem>
)} )}
<SelectItem value="__manual__">—— 继续手动输入 ——</SelectItem> <SelectItem value="__manual__">{t('kubernetes.resourcevisualeditor.se83eb1')}</SelectItem>
</SelectContent> </SelectContent>
</Select> </Select>
@@ -755,8 +761,8 @@ function IngressEditor({ manifest, clusterCode, onSave, saving, isCreate }: { ma
</div> </div>
<div className="flex-1 min-h-0 flex flex-col mt-3"> <div className="flex-1 min-h-0 flex flex-col mt-3">
<div className="flex items-center justify-between mb-2 shrink-0"> <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('k8s.resource.routeRules')}</Label>
<Button variant="outline" size="sm" className="h-7 text-xs" onClick={addRule}><Plus className="h-3 w-3 mr-1" />添加 Host</Button> <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>
<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)]"> <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) => ( {rules.map((rule, ri) => (
@@ -765,7 +771,7 @@ function IngressEditor({ manifest, clusterCode, onSave, saving, isCreate }: { ma
<Input <Input
value={rule.host} value={rule.host}
onChange={e => updateRule(ri, e.target.value)} 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)]" 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} title={rule.host}
/> />
@@ -774,21 +780,21 @@ function IngressEditor({ manifest, clusterCode, onSave, saving, isCreate }: { ma
{rule.paths.map((p, pi) => ( {rule.paths.map((p, pi) => (
<div key={pi} className="overflow-x-auto pl-4"> <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]"> <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)}> <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> <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> <SelectContent><SelectItem value="Prefix">Prefix</SelectItem><SelectItem value="Exact">Exact</SelectItem></SelectContent>
</Select> </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.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> <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>
</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> </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> </div>
<div className="shrink-0 flex justify-end gap-2 pt-3 mt-2 border-t border-[var(--dg-border)]"> <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 // PVC 编辑器 — 存储大小/访问模式/StorageClass
// ══════════════════════════════════════════════ // ══════════════════════════════════════════════
function PvcEditor({ manifest, onSave, saving, isCreate }: { manifest: any; onSave: (m: any) => void; saving: boolean; isCreate?: boolean }) { function PvcEditor({ manifest, onSave, saving, isCreate }: { manifest: any; onSave: (m: any) => void; saving: boolean; isCreate?: boolean }) {
const { t } = useTranslation();
const spec = manifest?.spec || {}; const spec = manifest?.spec || {};
const resources = spec.resources?.requests || {}; const resources = spec.resources?.requests || {};
const [resName, setResName] = useState(manifest?.metadata?.name || ''); const [resName, setResName] = useState(manifest?.metadata?.name || '');
@@ -828,30 +835,30 @@ function PvcEditor({ manifest, onSave, saving, isCreate }: { manifest: any; onSa
return ( return (
<div className="flex flex-col h-full"> <div className="flex flex-col h-full">
<div className="shrink-0"> <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)]" /> <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>
<div className="grid grid-cols-2 gap-4 mt-3 shrink-0"> <div className="grid grid-cols-2 gap-4 mt-3 shrink-0">
<div> <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 <Input
value={size} value={size}
onChange={e => setSize(e.target.value)} 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)]" 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>
<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}> <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"> <SelectTrigger className="mt-1 h-8 bg-[var(--dg-bg-tertiary)] border-[var(--dg-border)] text-[var(--dg-text-primary)] text-xs">
<SelectValue /> <SelectValue />
</SelectTrigger> </SelectTrigger>
<SelectContent> <SelectContent>
<SelectItem value="ReadWriteOnce">ReadWriteOnce (单节点读写)</SelectItem> <SelectItem value="ReadWriteOnce">{t('kubernetes.resourcevisualeditor.se1444f')}</SelectItem>
<SelectItem value="ReadOnlyMany">ReadOnlyMany (多节点只读)</SelectItem> <SelectItem value="ReadOnlyMany">{t('kubernetes.resourcevisualeditor.s9d4ea0')}</SelectItem>
<SelectItem value="ReadWriteMany">ReadWriteMany (多节点读写)</SelectItem> <SelectItem value="ReadWriteMany">{t('kubernetes.resourcevisualeditor.s093227')}</SelectItem>
</SelectContent> </SelectContent>
</Select> </Select>
</div> </div>
@@ -861,7 +868,7 @@ function PvcEditor({ manifest, onSave, saving, isCreate }: { manifest: any; onSa
<Input <Input
value={storageClass} value={storageClass}
onChange={e => setStorageClass(e.target.value)} 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)]" className="mt-1 font-mono text-xs h-8 bg-[var(--dg-bg-tertiary)] border-[var(--dg-border)] text-[var(--dg-text-primary)]"
/> />
</div> </div>
@@ -22,11 +22,13 @@ import { PodFileBrowser } from './PodFileBrowser';
import { formatK8sTime, statusColor, STATUS_COLORS } from './k8s-yaml-utils'; import { formatK8sTime, statusColor, STATUS_COLORS } from './k8s-yaml-utils';
import { PageShell } from '@/components/layout/PageShell'; import { PageShell } from '@/components/layout/PageShell';
import type { JsonData } from '@/types/common'; import type { JsonData } from '@/types/common';
import { useTranslation } from 'react-i18next';
type WorkloadKind = 'StatefulSet' | 'DaemonSet'; type WorkloadKind = 'StatefulSet' | 'DaemonSet';
type ViewMode = 'view' | 'yaml'; type ViewMode = 'view' | 'yaml';
function StatCard({ label, value, sub, color }: { label: string; value: React.ReactNode; sub?: string; color?: string }) { function StatCard({ label, value, sub, color }: { label: string; value: React.ReactNode; sub?: string; color?: string }) {
const { t } = useTranslation();
return ( return (
<Card className="bg-[var(--dg-bg-secondary)] border-[var(--dg-border)]"> <Card className="bg-[var(--dg-bg-secondary)] border-[var(--dg-border)]">
<CardContent className="p-3"> <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 // Helper: render key-value pairs as badges
function LabelBadges({ labels }: { labels: Record<string, string> | undefined }) { function LabelBadges({ labels }: { labels: Record<string, string> | undefined }) {
const { t } = useTranslation();
const entries = Object.entries(labels || {}); 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 ( return (
<div className="flex flex-wrap gap-1.5"> <div className="flex flex-wrap gap-1.5">
{entries.map(([k, v]) => ( {entries.map(([k, v]) => (
@@ -54,6 +57,7 @@ function LabelBadges({ labels }: { labels: Record<string, string> | undefined })
} }
export default function WorkloadViewPage() { export default function WorkloadViewPage() {
const { t } = useTranslation();
const params = useParams<{ clusterCode: string; namespace: string; name: string; mode?: string }>(); const params = useParams<{ clusterCode: string; namespace: string; name: string; mode?: string }>();
const navigate = useNavigate(); const navigate = useNavigate();
const location = useLocation(); const location = useLocation();
@@ -119,9 +123,9 @@ export default function WorkloadViewPage() {
const handleRestart = async () => { const handleRestart = async () => {
const ok = await confirm({ const ok = await confirm({
title: '滚动重启', title: t('kubernetes.deployment.restart'),
description: `确认重启 ${kind} ${name}?将触发滚动重启。`, description: t('kubernetes.workloadviewpage.s6139f5', { kind: kind, name: name }),
confirmText: '重启', confirmText: t('common.reboot'),
}); });
if (!ok) return; if (!ok) return;
setActionLoading(true); setActionLoading(true);
@@ -131,10 +135,10 @@ export default function WorkloadViewPage() {
} else { } else {
await kubernetesApi.restartDaemonSet(clusterCode, namespace, name); 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); setTimeout(loadData, 1000);
} catch (e) { } 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); } } finally { setActionLoading(false); }
}; };
@@ -142,11 +146,11 @@ export default function WorkloadViewPage() {
setActionLoading(true); setActionLoading(true);
try { try {
await kubernetesApi.scaleStatefulSet(clusterCode, namespace, name, scaleValue); 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); setScaleModal(false);
setTimeout(loadData, 1000); setTimeout(loadData, 1000);
} catch (e) { } 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); } } finally { setActionLoading(false); }
}; };
@@ -190,7 +194,7 @@ export default function WorkloadViewPage() {
const modeTabs = ( const modeTabs = (
<div className="flex items-center gap-1 bg-[var(--dg-bg-secondary)] border border-[var(--dg-border)] rounded-lg p-0.5"> <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> <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> </div>
); );
@@ -202,7 +206,7 @@ export default function WorkloadViewPage() {
subtitle={`${clusterCode} / ${namespace} · ${kind}`} subtitle={`${clusterCode} / ${namespace} · ${kind}`}
icon={<Boxes className="h-5 w-5" />} icon={<Boxes className="h-5 w-5" />}
loading={loading} loading={loading}
loadingLabel="加载工作负载..." loadingLabel=t('kubernetes.workloadviewpage.s4eb429')
actions={( actions={(
<> <>
<Button variant="outline" size="sm" className="dg-btn-secondary" onClick={() => navigate(-1)}> <Button variant="outline" size="sm" className="dg-btn-secondary" onClick={() => navigate(-1)}>
@@ -215,7 +219,7 @@ export default function WorkloadViewPage() {
</Button> </Button>
)} )}
<Button variant="outline" size="sm" className="dg-btn-secondary" disabled={actionLoading} onClick={handleRestart}> <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>
<Button variant="outline" size="sm" className="dg-btn-secondary" onClick={() => setYamlModal(true)}> <Button variant="outline" size="sm" className="dg-btn-secondary" onClick={() => setYamlModal(true)}>
<FileCode className="h-3.5 w-3.5 mr-1" />YAML <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)]">{kind}</Badge>
<Badge variant="outline" className="border-[var(--dg-border)] text-[var(--dg-text-secondary)]">{namespace}</Badge> <Badge variant="outline" className="border-[var(--dg-border)] text-[var(--dg-text-secondary)]">{namespace}</Badge>
{isHealthy {isHealthy
? <Badge className="bg-[var(--dg-green)]/20 text-[var(--dg-green)] border-[var(--dg-green)]/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">更新中</Badge>} : <Badge className="bg-[var(--dg-orange)]/20 text-[var(--dg-orange)] border-[var(--dg-orange)]/30">{t('kubernetes.workloadviewpage.sf339d4')}</Badge>}
</div> </div>
{!loading && (mode === 'yaml' ? ( {!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"> <div className="grid grid-cols-2 md:grid-cols-4 lg:grid-cols-6 gap-3">
{isSts ? ( {isSts ? (
<> <>
<StatCard label="副本就绪" value={`${readyReplicas}/${replicas}`} color={isHealthy ? STATUS_COLORS.green : STATUS_COLORS.orange} sub={isHealthy ? '全部就绪' : '部分未就绪'} /> <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="当前副本" value={currentReplicas} color={STATUS_COLORS.blue} /> <StatCard label=t('kubernetes.hpa.currentReplicas') value={currentReplicas} color={STATUS_COLORS.blue} />
<StatCard label="已更新副本" value={updatedReplicas} color={STATUS_COLORS.green} /> <StatCard label=t('kubernetes.deployment.updatedReplicas') value={updatedReplicas} color={STATUS_COLORS.green} />
<StatCard label="服务名" value={spec.serviceName || '-'} color="var(--dg-text-secondary)" /> <StatCard label=t('kubernetes.workloadviewpage.sf592ef') value={spec.serviceName || '-'} color="var(--dg-text-secondary)" />
<StatCard label="Pod 数量" value={pods.length} color="var(--dg-text-secondary)" /> <StatCard label=t('kubernetes.workloadviewpage.s55edf2') 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('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=t('kubernetes.workloadviewpage.sd78bc8') value={desiredScheduled} color={STATUS_COLORS.blue} />
<StatCard label="当前调度" value={currentScheduled} color="var(--dg-text-secondary)" /> <StatCard label=t('kubernetes.workloadviewpage.sb76164') value={currentScheduled} color="var(--dg-text-secondary)" />
<StatCard label="就绪数量" value={numberReady} color={isHealthy ? STATUS_COLORS.green : STATUS_COLORS.orange} /> <StatCard label=t('kubernetes.daemonset.numberReady') value={numberReady} color={isHealthy ? STATUS_COLORS.green : STATUS_COLORS.orange} />
<StatCard label="可用数量" value={numberAvailable} color={STATUS_COLORS.green} /> <StatCard label=t('kubernetes.daemonset.numberAvailable') value={numberAvailable} color={STATUS_COLORS.green} />
<StatCard label="已更新" value={numberUpdated} color="var(--dg-text-secondary)" /> <StatCard label=t('deploy.toast.updated') 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('common.createdAt') value={<span className="text-xs">{formatK8sTime(manifest?.metadata?.creationTimestamp)}</span>} color="var(--dg-text-secondary)" />
</> </>
)} )}
</div> </div>
@@ -280,18 +284,18 @@ export default function WorkloadViewPage() {
</CardHeader> </CardHeader>
<CardContent className="pt-0 space-y-2 text-xs"> <CardContent className="pt-0 space-y-2 text-xs">
<div className="flex justify-between"> <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> <Badge variant="outline" className="border-[var(--dg-border)] text-[var(--dg-text-secondary)]">{strategyType}</Badge>
</div> </div>
{strategyType === 'RollingUpdate' && isSts && updateStrategy.rollingUpdate && ( {strategyType === 'RollingUpdate' && isSts && updateStrategy.rollingUpdate && (
<> <>
<div className="flex justify-between"> <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> <span className="text-[var(--dg-text-secondary)] font-mono">{updateStrategy.rollingUpdate.partition ?? 0}</span>
</div> </div>
{updateStrategy.rollingUpdate.maxUnavailable && ( {updateStrategy.rollingUpdate.maxUnavailable && (
<div className="flex justify-between"> <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> <span className="text-[var(--dg-text-secondary)] font-mono">{typeof updateStrategy.rollingUpdate.maxUnavailable === 'object' ? JSON.stringify(updateStrategy.rollingUpdate.maxUnavailable) : updateStrategy.rollingUpdate.maxUnavailable}</span>
</div> </div>
)} )}
@@ -301,13 +305,13 @@ export default function WorkloadViewPage() {
<> <>
{updateStrategy.rollingUpdate.maxUnavailable && ( {updateStrategy.rollingUpdate.maxUnavailable && (
<div className="flex justify-between"> <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> <span className="text-[var(--dg-text-secondary)] font-mono">{typeof updateStrategy.rollingUpdate.maxUnavailable === 'object' ? JSON.stringify(updateStrategy.rollingUpdate.maxUnavailable) : updateStrategy.rollingUpdate.maxUnavailable}</span>
</div> </div>
)} )}
{updateStrategy.rollingUpdate.maxSurge && ( {updateStrategy.rollingUpdate.maxSurge && (
<div className="flex justify-between"> <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> <span className="text-[var(--dg-text-secondary)] font-mono">{typeof updateStrategy.rollingUpdate.maxSurge === 'object' ? JSON.stringify(updateStrategy.rollingUpdate.maxSurge) : updateStrategy.rollingUpdate.maxSurge}</span>
</div> </div>
)} )}
@@ -315,12 +319,12 @@ export default function WorkloadViewPage() {
)} )}
{isSts && ( {isSts && (
<div className="flex justify-between"> <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> <span className="text-[var(--dg-text-secondary)] font-mono">{spec.podManagementPolicy || 'OrderedReady'}</span>
</div> </div>
)} )}
<div className="flex justify-between"> <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> <span className="text-[var(--dg-text-secondary)] font-mono">{spec.revisionHistoryLimit ?? 10}</span>
</div> </div>
</CardContent> </CardContent>
@@ -369,10 +373,10 @@ export default function WorkloadViewPage() {
<Table> <Table>
<TableHeader> <TableHeader>
<TableRow className="border-[var(--dg-border)] hover:bg-transparent"> <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('common.name')}</TableHead>
<TableHead className="text-[var(--dg-text-secondary)]">访问模式</TableHead> <TableHead className="text-[var(--dg-text-secondary)]">{t('k8s.resource.accessMode')}</TableHead>
<TableHead className="text-[var(--dg-text-secondary)]">存储类</TableHead> <TableHead className="text-[var(--dg-text-secondary)]">{t('k8s.resource.storageClass')}</TableHead>
<TableHead className="text-[var(--dg-text-secondary)]">大小</TableHead> <TableHead className="text-[var(--dg-text-secondary)]">{t('deploy.table.size')}</TableHead>
</TableRow> </TableRow>
</TableHeader> </TableHeader>
<TableBody> <TableBody>
@@ -414,7 +418,7 @@ export default function WorkloadViewPage() {
</div> </div>
)} )}
{containers.length === 0 ? ( {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"> <div className="space-y-3">
<p className="text-[11px] text-[var(--dg-text-muted)] mb-1 uppercase tracking-wide">Containers</p> <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> <Table>
<TableHeader> <TableHeader>
<TableRow className="border-[var(--dg-border)] hover:bg-transparent"> <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)]">{t('kubernetes.pod.podName')}</TableHead>
<TableHead className="text-[var(--dg-text-secondary)]">状态</TableHead> <TableHead className="text-[var(--dg-text-secondary)]">{t('common.status')}</TableHead>
<TableHead className="text-[var(--dg-text-secondary)]">所在节点</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)]">Pod IP</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)]">操作</TableHead> <TableHead className="text-[var(--dg-text-secondary)]">{t('common.actions')}</TableHead>
</TableRow> </TableRow>
</TableHeader> </TableHeader>
<TableBody> <TableBody>
{pods.length === 0 ? ( {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) => ( ) : pods.map((pod: JsonData) => (
<TableRow key={pod.name} className="border-[var(--dg-border)] hover:bg-[var(--dg-bg-tertiary)]/30"> <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> <TableCell className="font-medium text-[var(--dg-text-primary)]">{pod.name}</TableCell>
@@ -484,7 +488,7 @@ export default function WorkloadViewPage() {
{scaleModal && ( {scaleModal && (
<div className="fixed inset-0 bg-black/60 z-50 flex items-center justify-center" onClick={() => setScaleModal(false)}> <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()}> <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"> <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))}> <Button variant="outline" size="icon" className="h-9 w-9" onClick={() => setScaleValue(Math.max(0, scaleValue - 1))}>
<Minus className="h-4 w-4" /> <Minus className="h-4 w-4" />
@@ -495,9 +499,9 @@ export default function WorkloadViewPage() {
</Button> </Button>
</div> </div>
<div className="flex gap-2"> <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}> <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> </Button>
</div> </div>
</div> </div>
@@ -544,6 +548,7 @@ export default function WorkloadViewPage() {
// Container info sub-component // Container info sub-component
function ContainerInfo({ c }: { c: JsonData}) { function ContainerInfo({ c }: { c: JsonData}) {
const { t } = useTranslation();
return ( return (
<div className="border border-[var(--dg-border)] rounded-lg p-3 bg-[var(--dg-bg-primary)]/30"> <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"> <div className="flex items-center justify-between mb-2">
@@ -7,6 +7,7 @@ import { useToast } from '@/hooks/use-toast';
import { kubernetesApi } from '@/api'; import { kubernetesApi } from '@/api';
import { YamlCodeMirror } from './YamlCodeMirror'; import { YamlCodeMirror } from './YamlCodeMirror';
import type { JsonData } from '@/types/common'; import type { JsonData } from '@/types/common';
import { useTranslation } from 'react-i18next';
interface YamlImportDialogProps { interface YamlImportDialogProps {
clusterCode: string; clusterCode: string;
@@ -15,23 +16,24 @@ interface YamlImportDialogProps {
} }
export function YamlImportDialog({ clusterCode, onClose, onApplied }: YamlImportDialogProps) { export function YamlImportDialog({ clusterCode, onClose, onApplied }: YamlImportDialogProps) {
const { t } = useTranslation();
const { toast } = useToast(); const { toast } = useToast();
const [content, setContent] = useState(''); const [content, setContent] = useState('');
const [applying, setApplying] = useState(false); const [applying, setApplying] = useState(false);
const apply = async () => { const apply = async () => {
if (!content.trim()) { if (!content.trim()) {
toast({ title: '请输入 YAML', variant: 'destructive' }); toast({ title: t('kubernetes.yamlimportdialog.s81d637'), variant: 'destructive' });
return; return;
} }
setApplying(true); setApplying(true);
try { try {
await kubernetesApi.applyYAML(clusterCode, content); await kubernetesApi.applyYAML(clusterCode, content);
toast({ title: '导入成功', description: 'YAML 已应用到集群' }); toast({ title: t('system.importSuccess'), description: t('kubernetes.yamlimportdialog.sb66e8e') });
onApplied?.(); onApplied?.();
onClose(); onClose();
} catch (e) { } 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); } } finally { setApplying(false); }
}; };
@@ -45,8 +47,8 @@ export function YamlImportDialog({ clusterCode, onClose, onApplied }: YamlImport
<div className="flex items-center gap-2"> <div className="flex items-center gap-2">
<Upload className="h-5 w-5 text-[var(--dg-text-muted)]" /> <Upload className="h-5 w-5 text-[var(--dg-text-muted)]" />
<div> <div>
<h2 className="text-lg font-bold text-[var(--dg-text-primary)]">导入 YAML</h2> <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)]">支持多文档(--- 分隔),适用于新建或更新资源</p> <p className="text-xs text-[var(--dg-text-muted)]">{t('kubernetes.yamlimportdialog.s92b733')}</p>
</div> </div>
</div> </div>
<Button variant="ghost" size="icon" className="h-8 w-8" onClick={onClose}><X className="h-4 w-4" /></Button> <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>
<div className="flex justify-end gap-2 p-4 border-t border-[var(--dg-border)] shrink-0"> <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}> <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" />} {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 { YamlCodeMirror } from './YamlCodeMirror';
import { downloadYamlFile } from '@/utils/export'; import { downloadYamlFile } from '@/utils/export';
import type { JsonData } from '@/types/common'; import type { JsonData } from '@/types/common';
import { useTranslation } from 'react-i18next';
interface YamlViewerProps { interface YamlViewerProps {
clusterCode: string; clusterCode: string;
@@ -37,6 +38,7 @@ export function YamlViewer({
autoEdit = false, inline = false, initialYaml, readOnly: readOnlyProp, autoEdit = false, inline = false, initialYaml, readOnly: readOnlyProp,
loadYamlFn, saveYamlFn, resourceHint, loadYamlFn, saveYamlFn, resourceHint,
}: YamlViewerProps) { }: YamlViewerProps) {
const { t } = useTranslation();
const { toast } = useToast(); const { toast } = useToast();
const resCfg = getYamlResourceConfig(resource); const resCfg = getYamlResourceConfig(resource);
const readOnly = readOnlyProp ?? resCfg.readOnly; const readOnly = readOnlyProp ?? resCfg.readOnly;
@@ -73,7 +75,7 @@ export function YamlViewer({
setRawYaml(text); setRawYaml(text);
await applyStripped(text); await applyStripped(text);
} catch (e) { } 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}`; const err = `# Error: ${(e as Error).message}`;
setRawYaml(err); setRawYaml(err);
setDisplayYaml(err); setDisplayYaml(err);
@@ -103,14 +105,14 @@ export function YamlViewer({
} else { } else {
await kubernetesApi.updateResourceYaml(clusterCode, namespace, resource, name, yamlStr); 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); setEditing(false);
setRawYaml(yamlStr); setRawYaml(yamlStr);
setDisplayYaml(yamlStr); setDisplayYaml(yamlStr);
setEditYaml(yamlStr); setEditYaml(yamlStr);
onSaved?.(); onSaved?.();
} catch (e) { } 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); } } finally { setSaving(false); }
}; };
@@ -124,7 +126,7 @@ export function YamlViewer({
const downloadYaml = () => { const downloadYaml = () => {
downloadYamlFile(yamlDownloadFilename(resource, namespace, name), currentYaml()); 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); const display = editing ? editYaml : (showRaw ? rawYaml : displayYaml);
@@ -186,7 +188,7 @@ export function YamlViewer({
<div className="min-w-0 flex-1"> <div className="min-w-0 flex-1">
<h2 className="text-lg font-bold text-[var(--dg-text-primary)] truncate" title={`${resCfg.label} YAML — ${name}`}> <h2 className="text-lg font-bold text-[var(--dg-text-primary)] truncate" title={`${resCfg.label} YAML — ${name}`}>
{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> </h2>
<p className="text-xs dg-text-muted truncate" title={`${namespace} · ${clusterCode}`}>{namespace} · {clusterCode}</p> <p className="text-xs dg-text-muted truncate" title={`${namespace} · ${clusterCode}`}>{namespace} · {clusterCode}</p>
</div> </div>
@@ -2,6 +2,7 @@
// Deployment 多文档 YAML(Deployment + 关联 Service)加载与保存 // Logan.Li // Deployment 多文档 YAML(Deployment + 关联 Service)加载与保存 // Logan.Li
import { kubernetesApi } from '@/api'; import { kubernetesApi } from '@/api';
import { import {
import i18n from '@/i18n';
manifestToEditableYaml, manifestToEditableYaml,
parseEditableManifest, parseEditableManifest,
parseEditableManifests, parseEditableManifests,
@@ -80,12 +81,12 @@ export async function saveDeploymentBundleYaml(
yamlText: string, yamlText: string,
): Promise<void> { ): Promise<void> {
const { manifests } = await parseEditableManifests(yamlText); 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) { for (const manifest of manifests) {
const kind = String(manifest.kind || '').toLowerCase(); const kind = String(manifest.kind || '').toLowerCase();
const name = String(manifest.metadata?.name || '').trim(); 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); const docYaml = await prepareManifestForSave(manifest);
if (kind === 'deployment') { if (kind === 'deployment') {
@@ -96,6 +97,6 @@ export async function saveDeploymentBundleYaml(
await kubernetesApi.applyYAML(clusterCode, docYaml); await kubernetesApi.applyYAML(clusterCode, docYaml);
continue; 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 { Label } from '@/components/ui/label';
import { kubernetesApi } from '@/api'; import { kubernetesApi } from '@/api';
import { useToast } from '@/hooks/use-toast'; import { useToast } from '@/hooks/use-toast';
import { useTranslation } from 'react-i18next';
export interface CreateHPADialogProps { export interface CreateHPADialogProps {
clusterCode: string; clusterCode: string;
@@ -15,6 +16,7 @@ export interface CreateHPADialogProps {
} }
export function CreateHPADialog({ clusterCode, namespace, deploymentName, onCreated }: CreateHPADialogProps) { export function CreateHPADialog({ clusterCode, namespace, deploymentName, onCreated }: CreateHPADialogProps) {
const { t } = useTranslation();
const { toast } = useToast(); const { toast } = useToast();
const [open, setOpen] = useState(false); const [open, setOpen] = useState(false);
const [loading, setLoading] = useState(false); const [loading, setLoading] = useState(false);
@@ -28,7 +30,7 @@ export function CreateHPADialog({ clusterCode, namespace, deploymentName, onCrea
const handleCreate = async () => { const handleCreate = async () => {
if (!form.name.trim()) { if (!form.name.trim()) {
toast({ title: '名称不能为空', variant: 'destructive' }); toast({ title: t('kubernetes.createhpadialog.sdf09ff'), variant: 'destructive' });
return; return;
} }
setLoading(true); setLoading(true);
@@ -43,12 +45,12 @@ export function CreateHPADialog({ clusterCode, namespace, deploymentName, onCrea
cpuPercent: form.cpuPercent, cpuPercent: form.cpuPercent,
memPercent: form.memPercent, memPercent: form.memPercent,
}); });
toast({ title: 'HPA 创建成功' }); toast({ title: t('kubernetes.createhpadialog.s74b0b0') });
setOpen(false); setOpen(false);
onCreated(); onCreated();
setForm({ name: '', minReplicas: 1, maxReplicas: 10, cpuPercent: 80, memPercent: 0 }); setForm({ name: '', minReplicas: 1, maxReplicas: 10, cpuPercent: 80, memPercent: 0 });
} catch (e: any) { } 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); } } finally { setLoading(false); }
}; };
@@ -60,29 +62,29 @@ export function CreateHPADialog({ clusterCode, namespace, deploymentName, onCrea
{open && ( {open && (
<div className="fixed inset-0 z-50 flex items-center justify-center bg-black/60 p-4" onClick={() => setOpen(false)}> <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()}> <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 className="flex-1 min-h-0 overflow-y-auto px-6 space-y-3">
<div> <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 })} <Input value={form.name} onChange={(e) => setForm({ ...form, name: e.target.value })}
placeholder={`hpa-${deploymentName}`} placeholder={`hpa-${deploymentName}`}
className="dg-input mt-1" /> className="dg-input mt-1" />
</div> </div>
<div> <div>
<Label className="dg-text-secondary text-sm">目标</Label> <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={`Deployment: ${deploymentName} · 命名空间: ${namespace}`}> <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} Deployment: {deploymentName} · 命名空间: {namespace}
</p> </p>
</div> </div>
<div className="grid grid-cols-2 gap-3"> <div className="grid grid-cols-2 gap-3">
<div> <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} <Input type="number" value={form.minReplicas} min={1}
onChange={(e) => setForm({ ...form, minReplicas: Number(e.target.value) })} onChange={(e) => setForm({ ...form, minReplicas: Number(e.target.value) })}
className="dg-input mt-1" /> className="dg-input mt-1" />
</div> </div>
<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} <Input type="number" value={form.maxReplicas} min={1}
onChange={(e) => setForm({ ...form, maxReplicas: Number(e.target.value) })} onChange={(e) => setForm({ ...form, maxReplicas: Number(e.target.value) })}
className="dg-input mt-1" /> className="dg-input mt-1" />
@@ -90,13 +92,13 @@ export function CreateHPADialog({ clusterCode, namespace, deploymentName, onCrea
</div> </div>
<div className="grid grid-cols-2 gap-3"> <div className="grid grid-cols-2 gap-3">
<div> <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} <Input type="number" value={form.cpuPercent} min={0} max={100}
onChange={(e) => setForm({ ...form, cpuPercent: Number(e.target.value) })} onChange={(e) => setForm({ ...form, cpuPercent: Number(e.target.value) })}
className="dg-input mt-1" /> className="dg-input mt-1" />
</div> </div>
<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} <Input type="number" value={form.memPercent} min={0} max={100}
onChange={(e) => setForm({ ...form, memPercent: Number(e.target.value) })} onChange={(e) => setForm({ ...form, memPercent: Number(e.target.value) })}
className="dg-input mt-1" /> className="dg-input mt-1" />
@@ -104,9 +106,9 @@ export function CreateHPADialog({ clusterCode, namespace, deploymentName, onCrea
</div> </div>
</div> </div>
<div className="flex justify-end gap-2 px-6 py-4 border-t border-[var(--dg-border)] shrink-0"> <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}> <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> </Button>
</div> </div>
</div> </div>
@@ -8,6 +8,7 @@ import { Input } from '@/components/ui/input';
import { Badge } from '@/components/ui/badge'; import { Badge } from '@/components/ui/badge';
import { CreateHPADialog } from './CreateHPADialog'; import { CreateHPADialog } from './CreateHPADialog';
import type { JsonData } from '@/types/common'; import type { JsonData } from '@/types/common';
import { useTranslation } from 'react-i18next';
export interface DeploymentOverviewProps { export interface DeploymentOverviewProps {
deploymentName: string; deploymentName: string;
@@ -37,6 +38,7 @@ export function DeploymentOverview({
newImage, showImageUpdate, onBack, onRefresh, onScale, onRestart, newImage, showImageUpdate, onBack, onRefresh, onScale, onRestart,
onNewImageChange, onToggleImageUpdate, onUpdateImage, onNewImageChange, onToggleImageUpdate, onUpdateImage,
}: DeploymentOverviewProps) { }: DeploymentOverviewProps) {
const { t } = useTranslation();
return ( return (
<> <>
<div className="flex items-center justify-between"> <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"> <div className="grid grid-cols-2 md:grid-cols-4 gap-3">
<Card className="dg-card"> <Card className="dg-card">
<CardContent className="p-3"> <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'}`}> <p className={`text-lg font-bold ${isHealthy ? 'dg-text-green' : 'dg-text-yellow'}`}>
{ready}/{total} {ready}/{total}
</p> </p>
@@ -68,13 +70,13 @@ export function DeploymentOverview({
</Card> </Card>
<Card className="dg-card"> <Card className="dg-card">
<CardContent className="p-3"> <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> <p className="text-lg font-bold dg-text-blue">{available}</p>
</CardContent> </CardContent>
</Card> </Card>
<Card className="dg-card"> <Card className="dg-card">
<CardContent className="p-3"> <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}> <p className="text-sm font-mono text-[var(--dg-text-secondary)] truncate max-w-[200px]" title={deployment.image}>
{deployment.image?.split('/').pop() || '-'} {deployment.image?.split('/').pop() || '-'}
</p> </p>
@@ -84,10 +86,10 @@ export function DeploymentOverview({
<CardContent className="p-3"> <CardContent className="p-3">
<p className="text-xs dg-text-muted">HPA</p> <p className="text-xs dg-text-muted">HPA</p>
{hpas.length > 0 ? ( {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"> <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 <CreateHPADialog
clusterCode={clusterCode} clusterCode={clusterCode}
namespace={namespace} namespace={namespace}
@@ -102,7 +104,7 @@ export function DeploymentOverview({
<Card className="dg-card"> <Card className="dg-card">
<CardHeader className="pb-3"> <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> </CardHeader>
<CardContent> <CardContent>
<div className="flex flex-wrap items-center gap-3"> <div className="flex flex-wrap items-center gap-3">
@@ -146,16 +148,16 @@ export function DeploymentOverview({
<Input <Input
value={newImage} value={newImage}
onChange={(e) => onNewImageChange(e.target.value)} 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" 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" <Button size="sm" className="bg-blue-600 hover:bg-blue-700"
disabled={actionLoading === 'image' || !newImage.trim()} disabled={actionLoading === 'image' || !newImage.trim()}
onClick={onUpdateImage} 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>
<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> </div>
)} )}
</CardContent> </CardContent>
@@ -22,11 +22,13 @@ import {
import { arrToText, textToArr } from './container-utils'; import { arrToText, textToArr } from './container-utils';
import type { import type {
import { useTranslation } from 'react-i18next';
ContainerEditorProps, ProbeEditorProps, LifecycleHandlerEditorProps, ContainerEditorProps, ProbeEditorProps, LifecycleHandlerEditorProps,
BoolToggleProps, ProbeDef, LifecycleHandler, BoolToggleProps, ProbeDef, LifecycleHandler,
} from './types'; } from './types';
export function ContainerEditor({ container, onUpdate }: ContainerEditorProps) { export function ContainerEditor({ container, onUpdate }: ContainerEditorProps) {
const { t } = useTranslation();
const c = container; const c = container;
const sectionBtn = "flex items-center gap-1.5 text-xs font-semibold text-[var(--dg-text-secondary)] mb-2"; 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 className="grid grid-cols-1 md:grid-cols-2 gap-3">
<div> <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 })} <Input value={c.name} onChange={e => onUpdate({ name: e.target.value })}
placeholder="my-app" placeholder="my-app"
className="mt-1 dg-input font-mono text-xs h-8" /> className="mt-1 dg-input font-mono text-xs h-8" />
</div> </div>
<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 })} <Input value={c.image} onChange={e => onUpdate({ image: e.target.value })}
placeholder="nginx:1.25" placeholder="nginx:1.25"
className="mt-1 dg-input font-mono text-xs h-8" /> className="mt-1 dg-input font-mono text-xs h-8" />
</div> </div>
<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 })}> <Select value={c.imagePullPolicy || '__none'} onValueChange={v => onUpdate({ imagePullPolicy: v === '__none' ? '' : v })}>
<SelectTrigger className="mt-1 dg-input text-xs h-8"> <SelectTrigger className="mt-1 dg-input text-xs h-8">
<SelectValue /> <SelectValue />
</SelectTrigger> </SelectTrigger>
<SelectContent className="dg-input"> <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="Always" className="text-[var(--dg-text-primary)]">Always</SelectItem>
<SelectItem value="IfNotPresent" className="text-[var(--dg-text-primary)]">IfNotPresent</SelectItem> <SelectItem value="IfNotPresent" className="text-[var(--dg-text-primary)]">IfNotPresent</SelectItem>
<SelectItem value="Never" className="text-[var(--dg-text-primary)]">Never</SelectItem> <SelectItem value="Never" className="text-[var(--dg-text-primary)]">Never</SelectItem>
@@ -61,7 +63,7 @@ export function ContainerEditor({ container, onUpdate }: ContainerEditorProps) {
</Select> </Select>
</div> </div>
<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 })} <Input value={c.workingDir || ''} onChange={e => onUpdate({ workingDir: e.target.value })}
placeholder="/app" placeholder="/app"
className="mt-1 dg-input font-mono text-xs h-8" /> 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 className="grid grid-cols-1 md:grid-cols-2 gap-3">
<div> <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"} <Textarea value={arrToText(c.command)} placeholder={"/bin/sh\n-c"}
onChange={e => onUpdate({ command: textToArr(e.target.value) })} onChange={e => onUpdate({ command: textToArr(e.target.value) })}
className="mt-1 dg-input font-mono text-xs min-h-[60px]" /> className="mt-1 dg-input font-mono text-xs min-h-[60px]" />
</div> </div>
<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"} <Textarea value={arrToText(c.args)} placeholder={"--config=/etc/app.yaml\n--debug"}
onChange={e => onUpdate({ args: textToArr(e.target.value) })} onChange={e => onUpdate({ args: textToArr(e.target.value) })}
className="mt-1 dg-input font-mono text-xs min-h-[60px]" /> className="mt-1 dg-input font-mono text-xs min-h-[60px]" />
@@ -87,7 +89,7 @@ export function ContainerEditor({ container, onUpdate }: ContainerEditorProps) {
{/* ---- 环境变量 ---- */} {/* ---- 环境变量 ---- */}
<div> <div>
<div className="flex items-center justify-between mb-2"> <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]" <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: '' }] })}> onClick={() => onUpdate({ env: [...c.env, { name: '', value: '' }] })}>
<Plus className="h-3 w-3 mr-1" />新增 <Plus className="h-3 w-3 mr-1" />新增
@@ -108,14 +110,14 @@ export function ContainerEditor({ container, onUpdate }: ContainerEditorProps) {
</Button> </Button>
</div> </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>
{/* ---- 端口 ---- */} {/* ---- 端口 ---- */}
<div> <div>
<div className="flex items-center justify-between mb-2"> <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]" <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' }] })}> onClick={() => onUpdate({ ports: [...c.ports, { name: '', containerPort: '', protocol: 'TCP' }] })}>
<Plus className="h-3 w-3 mr-1" />新增 <Plus className="h-3 w-3 mr-1" />新增
@@ -146,34 +148,34 @@ export function ContainerEditor({ container, onUpdate }: ContainerEditorProps) {
</Button> </Button>
</div> </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>
</div> </div>
{/* ---- 资源 requests/limits ---- */} {/* ---- 资源 requests/limits ---- */}
<div> <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 className="grid grid-cols-2 md:grid-cols-4 gap-2">
<div> <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" <Input value={c.resources.requests?.cpu || ''} placeholder="100m"
onChange={e => onUpdate({ resources: { ...c.resources, requests: { ...c.resources.requests, cpu: e.target.value } } })} onChange={e => onUpdate({ resources: { ...c.resources, requests: { ...c.resources.requests, cpu: e.target.value } } })}
className="dg-input font-mono text-xs h-8" /> className="dg-input font-mono text-xs h-8" />
</div> </div>
<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" <Input value={c.resources.limits?.cpu || ''} placeholder="500m"
onChange={e => onUpdate({ resources: { ...c.resources, limits: { ...c.resources.limits, cpu: e.target.value } } })} onChange={e => onUpdate({ resources: { ...c.resources, limits: { ...c.resources.limits, cpu: e.target.value } } })}
className="dg-input font-mono text-xs h-8" /> className="dg-input font-mono text-xs h-8" />
</div> </div>
<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" <Input value={c.resources.requests?.memory || ''} placeholder="128Mi"
onChange={e => onUpdate({ resources: { ...c.resources, requests: { ...c.resources.requests, memory: e.target.value } } })} onChange={e => onUpdate({ resources: { ...c.resources, requests: { ...c.resources.requests, memory: e.target.value } } })}
className="dg-input font-mono text-xs h-8" /> className="dg-input font-mono text-xs h-8" />
</div> </div>
<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" <Input value={c.resources.limits?.memory || ''} placeholder="512Mi"
onChange={e => onUpdate({ resources: { ...c.resources, limits: { ...c.resources.limits, memory: e.target.value } } })} onChange={e => onUpdate({ resources: { ...c.resources, limits: { ...c.resources.limits, memory: e.target.value } } })}
className="dg-input font-mono text-xs h-8" /> className="dg-input font-mono text-xs h-8" />
@@ -183,11 +185,11 @@ export function ContainerEditor({ container, onUpdate }: ContainerEditorProps) {
{/* ---- 健康检查 ---- */} {/* ---- 健康检查 ---- */}
<div> <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"> <div className="space-y-2">
{(['livenessProbe', 'readinessProbe', 'startupProbe'] as const).map(pt => ( {(['livenessProbe', 'readinessProbe', 'startupProbe'] as const).map(pt => (
<ProbeEditor key={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]} probe={c[pt]}
onChange={(p) => onUpdate({ [pt]: p } as Record<string, unknown>)} onChange={(p) => onUpdate({ [pt]: p } as Record<string, unknown>)}
/> />
@@ -197,11 +199,11 @@ export function ContainerEditor({ container, onUpdate }: ContainerEditorProps) {
{/* ---- 生命周期 ---- */} {/* ---- 生命周期 ---- */}
<div> <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"> <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 } })} /> 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 } })} /> onChange={h => onUpdate({ lifecycle: { ...c.lifecycle, preStop: h } })} />
</div> </div>
{!c.lifecycle && ( {!c.lifecycle && (
@@ -214,7 +216,7 @@ export function ContainerEditor({ container, onUpdate }: ContainerEditorProps) {
{/* ---- 安全上下文 ---- */} {/* ---- 安全上下文 ---- */}
<div> <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 ? ( {c.securityContext ? (
<div className="space-y-2 border border-[var(--dg-border)] rounded-md p-3 bg-[var(--dg-bg-primary)]/30"> <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"> <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" /> className="dg-input font-mono text-xs h-8" />
</div> </div>
<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" <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) } })} 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" /> className="dg-input font-mono text-xs h-8" />
</div> </div>
<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" <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) } })} 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" /> className="dg-input font-mono text-xs h-8" />
@@ -269,7 +271,7 @@ export function ContainerEditor({ container, onUpdate }: ContainerEditorProps) {
{/* ---- 卷挂载 ---- */} {/* ---- 卷挂载 ---- */}
<div> <div>
<div className="flex items-center justify-between mb-2"> <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]" <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 }] })}> onClick={() => onUpdate({ volumeMounts: [...c.volumeMounts, { name: '', mountPath: '', subPath: '', readOnly: false }] })}>
<Plus className="h-3 w-3 mr-1" />新增 <Plus className="h-3 w-3 mr-1" />新增
@@ -278,13 +280,13 @@ export function ContainerEditor({ container, onUpdate }: ContainerEditorProps) {
<div className="space-y-1.5"> <div className="space-y-1.5">
{c.volumeMounts.map((m, mi) => ( {c.volumeMounts.map((m, mi) => (
<div key={mi} className="grid grid-cols-[1fr_1fr_1fr_60px_auto] gap-2 items-center"> <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 }); }} 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" /> className="dg-input font-mono text-xs h-8" />
<Input value={m.mountPath} placeholder="/data" <Input value={m.mountPath} placeholder="/data"
onChange={e => { const n = [...c.volumeMounts]; n[mi] = { ...m, mountPath: e.target.value }; onUpdate({ volumeMounts: n }); }} 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" /> 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 }); }} 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" /> className="dg-input font-mono text-xs h-8" />
<label className="flex items-center gap-1 text-[10px] dg-text-muted cursor-pointer"> <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> </Button>
</div> </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>
</div> </div>
</> </>
@@ -306,6 +308,7 @@ export function ContainerEditor({ container, onUpdate }: ContainerEditorProps) {
} }
function ProbeEditor({ label, probe, onChange }: ProbeEditorProps) { function ProbeEditor({ label, probe, onChange }: ProbeEditorProps) {
const { t } = useTranslation();
const enabled = !!probe; const enabled = !!probe;
const p = probe || { type: 'httpGet' as const }; const p = probe || { type: 'httpGet' as const };
@@ -321,7 +324,7 @@ function ProbeEditor({ label, probe, onChange }: ProbeEditorProps) {
{enabled && ( {enabled && (
<> <>
<div className="flex items-center gap-2 mb-2"> <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'] })}> <Select value={p.type || 'httpGet'} onValueChange={v => setField({ type: v as ProbeDef['type'] })}>
<SelectTrigger className="dg-input text-xs h-7 flex-1"> <SelectTrigger className="dg-input text-xs h-7 flex-1">
<SelectValue /> <SelectValue />
@@ -329,7 +332,7 @@ function ProbeEditor({ label, probe, onChange }: ProbeEditorProps) {
<SelectContent className="dg-input"> <SelectContent className="dg-input">
<SelectItem value="httpGet" className="text-[var(--dg-text-primary)]">HTTP GET</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> <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> </SelectContent>
</Select> </Select>
</div> </div>
@@ -341,52 +344,52 @@ function ProbeEditor({ label, probe, onChange }: ProbeEditorProps) {
<Input type="number" value={p.httpPort ?? ''} placeholder="8080" <Input type="number" value={p.httpPort ?? ''} placeholder="8080"
onChange={e => setField({ httpPort: e.target.value === '' ? undefined : Number(e.target.value) })} onChange={e => setField({ httpPort: e.target.value === '' ? undefined : Number(e.target.value) })}
className="dg-input font-mono text-xs h-7" /> 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 })} onChange={e => setField({ httpHost: e.target.value })}
className="dg-input font-mono text-xs h-7" /> className="dg-input font-mono text-xs h-7" />
</div> </div>
)} )}
{p.type === 'tcpSocket' && ( {p.type === 'tcpSocket' && (
<div className="mb-2"> <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) })} onChange={e => setField({ tcpPort: e.target.value === '' ? undefined : Number(e.target.value) })}
className="dg-input font-mono text-xs h-7" /> className="dg-input font-mono text-xs h-7" />
</div> </div>
)} )}
{p.type === 'exec' && ( {p.type === 'exec' && (
<div className="mb-2"> <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 })} onChange={e => setField({ execCommand: e.target.value })}
className="dg-input font-mono text-xs min-h-[50px]" /> className="dg-input font-mono text-xs min-h-[50px]" />
</div> </div>
)} )}
<div className="grid grid-cols-5 gap-2"> <div className="grid grid-cols-5 gap-2">
<div> <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" <Input type="number" value={p.initialDelaySeconds ?? ''} placeholder="10"
onChange={e => setField({ initialDelaySeconds: e.target.value === '' ? undefined : Number(e.target.value) })} onChange={e => setField({ initialDelaySeconds: e.target.value === '' ? undefined : Number(e.target.value) })}
className="dg-input font-mono text-xs h-7" /> className="dg-input font-mono text-xs h-7" />
</div> </div>
<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" <Input type="number" value={p.periodSeconds ?? ''} placeholder="10"
onChange={e => setField({ periodSeconds: e.target.value === '' ? undefined : Number(e.target.value) })} onChange={e => setField({ periodSeconds: e.target.value === '' ? undefined : Number(e.target.value) })}
className="dg-input font-mono text-xs h-7" /> className="dg-input font-mono text-xs h-7" />
</div> </div>
<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" <Input type="number" value={p.timeoutSeconds ?? ''} placeholder="1"
onChange={e => setField({ timeoutSeconds: e.target.value === '' ? undefined : Number(e.target.value) })} onChange={e => setField({ timeoutSeconds: e.target.value === '' ? undefined : Number(e.target.value) })}
className="dg-input font-mono text-xs h-7" /> className="dg-input font-mono text-xs h-7" />
</div> </div>
<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" <Input type="number" value={p.successThreshold ?? ''} placeholder="1"
onChange={e => setField({ successThreshold: e.target.value === '' ? undefined : Number(e.target.value) })} onChange={e => setField({ successThreshold: e.target.value === '' ? undefined : Number(e.target.value) })}
className="dg-input font-mono text-xs h-7" /> className="dg-input font-mono text-xs h-7" />
</div> </div>
<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" <Input type="number" value={p.failureThreshold ?? ''} placeholder="3"
onChange={e => setField({ failureThreshold: e.target.value === '' ? undefined : Number(e.target.value) })} onChange={e => setField({ failureThreshold: e.target.value === '' ? undefined : Number(e.target.value) })}
className="dg-input font-mono text-xs h-7" /> 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) { function LifecycleHandlerEditor({ label, handler, onChange }: LifecycleHandlerEditorProps) {
const { t } = useTranslation();
const h = handler || { type: 'none' as const }; const h = handler || { type: 'none' as const };
const selVal = (!h.type || h.type === 'none') ? '__none' : h.type; 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"> <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> <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"> <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'] })}> <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"> <SelectTrigger className="dg-input text-xs h-7 flex-1">
<SelectValue /> <SelectValue />
</SelectTrigger> </SelectTrigger>
<SelectContent className="dg-input"> <SelectContent className="dg-input">
<SelectItem value="__none" className="dg-text-secondary">不设置</SelectItem> <SelectItem value="__none" className="dg-text-secondary">{t('kubernetes.containereditor.s2e3432')}</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>
<SelectItem value="httpGet" className="text-[var(--dg-text-primary)]">HTTP GET</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> <SelectItem value="tcpSocket" className="text-[var(--dg-text-primary)]">TCP Socket</SelectItem>
</SelectContent> </SelectContent>
</Select> </Select>
</div> </div>
{h.type === 'exec' && ( {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 })} onChange={e => onChange({ ...h, execCommand: e.target.value })}
className="dg-input font-mono text-xs min-h-[50px]" /> className="dg-input font-mono text-xs min-h-[50px]" />
)} )}
@@ -435,7 +439,7 @@ function LifecycleHandlerEditor({ label, handler, onChange }: LifecycleHandlerEd
</div> </div>
)} )}
{h.type === 'tcpSocket' && ( {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) })} onChange={e => onChange({ ...h, tcpPort: e.target.value === '' ? undefined : Number(e.target.value) })}
className="dg-input font-mono text-xs h-7" /> 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) { function BoolToggle({ label, value, onChange }: BoolToggleProps) {
const { t } = useTranslation();
return ( return (
<label className="flex items-center gap-1.5 cursor-pointer"> <label className="flex items-center gap-1.5 cursor-pointer">
<Switch checked={value} onCheckedChange={onChange} /> <Switch checked={value} onCheckedChange={onChange} />
@@ -16,11 +16,13 @@ import {
import { ContainerEditor } from './ContainerEditor'; import { ContainerEditor } from './ContainerEditor';
import type { ContainerGroupSectionProps } from './types'; import type { ContainerGroupSectionProps } from './types';
import { useConfirm } from '@/components/ui/confirm-dialog'; import { useConfirm } from '@/components/ui/confirm-dialog';
import { useTranslation } from 'react-i18next';
export function ContainerGroupSection({ export function ContainerGroupSection({
title, description, icon, containers, accentColor, title, description, icon, containers, accentColor,
onAdd, onRemove, onUpdate, onDuplicate, onAdd, onRemove, onUpdate, onDuplicate,
}: ContainerGroupSectionProps) { }: ContainerGroupSectionProps) {
const { t } = useTranslation();
const confirm = useConfirm(); const confirm = useConfirm();
const [openIndices, setOpenIndices] = useState<Set<number>>(new Set([0])); const [openIndices, setOpenIndices] = useState<Set<number>>(new Set([0]));
const toggleOpen = (idx: number) => { const toggleOpen = (idx: number) => {
@@ -50,7 +52,7 @@ export function ContainerGroupSection({
</CardHeader> </CardHeader>
<CardContent className="pt-0 space-y-3"> <CardContent className="pt-0 space-y-3">
{containers.length === 0 && ( {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) => { {containers.map((c, idx) => {
const isOpen = openIndices.has(idx) || containers.length === 1; const isOpen = openIndices.has(idx) || containers.length === 1;
@@ -61,22 +63,22 @@ export function ContainerGroupSection({
<div className="flex items-center gap-2"> <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" />} {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'}`} /> <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>} {c.image && <code className="text-[10px] dg-text-muted font-mono truncate max-w-[300px]">{c.image}</code>}
</div> </div>
<div className="flex items-center gap-1" onClick={e => e.stopPropagation()}> <div className="flex items-center gap-1" onClick={e => e.stopPropagation()}>
{onDuplicate && ( {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)}> onClick={() => onDuplicate(idx)}>
<RotateCw className="h-3.5 w-3.5" /> <RotateCw className="h-3.5 w-3.5" />
</Button> </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 () => { onClick={async () => {
const ok = await confirm({ const ok = await confirm({
title: '删除容器', title: t('kubernetes.containergroupsection.s860aaf'),
description: `确认删除容器「${c.name}」?`, description: t('kubernetes.containergroupsection.s04ce19', { c.name: c.name }),
confirmText: '删除', confirmText: t('common.delete'),
variant: 'destructive', variant: 'destructive',
}); });
if (ok) onRemove(idx); if (ok) onRemove(idx);
@@ -2,6 +2,7 @@
import { kubernetesApi } from '@/api'; import { kubernetesApi } from '@/api';
import { prepareManifestForSave } from './k8s-manifest-utils'; import { prepareManifestForSave } from './k8s-manifest-utils';
import { isCreateDeployment } from './deployment-constants'; import { isCreateDeployment } from './deployment-constants';
import i18n from '@/i18n';
export async function saveDeploymentManifest( export async function saveDeploymentManifest(
clusterCode: string, clusterCode: string,
@@ -10,7 +11,7 @@ export async function saveDeploymentManifest(
manifest: Record<string, any>, manifest: Record<string, any>,
): Promise<string> { ): Promise<string> {
const resName = String(manifest?.metadata?.name || '').trim(); 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); const yaml = await prepareManifestForSave(manifest);
if (isCreateDeployment(deploymentName)) { if (isCreateDeployment(deploymentName)) {
await kubernetesApi.applyYAML(clusterCode, yaml); await kubernetesApi.applyYAML(clusterCode, yaml);
@@ -3,6 +3,7 @@ import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input'; import { Input } from '@/components/ui/input';
import { RefreshCw, Plus, Loader2 } from 'lucide-react'; import { RefreshCw, Plus, Loader2 } from 'lucide-react';
import type { VolumeForm } from './deployment-volume-utils'; import type { VolumeForm } from './deployment-volume-utils';
import { useTranslation } from 'react-i18next';
export interface NamespaceResourceLists { export interface NamespaceResourceLists {
configMaps: string[]; configMaps: string[];
@@ -31,6 +32,7 @@ interface ResourcePickerProps {
export function NamespaceResourcePicker({ export function NamespaceResourcePicker({
label, value, options, loading, onChange, onRefresh, onCreate, label, value, options, loading, onChange, onRefresh, onCreate,
}: ResourcePickerProps) { }: ResourcePickerProps) {
const { t } = useTranslation();
const orphan = value && !options.includes(value); const orphan = value && !options.includes(value);
return ( return (
<div className="flex items-center gap-2 flex-wrap flex-1 min-w-0"> <div className="flex items-center gap-2 flex-wrap flex-1 min-w-0">
@@ -41,7 +43,7 @@ export function NamespaceResourcePicker({
disabled={loading} 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" 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>} {orphan && <option value={value}>{value}(未在集群中找到)</option>}
{options.map((n) => <option key={n} value={n}>{n}</option>)} {options.map((n) => <option key={n} value={n}>{n}</option>)}
</select> </select>
@@ -70,11 +72,12 @@ interface VolumeTypeFieldsProps {
export function VolumeTypeFields({ export function VolumeTypeFields({
vol, resources, resourcesLoading, onChange, onRefreshResources, onCreateResource, vol, resources, resourcesLoading, onChange, onRefreshResources, onCreateResource,
}: VolumeTypeFieldsProps) { }: VolumeTypeFieldsProps) {
const { t } = useTranslation();
if (vol.type === 'persistentVolumeClaim') { if (vol.type === 'persistentVolumeClaim') {
return ( return (
<div className="space-y-2"> <div className="space-y-2">
<NamespaceResourcePicker <NamespaceResourcePicker
label="PVC 关联" label=t('kubernetes.deploymentStorageFields.s9f74c4')
value={vol.pvcName || ''} value={vol.pvcName || ''}
options={resources.pvcs} options={resources.pvcs}
loading={resourcesLoading} loading={resourcesLoading}
@@ -92,28 +95,28 @@ export function VolumeTypeFields({
if (vol.type === 'emptyDir') { if (vol.type === 'emptyDir') {
return ( return (
<div className="flex items-center gap-2 flex-wrap"> <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 })} <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"> 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> <option value="Memory">Memory</option>
</select> </select>
<Input value={vol.sizeLimit || ''} onChange={(e) => onChange({ sizeLimit: e.target.value })} <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> </div>
); );
} }
if (vol.type === 'hostPath') { if (vol.type === 'hostPath') {
return ( return (
<div className="flex items-center gap-2 flex-wrap"> <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 })} <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" /> 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 })} <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"> 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="Directory">Directory</option>
<option value="File">File</option> <option value="File">File</option>
<option value="">默认</option> <option value="">{t('approval.status.default')}</option>
</select> </select>
</div> </div>
); );
@@ -142,9 +145,9 @@ export function VolumeTypeFields({
onCreate={() => onCreateResource('configmaps')} onCreate={() => onCreateResource('configmaps')}
/> />
<div className="flex items-center gap-2 pl-[88px]"> <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 })} <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>
</div> </div>
); );
@@ -162,15 +165,15 @@ export function VolumeTypeFields({
onCreate={() => onCreateResource('secrets')} onCreate={() => onCreateResource('secrets')}
/> />
<div className="flex items-center gap-2 pl-[88px]"> <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 })} <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>
</div> </div>
); );
} }
if (vol.type === 'custom') { 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; return null;
} }
@@ -5,6 +5,8 @@ import {
} from '../k8s-yaml-utils'; } from '../k8s-yaml-utils';
import type { PodItem } from './types'; import type { PodItem } from './types';
import type { JsonData } from '@/types/common'; import type { JsonData } from '@/types/common';
import { useTranslation } from 'react-i18next';
import i18n from '@/i18n';
export interface PodStage { export interface PodStage {
label: string; label: string;
@@ -30,15 +32,16 @@ export function getPodTimeline(pod: PodItem) {
export function getPodStages(pod: PodItem): PodStage[] { export function getPodStages(pod: PodItem): PodStage[] {
const tl = getPodTimeline(pod); const tl = getPodTimeline(pod);
return [ return [
{ label: '已调度', ts: tl.scheduled, color: STATUS_COLORS.blue }, { label: i18n.t('kubernetes.event.scheduled'), ts: tl.scheduled, color: STATUS_COLORS.blue },
{ label: '已初始化', ts: tl.initialized, color: STATUS_COLORS.orange }, { label: i18n.t('kubernetes.helpers.scee76a'), ts: tl.initialized, color: STATUS_COLORS.orange },
{ label: '容器已就绪', ts: tl.containersReady, color: STATUS_COLORS.green }, { label: i18n.t('kubernetes.helpers.s712b04'), ts: tl.containersReady, color: STATUS_COLORS.green },
{ label: '容器组已就绪', ts: tl.ready, color: STATUS_COLORS.green }, { label: i18n.t('kubernetes.helpers.s504965'), ts: tl.ready, color: STATUS_COLORS.green },
]; ];
} }
// 信息面板单项 // Logan.Li // 信息面板单项 // Logan.Li
export function InfoItem({ label, value }: { label: string; value: React.ReactNode }) { export function InfoItem({ label, value }: { label: string; value: React.ReactNode }) {
const { t } = useTranslation();
return ( return (
<div> <div>
<p className="text-xs text-[var(--dg-text-muted)] mb-1">{label}</p> <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 // 列表行紧凑就绪指示(无时间戳,避免视觉疲劳) // Logan.Li
export function PodStatusCompact({ pod }: { pod: PodItem }) { export function PodStatusCompact({ pod }: { pod: PodItem }) {
const { t } = useTranslation();
const stages = getPodStages(pod); const stages = getPodStages(pod);
const done = stages.filter(s => s.ts).length; const done = stages.filter(s => s.ts).length;
const allReady = done === stages.length; const allReady = done === stages.length;
@@ -56,7 +60,7 @@ export function PodStatusCompact({ pod }: { pod: PodItem }) {
return ( return (
<div className="flex items-center gap-2 min-w-[88px]"> <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) => ( {stages.map((s, i) => (
<Fragment key={s.label}> <Fragment key={s.label}>
<span <span
@@ -77,7 +81,7 @@ export function PodStatusCompact({ pod }: { pod: PodItem }) {
className="text-[11px] whitespace-nowrap" className="text-[11px] whitespace-nowrap"
style={{ color: allReady ? STATUS_COLORS.green : 'var(--dg-text-muted)' }} 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> </span>
</div> </div>
); );
@@ -85,13 +89,14 @@ export function PodStatusCompact({ pod }: { pod: PodItem }) {
// 详情区完整启动时间线(仅展开或概览面板使用) // Logan.Li // 详情区完整启动时间线(仅展开或概览面板使用) // Logan.Li
export function PodConditionsRow({ pod }: { pod: PodItem }) { export function PodConditionsRow({ pod }: { pod: PodItem }) {
const { t } = useTranslation();
const stages = getPodStages(pod); const stages = getPodStages(pod);
const totalBoot = elapsedSeconds(stages[0]?.ts, stages[stages.length - 1]?.ts); const totalBoot = elapsedSeconds(stages[0]?.ts, stages[stages.length - 1]?.ts);
return ( return (
<div className="rounded-lg bg-[var(--dg-bg-tertiary)]/60 px-4 py-3"> <div className="rounded-lg bg-[var(--dg-bg-tertiary)]/60 px-4 py-3">
<div className="flex items-center justify-between mb-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 && ( {totalBoot != null && (
<span className="text-[11px] text-[var(--dg-text-muted)]"> <span className="text-[11px] text-[var(--dg-text-muted)]">
总耗时 <span className="font-mono text-[var(--dg-text-secondary)]">{formatDuration(totalBoot)}</span> 总耗时 <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 { authApi } from '@/api';
import { getPublicApiBase } from '@/utils/request'; import { getPublicApiBase } from '@/utils/request';
import { getSessionApiAccessKey } from '@/utils/storage'; import { getSessionApiAccessKey } from '@/utils/storage';
import { useTranslation } from 'react-i18next';
export interface CICDWebhookContentProps { export interface CICDWebhookContentProps {
clusterCode: string; clusterCode: string;
@@ -24,6 +25,7 @@ export function CICDWebhookContent({
image = '', image = '',
containerName = '', containerName = '',
}: CICDWebhookContentProps) { }: CICDWebhookContentProps) {
const { t } = useTranslation();
const apiBase = getPublicApiBase(); const apiBase = getPublicApiBase();
const [keyLoading, setKeyLoading] = useState(true); const [keyLoading, setKeyLoading] = useState(true);
const [hasKey, setHasKey] = useState(false); const [hasKey, setHasKey] = useState(false);
@@ -55,7 +57,7 @@ export function CICDWebhookContent({
const restartUrl = `${apiBase}/kubernetes/${clusterCode}/namespace/${namespace}/deployments/${deploymentName}/restart`; const restartUrl = `${apiBase}/kubernetes/${clusterCode}/namespace/${namespace}/deployments/${deploymentName}/restart`;
const updateBody = useMemo(() => { 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; if (containerName) body.container_name = containerName;
return JSON.stringify(body); return JSON.stringify(body);
}, [image, containerName]); }, [image, containerName]);
@@ -65,16 +67,12 @@ export function CICDWebhookContent({
-H 'X-AIOps-Access-Key: ${accessKey}' \\ -H 'X-AIOps-Access-Key: ${accessKey}' \\
-H 'Content-Type: application/json' \\ -H 'Content-Type: application/json' \\
-d '${updateBody}'` -d '${updateBody}'`
: `curl -X POST '${updateUrl}' \\ : t('kubernetes.cicdwebhookcontent.s1976d2', { updateUrl: updateUrl, updateBody: updateBody });
-H 'X-AIOps-Access-Key: <个人中心生成的访问密钥>' \\
-H 'Content-Type: application/json' \\
-d '${updateBody}'`;
const restartCurl = accessKey const restartCurl = accessKey
? `curl -X POST '${restartUrl}' \\ ? `curl -X POST '${restartUrl}' \\
-H 'X-AIOps-Access-Key: ${accessKey}'` -H 'X-AIOps-Access-Key: ${accessKey}'`
: `curl -X POST '${restartUrl}' \\ : t('kubernetes.cicdwebhookcontent.s0e3668', { restartUrl: restartUrl });
-H 'X-AIOps-Access-Key: <个人中心生成的访问密钥>'`;
const canCopy = !!accessKey && !keyExpired; const canCopy = !!accessKey && !keyExpired;
@@ -88,48 +86,48 @@ export function CICDWebhookContent({
) : keyExpired ? ( ) : 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。 调整有效期或轮换凭证后再复制 curl。
</> </>
) : accessKey ? ( ) : accessKey ? (
<>已填入本机保存的访问凭证,复制 curl 后可直接在终端执行触发更新。</> <>{t('kubernetes.cicdwebhookcontent.scd2b7d')}</>
) : hasKey ? ( ) : 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 将自动填入。 轮换凭证一次,之后 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 将自动填入。 签发 CI/CD 访问凭证,curl 将自动填入。
</> </>
)} )}
</div> </div>
<CodeSnippetBlock <CodeSnippetBlock
label="更新镜像" label=t('kubernetes.deployment.updateImage')
code={updateCurl} code={updateCurl}
copyLabel="curl 已复制,可直接粘贴到终端执行" copyLabel=t('kubernetes.cicdwebhookcontent.s25a990')
copyDisabled={!canCopy} copyDisabled={!canCopy}
copyDisabledTitle="请先在个人中心签发访问凭证" copyDisabledTitle=t('kubernetes.cicdwebhookcontent.sc3bc41')
/> />
<CodeSnippetBlock <CodeSnippetBlock
label="滚动重启" label=t('kubernetes.deployment.restart')
code={restartCurl} code={restartCurl}
copyLabel="curl 已复制,可直接粘贴到终端执行" copyLabel=t('kubernetes.cicdwebhookcontent.s25a990')
copyDisabled={!canCopy} copyDisabled={!canCopy}
copyDisabledTitle="请先在个人中心签发访问凭证" copyDisabledTitle=t('kubernetes.cicdwebhookcontent.sc3bc41')
/> />
<div className="text-xs text-[var(--dg-text-muted)] space-y-1"> <div className="text-xs text-[var(--dg-text-muted)] space-y-1">
<p>• 示例镜像:<code className="text-[var(--dg-text-secondary)]">{image || '—'}</code> <p>{t('kubernetes.cicdwebhookcontent.s1bdaf4')}<code className="text-[var(--dg-text-secondary)]">{image || '—'}</code>
{containerName ? <> · 容器 <code className="text-[var(--dg-text-secondary)]">{containerName}</code></> : null} {containerName ? <> {t('kubernetes.cicdwebhookcontent.s9b07e8')} <code className="text-[var(--dg-text-secondary)]">{containerName}</code></> : null}
</p> </p>
<p>• 使用长期 API 密钥,不会随登录 JWT 过期</p> <p>{t('kubernetes.cicdwebhookcontent.se067d1')}</p>
<p>• 修改 <code className="text-[var(--dg-text-secondary)]">image</code> 字段后执行 curl 即可触发滚动更新</p> <p>{t('kubernetes.cicdwebhookcontent.s311998')} <code className="text-[var(--dg-text-secondary)]">image</code> {t('kubernetes.cicdwebhookcontent.s55260c')}</p>
<p>• 也可用 <code className="text-[var(--dg-text-secondary)]">Authorization: Bearer &lt;密钥&gt;</code></p> <p>{t('kubernetes.cicdwebhookcontent.s4e20ba')} <code className="text-[var(--dg-text-secondary)]">{t('kubernetes.cicdwebhookcontent.s67cc60')}</code></p>
</div> </div>
</div> </div>
); );
@@ -7,6 +7,7 @@ import { DeploymentEditContainers } from '../DeploymentEditContainers';
import { DeploymentEditStorage } from '../DeploymentEditStorage'; import { DeploymentEditStorage } from '../DeploymentEditStorage';
import { DeploymentEditAdvanced } from '../DeploymentEditAdvanced'; import { DeploymentEditAdvanced } from '../DeploymentEditAdvanced';
import { DeploymentEditService } from '../DeploymentEditService'; import { DeploymentEditService } from '../DeploymentEditService';
import { useTranslation } from 'react-i18next';
export interface EditModeContainerProps { export interface EditModeContainerProps {
clusterCode: string; clusterCode: string;
@@ -20,6 +21,7 @@ export interface EditModeContainerProps {
} }
export function EditModeContainer({ clusterCode, namespace, deploymentName, manifest, onSaved, onCancel, isCreate = false }: EditModeContainerProps) { export function EditModeContainer({ clusterCode, namespace, deploymentName, manifest, onSaved, onCancel, isCreate = false }: EditModeContainerProps) {
const { t } = useTranslation();
type EditTab = 'basic' | 'containers' | 'storage' | 'advanced' | 'service'; type EditTab = 'basic' | 'containers' | 'storage' | 'advanced' | 'service';
const [activeTab, setActiveTab] = useState<EditTab>('basic'); const [activeTab, setActiveTab] = useState<EditTab>('basic');
const [editManifest, setEditManifest] = useState<any>(manifest); 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 }> = [ const tabs: Array<{ key: EditTab; label: string; icon: typeof Settings }> = [
{ key: 'basic', label: '基本信息', icon: Settings }, { key: 'basic', label: t('deploy.label.basicInfo'), icon: Settings },
{ key: 'containers', label: '容器信息', icon: Container }, { key: 'containers', label: t('kubernetes.editmodecontainer.sd58c2e'), icon: Container },
{ key: 'storage', label: '存储挂载', icon: Database }, { key: 'storage', label: t('kubernetes.editmodecontainer.s9ffdac'), icon: Database },
{ key: 'advanced', label: '高级设置', icon: Settings }, { key: 'advanced', label: t('kubernetes.editmodecontainer.se37075'), icon: Settings },
{ key: 'service', label: '服务/应用路由', icon: Network }, { key: 'service', label: t('kubernetes.editmodecontainer.s8bdc2d'), icon: Network },
]; ];
const commonProps = { const commonProps = {
@@ -9,6 +9,7 @@ import { kubernetesApi } from '@/api';
import { useToast } from '@/hooks/use-toast'; import { useToast } from '@/hooks/use-toast';
import { useUserStore } from '@/store'; import { useUserStore } from '@/store';
import type { JsonData } from '@/types/common'; import type { JsonData } from '@/types/common';
import { useTranslation } from 'react-i18next';
export interface PodLogsModalProps { export interface PodLogsModalProps {
clusterCode: string; clusterCode: string;
@@ -19,6 +20,7 @@ export interface PodLogsModalProps {
} }
export function PodLogsModal({ clusterCode, namespace, podName, containers, onClose }: PodLogsModalProps) { export function PodLogsModal({ clusterCode, namespace, podName, containers, onClose }: PodLogsModalProps) {
const { t } = useTranslation();
const { toast } = useToast(); const { toast } = useToast();
const [logs, setLogs] = useState(''); const [logs, setLogs] = useState('');
const [tail, setTail] = useState(200); const [tail, setTail] = useState(200);
@@ -30,9 +32,9 @@ export function PodLogsModal({ clusterCode, namespace, podName, containers, onCl
setLoading(true); setLoading(true);
try { try {
const res: JsonData = await kubernetesApi.getPodLogs(clusterCode, namespace, podName, tail, container || undefined); 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 { } catch {
setLogs('获取日志失败'); setLogs(t('kubernetes.podlogsmodal.sc93f33'));
} finally { setLoading(false); } } finally { setLoading(false); }
}; };
@@ -57,7 +59,7 @@ export function PodLogsModal({ clusterCode, namespace, podName, containers, onCl
setLogs(buf); setLogs(buf);
} }
} catch { } catch {
toast({ title: '流式日志连接中断', variant: 'destructive' }); toast({ title: t('kubernetes.podlogsmodal.s6273c9'), variant: 'destructive' });
} finally { setStreaming(false); } } 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>)} {containers.map(c => <option key={c} value={c}>{c}</option>)}
</select> </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)} <Input type="number" value={tail} onChange={e => setTail(Number(e.target.value) || 200)}
className="w-16 h-7 dg-input text-xs" /> 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}> <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" />} {loading ? <Loader2 className="h-3 w-3 animate-spin" /> : <RefreshCw className="h-3 w-3" />}
</Button> </Button>
<Button size="sm" variant="outline" className="h-7 border-[var(--dg-border)] dg-text-green text-xs" onClick={startStream} disabled={streaming}> <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>
<Button variant="ghost" size="icon" className="h-7 w-7 dg-text-secondary" onClick={onClose}><X className="h-4 w-4" /></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> </div>
<div className="flex-1 overflow-auto p-3"> <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"> <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> </pre>
</div> </div>
</div> </div>
@@ -6,6 +6,7 @@ import { Label } from '@/components/ui/label';
import { ArrowRight, Loader2 } from 'lucide-react'; import { ArrowRight, Loader2 } from 'lucide-react';
import { joinImageRef, parseImageRef } from '../image-ref-utils'; import { joinImageRef, parseImageRef } from '../image-ref-utils';
import { ModalShell } from './ModalShell'; import { ModalShell } from './ModalShell';
import { useTranslation } from 'react-i18next';
export interface UpdateImageModalProps { export interface UpdateImageModalProps {
deployment: any; deployment: any;
@@ -24,6 +25,7 @@ export function UpdateImageModal({
onClose, onClose,
onUpdateImage, onUpdateImage,
}: UpdateImageModalProps) { }: UpdateImageModalProps) {
const { t } = useTranslation();
const currentImage = deployment?.image || ''; const currentImage = deployment?.image || '';
const current = useMemo(() => parseImageRef(currentImage), [currentImage]); const current = useMemo(() => parseImageRef(currentImage), [currentImage]);
@@ -46,14 +48,14 @@ export function UpdateImageModal({
}; };
return ( return (
<ModalShell title="调整镜像版本" onClose={onClose} size="xl"> <ModalShell title=t('kubernetes.updateimagemodal.s22a2ed') onClose={onClose} size="xl">
<div className="space-y-5"> <div className="space-y-5">
{/* 当前镜像:只读展示完整地址与 Tag // Logan.Li */} {/* 当前镜像:只读展示完整地址与 Tag // Logan.Li */}
<div className="rounded-lg border border-[var(--dg-border)]/80 bg-[var(--dg-bg-tertiary)]/40 p-4 space-y-3"> <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 className="grid grid-cols-[1fr_180px] gap-3">
<div> <div>
<Label className="dg-text-muted text-xs">镜像地址</Label> <Label className="dg-text-muted text-xs">{t('kubernetes.updateimagemodal.sdbe6a6')}</Label>
<p <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]" 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 || '-'} title={current.repository || '-'}
@@ -62,7 +64,7 @@ export function UpdateImageModal({
</p> </p>
</div> </div>
<div> <div>
<Label className="dg-text-muted text-xs">当前 Tag</Label> <Label className="dg-text-muted text-xs">{t('kubernetes.updateimagemodal.sf08c71')}</Label>
<p <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]" 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 || '-'} title={current.tag || '-'}
@@ -82,10 +84,10 @@ export function UpdateImageModal({
{/* 新镜像:地址与 Tag 分栏编辑 // Logan.Li */} {/* 新镜像:地址与 Tag 分栏编辑 // Logan.Li */}
<div className="rounded-lg border border-blue-500/30 bg-blue-500/5 p-4 space-y-3"> <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 className="grid grid-cols-[1fr_180px] gap-3">
<div> <div>
<Label className="dg-text-secondary text-xs">镜像地址</Label> <Label className="dg-text-secondary text-xs">{t('kubernetes.updateimagemodal.sdbe6a6')}</Label>
<Input <Input
value={newRepo} value={newRepo}
onChange={e => { onChange={e => {
@@ -98,7 +100,7 @@ export function UpdateImageModal({
/> />
</div> </div>
<div> <div>
<Label className="dg-text-secondary text-xs">新版本 Tag</Label> <Label className="dg-text-secondary text-xs">{t('kubernetes.updateimagemodal.s6a38a8')}</Label>
<Input <Input
value={newTag} value={newTag}
onChange={e => { onChange={e => {
@@ -113,7 +115,7 @@ export function UpdateImageModal({
</div> </div>
<div className="flex flex-wrap items-center gap-2 text-xs"> <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> <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" /> <ArrowRight className="h-3 w-3 dg-text-muted" />
<code <code
@@ -124,10 +126,10 @@ export function UpdateImageModal({
{newTag.trim() || '-'} {newTag.trim() || '-'}
</code> </code>
{!tagChanged && !repoChanged && ( {!tagChanged && !repoChanged && (
<span className="dg-text-muted">(未修改)</span> <span className="dg-text-muted">{t('kubernetes.updateimagemodal.s47c8cf')}</span>
)} )}
{repoChanged && !tagChanged && ( {repoChanged && !tagChanged && (
<span className="dg-text-yellow/80">地址已变更</span> <span className="dg-text-yellow/80">{t('kubernetes.updateimagemodal.sdb3122')}</span>
)} )}
</div> </div>
@@ -145,7 +147,7 @@ export function UpdateImageModal({
disabled={actionLoading === 'image' || !previewImage.trim() || !hasChanges} disabled={actionLoading === 'image' || !previewImage.trim() || !hasChanges}
onClick={onUpdateImage} 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> </Button>
</div> </div>
</div> </div>
@@ -1,6 +1,7 @@
// k8s-event-utils — K8s Event 字段归一化与展示 // Logan.Li // k8s-event-utils — K8s Event 字段归一化与展示 // Logan.Li
import { elapsedSeconds, formatDuration, formatK8sTime } from './k8s-yaml-utils'; import { elapsedSeconds, formatDuration, formatK8sTime } from './k8s-yaml-utils';
import type { JsonData } from '@/types/common'; import type { JsonData } from '@/types/common';
import i18n from '@/i18n';
export interface NormalizedEvent { export interface NormalizedEvent {
name: string; name: string;
@@ -59,11 +60,11 @@ export function formatEventRelative(ts: string): string {
const diff = Date.now() - new Date(ts).getTime(); const diff = Date.now() - new Date(ts).getTime();
if (diff < 0) return ''; if (diff < 0) return '';
const mins = Math.floor(diff / 60000); const mins = Math.floor(diff / 60000);
if (mins < 1) return '刚刚'; if (mins < 1) return i18n.t('task.cronJob.time.justNow');
if (mins < 60) return `${mins}分钟前`; if (mins < 60) return i18n.t('kubernetes.k8sEventUtils.s9dc098', { mins: mins });
const hrs = Math.floor(mins / 60); const hrs = Math.floor(mins / 60);
if (hrs < 24) return `${hrs}小时前`; if (hrs < 24) return i18n.t('kubernetes.k8sEventUtils.sc71bd7', { hrs: hrs });
return `${Math.floor(hrs / 24)}天前`; return i18n.t('kubernetes.k8sEventUtils.s02f1ca', { Math.floor(hrs / 24): Math.floor(hrs / 24) });
} }
/** 重复跨度:首次 → 最后 // Logan.Li */ /** 重复跨度:首次 → 最后 // Logan.Li */
@@ -3,25 +3,26 @@ import {
Network, Server, Globe, Cloud, Boxes, Database, Zap, Box, Network, Server, Globe, Cloud, Boxes, Database, Zap, Box,
} from 'lucide-react'; } from 'lucide-react';
import type { TopologyNode, TopologyEdge } from '@/types'; import type { TopologyNode, TopologyEdge } from '@/types';
import i18n from '@/i18n';
// K8s 资源类型 → 拓扑节点类型标签 // Logan.Li // K8s 资源类型 → 拓扑节点类型标签 // Logan.Li
export const NODE_TYPE_LABELS: Record<string, string> = { export const NODE_TYPE_LABELS: Record<string, string> = {
cluster: '集群', cluster: i18n.t('kubernetes.topologyHelpers.s85fe50'),
loadbalancer: 'Ingress', loadbalancer: 'Ingress',
service: 'Service', service: 'Service',
app: 'Deployment', app: 'Deployment',
pod: 'Pod', pod: 'Pod',
server: 'Node', server: 'Node',
database: '数据库', database: i18n.t('kubernetes.topologyHelpers.s68051b'),
external: '外部服务', external: i18n.t('kubernetes.topologyHelpers.s47921e'),
custom: '自定义', custom: i18n.t('common.custom'),
}; };
// 自定义节点类型选项(编辑模式用) // 自定义节点类型选项(编辑模式用)
export const CUSTOM_NODE_TYPES = [ export const CUSTOM_NODE_TYPES = [
{ value: 'database', label: '数据库', desc: 'MySQL / Redis / PostgreSQL 等' }, { value: 'database', label: i18n.t('kubernetes.topologyHelpers.s68051b'), desc: i18n.t('kubernetes.topologyHelpers.sf6a891') },
{ value: 'external', label: '外部服务', desc: '外部 API / CDN / DNS 等' }, { value: 'external', label: i18n.t('kubernetes.topologyHelpers.s47921e'), desc: i18n.t('kubernetes.topologyHelpers.s39b435') },
{ value: 'custom', label: '自定义', desc: '其他自定义节点' }, { value: 'custom', label: i18n.t('common.custom'), desc: i18n.t('kubernetes.topologyHelpers.sfb5d27') },
]; ];
// 判断是否为自定义节点(非 K8s 原生资源) // 判断是否为自定义节点(非 K8s 原生资源)
@@ -85,7 +86,7 @@ export function buildTopology( cluster: any, ingresses: any[], services: any[],
// Layer 0: Cluster // Layer 0: Cluster
const clusterId = `cluster-${cluster.id}`; const clusterId = `cluster-${cluster.id}`;
tNodes.push({ 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], 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 }, data: { kind: 'cluster', version: cluster.version, status: cluster.status, api_server: cluster.api_server, node_count: cluster.node_count, pod_count: cluster.pod_count },
}); });
+55 -52
View File
@@ -1,71 +1,73 @@
import { Link, useLocation } from 'react-router-dom'; import { Link, useLocation } from 'react-router-dom';
import { ChevronRight, Home } from 'lucide-react'; import { ChevronRight, Home } from 'lucide-react';
import { useMemo } from 'react'; import { useMemo } from 'react';
import { useTranslation } from 'react-i18next';
import i18n from '@/i18n';
/** /**
* Route name mapping - breadcrumb display names * Route name mapping - breadcrumb display names
*/ */
const ROUTE_NAME_MAP: Record<string, string> = { const ROUTE_NAME_MAP: Record<string, string> = {
'': '仪表盘', '': i18n.t('menu.dashboard'),
'servers': '服务器管理', 'servers': i18n.t('menu.servers'),
'cloud-accounts': '云账号管理', 'cloud-accounts': i18n.t('menu.cloudAccounts'),
'domains': '域名管理', 'domains': i18n.t('menu.domains'),
'regions': '区域管理', 'regions': i18n.t('menu.regions'),
'platforms': '云平台', 'platforms': i18n.t('menu.platforms'),
'cloud-billing': '云账单', 'cloud-billing': i18n.t('menu.cloudBilling'),
'kubernetes': 'Kubernetes', 'kubernetes': 'Kubernetes',
'clusters': '集群列表', 'clusters': i18n.t('menu.clusterList'),
'nodes': '节点管理', 'nodes': i18n.t('menu.nodeManagement'),
'workloads': '工作负载', 'workloads': i18n.t('menu.workloads'),
'deployments': 'Deployments', 'deployments': 'Deployments',
'statefulsets': 'StatefulSets', 'statefulsets': 'StatefulSets',
'daemonsets': 'DaemonSets', 'daemonsets': 'DaemonSets',
'cronjobs': '定时任务', 'cronjobs': i18n.t('menu.cronJobs'),
'services': 'Services', 'services': 'Services',
'ingresses': 'Ingresses', 'ingresses': 'Ingresses',
'configmaps': 'ConfigMaps', 'configmaps': 'ConfigMaps',
'secrets': 'Secrets', 'secrets': 'Secrets',
'hpas': 'HPA', 'hpas': 'HPA',
'pvcs': '存储', 'pvcs': i18n.t('menu.storage'),
'events': '事件', 'events': i18n.t('menu.events'),
'topology': '架构拓扑', 'topology': i18n.t('menu.topology'),
'namespace': '命名空间', 'namespace': i18n.t('k8s.column.namespace'),
'workload': '工作负载', 'workload': i18n.t('menu.workloads'),
'view': '查看', 'view': i18n.t('common.view'),
'edit': '编辑', 'edit': i18n.t('common.edit'),
'pipelines': '流水线', 'pipelines': i18n.t('menu.pipelines'),
'deploy': '应用发布', 'deploy': i18n.t('menu.deploy'),
'configureTools': '发布配置', 'configureTools': i18n.t('menu.deployConfig'),
'groups': '用户组', 'groups': i18n.t('pipeline.userGroup'),
'rbac': '权限管理', 'rbac': i18n.t('system.permissions'),
'monitor-center': '资源监控', 'monitor-center': i18n.t('menu.resourceMonitor'),
'log-center': '日志中心', 'log-center': i18n.t('menu.logCenter'),
'loki': 'Loki', 'loki': 'Loki',
'es': 'ES', 'es': 'ES',
'logs': '日志中心', 'logs': i18n.t('menu.logCenter'),
'trace': '链路追踪', 'trace': i18n.t('menu.trace'),
'alert-center': '告警中心', 'alert-center': i18n.t('menu.alertCenter'),
'datasources': '数据源', 'datasources': i18n.t('menu.datasources'),
'dashboards': '监控大屏', 'dashboards': i18n.t('menu.grafana'),
'host-monitor': '主机监控', 'host-monitor': i18n.t('monitor.hostMonitor'),
'alerts': '监控告警', 'alerts': i18n.t('ui.breadcrumb.sa57c10'),
'approval': '资源申请', 'approval': i18n.t('menu.approval'),
'approval-resource': '资源申请', 'approval-resource': i18n.t('menu.approval'),
'approval-app': '应用申请', 'approval-app': i18n.t('menu.approvalApp'),
'approval-permission': '权限审批', 'approval-permission': i18n.t('menu.approvalPermission'),
'approval-workflow': '审批流程', 'approval-workflow': i18n.t('menu.approvalWorkflow'),
'scripts': '脚本库', 'scripts': i18n.t('menu.scripts'),
'ansible': 'Ansible', 'ansible': 'Ansible',
'ai-assistant': '智能助手', 'ai-assistant': i18n.t('menu.aiAssistant'),
'ai-alert-analyzer': '告警分析', 'ai-alert-analyzer': i18n.t('aiops.alertAnalysis'),
'ai-predictive': '容量预测', 'ai-predictive': i18n.t('aiops.predictive'),
'users': '用户管理', 'users': i18n.t('menu.users'),
'roles': '角色权限', 'roles': i18n.t('menu.roles'),
'logs-audit': '操作审计', 'logs-audit': i18n.t('system.auditLog'),
'terminal-audit': '终端审计', 'terminal-audit': i18n.t('system.terminal'),
'credentials': '凭证配置', 'credentials': i18n.t('menu.credentials'),
'settings': '系统设置', 'settings': i18n.t('menu.settings'),
}; };
interface BreadcrumbItem { interface BreadcrumbItem {
@@ -81,12 +83,13 @@ interface BreadcrumbItem {
* 支持动态参数(如 clusterCode, namespace, name)显示 * 支持动态参数(如 clusterCode, namespace, name)显示
*/ */
export function Breadcrumb() { export function Breadcrumb() {
const { t } = useTranslation();
const location = useLocation(); const location = useLocation();
const breadcrumbs = useMemo<BreadcrumbItem[]>(() => { const breadcrumbs = useMemo<BreadcrumbItem[]>(() => {
const paths = location.pathname.split('/').filter(Boolean); const paths = location.pathname.split('/').filter(Boolean);
if (paths.length === 0) { if (paths.length === 0) {
return [{ name: '仪表盘', path: '/', isLast: true }]; return [{ name: t('menu.dashboard'), path: '/', isLast: true }];
} }
const items: BreadcrumbItem[] = []; const items: BreadcrumbItem[] = [];
@@ -102,10 +105,10 @@ export function Breadcrumb() {
// 日志中心子路由区分 // Logan.Li // 日志中心子路由区分 // Logan.Li
if (segment === 'alerts' && paths[index - 1] === 'log-center') { if (segment === 'alerts' && paths[index - 1] === 'log-center') {
displayName = '日志告警'; displayName = t('menu.logAlerts');
} }
if (segment === 'datasources' && paths[index - 1] === 'log-center') { if (segment === 'datasources' && paths[index - 1] === 'log-center') {
displayName = '日志库'; displayName = t('menu.logLibrary');
} }
if (!displayName) { if (!displayName) {
@@ -135,13 +138,13 @@ export function Breadcrumb() {
return ( return (
<nav <nav
aria-label="面包屑导航" aria-label=t('ui.breadcrumb.s357625')
className="flex items-center gap-1.5 text-sm animate-fade-in" className="flex items-center gap-1.5 text-sm animate-fade-in"
> >
<Link <Link
to="/" to="/"
className="flex items-center gap-1 text-[var(--dg-text-muted)] hover:text-[var(--dg-blue)] transition-colors duration-200" className="flex items-center gap-1 text-[var(--dg-text-muted)] hover:text-[var(--dg-blue)] transition-colors duration-200"
title="仪表盘" title=t('menu.dashboard')
> >
<Home className="h-3.5 w-3.5" /> <Home className="h-3.5 w-3.5" />
</Link> </Link>
@@ -2,6 +2,7 @@ import { Component, type ErrorInfo, type ReactNode } from 'react';
import { Button } from '@/components/ui/button'; import { Button } from '@/components/ui/button';
import { AlertTriangle, RotateCcw, Home, Bug } from 'lucide-react'; import { AlertTriangle, RotateCcw, Home, Bug } from 'lucide-react';
import { toast } from 'sonner'; import { toast } from 'sonner';
import i18n from '@/i18n';
interface Props { interface Props {
children: ReactNode; children: ReactNode;
@@ -31,8 +32,8 @@ export class ErrorBoundary extends Component<Props, State> {
} }
override componentDidCatch(error: Error, errorInfo: ErrorInfo) { override componentDidCatch(error: Error, errorInfo: ErrorInfo) {
console.error('[ErrorBoundary] 捕获到错误:', error); console.error(i18n.t('ui.errorboundary.sc0bdc3'), error);
console.error('[ErrorBoundary] 错误信息:', errorInfo.componentStack); console.error(i18n.t('ui.errorboundary.s1f72f8'), errorInfo.componentStack);
this.setState({ error, errorInfo }); this.setState({ error, errorInfo });
} }
@@ -46,11 +47,11 @@ export class ErrorBoundary extends Component<Props, State> {
handleReport = () => { handleReport = () => {
const { error, errorInfo } = this.state; const { error, errorInfo } = this.state;
const body = `## 错误报告\n\n**时间:** ${new Date().toISOString()}\n**URL:** ${window.location.href}\n**用户代理:** ${navigator.userAgent}\n\n### 错误信息\n\n\`\`\`\n${error?.name}: ${error?.message}\n\`\`\`\n\n### 组件堆栈\n\n\`\`\`\n${errorInfo?.componentStack}\n\`\`\`\n`; const body = i18n.t('ui.errorboundary.s8f0ca2', { new Date().toISOString(): new Date().toISOString(), window.location.href: window.location.href, navigator.userAgent: navigator.userAgent, error?.name: error?.name, error?.message: error?.message, errorInfo?.componentStack: errorInfo?.componentStack });
navigator.clipboard.writeText(body).then(() => { navigator.clipboard.writeText(body).then(() => {
toast.success('错误信息已复制到剪贴板,请粘贴到 Issue 中'); toast.success(i18n.t('ui.errorboundary.sf29c9d'));
}).catch(() => { }).catch(() => {
toast.error('复制失败,请手动复制错误信息'); toast.error(i18n.t('ui.errorboundary.s7b5065'));
}); });
}; };
@@ -7,12 +7,14 @@ import { Header } from './Header';
import { Breadcrumb } from './Breadcrumb'; import { Breadcrumb } from './Breadcrumb';
import { authApi } from '@/api'; import { authApi } from '@/api';
import type { JsonData } from '@/types/common'; import type { JsonData } from '@/types/common';
import { useTranslation } from 'react-i18next';
/** /**
* MainLayout — 统一应用布局壳 * MainLayout — 统一应用布局壳
* 侧栏 + 顶栏 + 面包屑 + 内容区,间距由 --layout-* 令牌驱动 // Logan.Li * 侧栏 + 顶栏 + 面包屑 + 内容区,间距由 --layout-* 令牌驱动 // Logan.Li
*/ */
export function MainLayout() { export function MainLayout() {
const { t } = useTranslation();
const { sidebarCollapsed } = useThemeStore(); const { sidebarCollapsed } = useThemeStore();
const token = useUserStore((s) => s.token); const token = useUserStore((s) => s.token);
const permissions = useUserStore((s) => s.permissions); const permissions = useUserStore((s) => s.permissions);
@@ -59,7 +61,7 @@ export function MainLayout() {
</main> </main>
<footer className="dg-app-footer"> <footer className="dg-app-footer">
<div className="flex items-center justify-between text-xs dg-text-muted"> <div className="flex items-center justify-between text-xs dg-text-muted">
<span>AIOps 智能运维平台</span> <span>{t('login.title')}</span>
<span>v1.0.0</span> <span>v1.0.0</span>
</div> </div>
</footer> </footer>
@@ -18,6 +18,7 @@ import { Plus, Trash2, Loader2 } from 'lucide-react';
import { alertApi } from '@/api'; import { alertApi } from '@/api';
import { CHANNEL_TYPES, getChannelTypeLabel } from './alertShared'; import { CHANNEL_TYPES, getChannelTypeLabel } from './alertShared';
import type { AlertChannel } from '@/types'; import type { AlertChannel } from '@/types';
import { useTranslation } from 'react-i18next';
const defaultChannelForm = { name: '', type: 'dingtalk', config: '', enabled: true }; const defaultChannelForm = { name: '', type: 'dingtalk', config: '', enabled: true };
@@ -32,6 +33,7 @@ export function AlertChannelDialog({
notifyChannels: AlertChannel[]; notifyChannels: AlertChannel[];
onChannelsChanged: () => void; onChannelsChanged: () => void;
}) { }) {
const { t } = useTranslation();
const _confirm = useConfirm(); const _confirm = useConfirm();
const [editingChannel, setEditingChannel] = useState<AlertChannel | null>(null); const [editingChannel, setEditingChannel] = useState<AlertChannel | null>(null);
const [channelSaving, setChannelSaving] = useState(false); const [channelSaving, setChannelSaving] = useState(false);
@@ -85,7 +87,7 @@ export function AlertChannelDialog({
}; };
const handleDeleteChannel = async ( id: number) => { const handleDeleteChannel = async ( id: number) => {
{ const ok = await _confirm({ title: '删除通知渠道', description: '确定删除此通知渠道?', confirmText: '删除', variant: 'destructive' }); if (!ok) return; } { const ok = await _confirm({ title: t('monitor.alertchanneldialog.sa4450b'), description: t('monitor.alertchanneldialog.sb1a9e5'), confirmText: t('common.delete'), variant: 'destructive' }); if (!ok) return; }
try { try {
await alertApi.deleteNotifyChannel(id); await alertApi.deleteNotifyChannel(id);
if (editingChannel && editingChannel.id === id) resetChannelForm(); if (editingChannel && editingChannel.id === id) resetChannelForm();
@@ -120,7 +122,7 @@ export function AlertChannelDialog({
<Dialog open={open} onOpenChange={onOpenChange}> <Dialog open={open} onOpenChange={onOpenChange}>
<DialogContent className="dg-input max-w-2xl"> <DialogContent className="dg-input max-w-2xl">
<DialogHeader> <DialogHeader>
<DialogTitle className="text-[var(--dg-text-primary)]">通知渠道配置</DialogTitle> <DialogTitle className="text-[var(--dg-text-primary)]">{t('monitor.alertchanneldialog.s976ad4')}</DialogTitle>
<DialogDescription className="dg-text-muted"> <DialogDescription className="dg-text-muted">
管理告警通知渠道(钉钉/企业微信/邮件/短信/Webhook),配置后可在告警规则中引用 管理告警通知渠道(钉钉/企业微信/邮件/短信/Webhook),配置后可在告警规则中引用
</DialogDescription> </DialogDescription>
@@ -130,7 +132,7 @@ export function AlertChannelDialog({
{/* 渠道列表 */} {/* 渠道列表 */}
<div className="space-y-2"> <div className="space-y-2">
<div className="flex items-center justify-between"> <div className="flex items-center justify-between">
<Label className="text-[var(--dg-text-secondary)] text-sm">已配置渠道</Label> <Label className="text-[var(--dg-text-secondary)] text-sm">{t('monitor.alertchanneldialog.se6ad00')}</Label>
<Button <Button
size="sm" size="sm"
variant="outline" variant="outline"
@@ -173,9 +175,9 @@ export function AlertChannelDialog({
</div> </div>
<div className="flex items-center justify-between mt-2"> <div className="flex items-center justify-between mt-2">
{ch.test_status === 'success' ? ( {ch.test_status === 'success' ? (
<span className="text-[11px] dg-text-green">测试通过</span> <span className="text-[11px] dg-text-green">{t('monitor.alertchanneldialog.sd25431')}</span>
) : ( ) : (
<span className="text-[11px] dg-text-muted">未测试</span> <span className="text-[11px] dg-text-muted">{t('monitor.alertchanneldialog.s8c852a')}</span>
)} )}
<div className="flex items-center gap-1" onClick={(e) => e.stopPropagation()}> <div className="flex items-center gap-1" onClick={(e) => e.stopPropagation()}>
<Button <Button
@@ -185,7 +187,7 @@ export function AlertChannelDialog({
disabled={channelTesting === ch.id} disabled={channelTesting === ch.id}
onClick={() => handleTestChannel(ch.id)} onClick={() => handleTestChannel(ch.id)}
> >
{channelTesting === ch.id ? <Loader2 className="h-3 w-3 animate-spin" /> : '测试'} {channelTesting === ch.id ? <Loader2 className="h-3 w-3 animate-spin" /> : t('common.test')}
</Button> </Button>
<Button <Button
size="sm" size="sm"
@@ -206,19 +208,19 @@ export function AlertChannelDialog({
{/* 渠道表单 */} {/* 渠道表单 */}
<div className="space-y-4"> <div className="space-y-4">
<Label className="text-[var(--dg-text-secondary)] text-sm"> <Label className="text-[var(--dg-text-secondary)] text-sm">
{editingChannel ? '编辑渠道' : '新建渠道'} {editingChannel ? t('monitor.alertchanneldialog.sc47145') : t('monitor.alertchanneldialog.s82bd47')}
</Label> </Label>
<div className="space-y-1.5"> <div className="space-y-1.5">
<Label className="dg-text-secondary text-xs">渠道名称 <span className="dg-text-red">*</span></Label> <Label className="dg-text-secondary text-xs">{t('monitor.alertchanneldialog.sb8cbd8')} <span className="dg-text-red">*</span></Label>
<Input <Input
value={channelForm.name} value={channelForm.name}
onChange={(e) => setChannelForm({ ...channelForm, name: e.target.value })} onChange={(e) => setChannelForm({ ...channelForm, name: e.target.value })}
placeholder="如:运维告警群" placeholder=t('monitor.alertchanneldialog.s6906c9')
className="dg-input h-9" className="dg-input h-9"
/> />
</div> </div>
<div className="space-y-1.5"> <div className="space-y-1.5">
<Label className="dg-text-secondary text-xs">渠道类型</Label> <Label className="dg-text-secondary text-xs">{t('monitor.channelType')}</Label>
<select <select
value={channelForm.type} value={channelForm.type}
onChange={(e) => setChannelForm({ ...channelForm, type: e.target.value })} onChange={(e) => setChannelForm({ ...channelForm, type: e.target.value })}
@@ -230,7 +232,7 @@ export function AlertChannelDialog({
</select> </select>
</div> </div>
<div className="space-y-1.5"> <div className="space-y-1.5">
<Label className="dg-text-secondary text-xs">配置(JSON)</Label> <Label className="dg-text-secondary text-xs">{t('monitor.alertchanneldialog.s9ca77d')}</Label>
<Textarea <Textarea
value={channelForm.config} value={channelForm.config}
onChange={(e) => setChannelForm({ ...channelForm, config: e.target.value })} onChange={(e) => setChannelForm({ ...channelForm, config: e.target.value })}
@@ -246,7 +248,7 @@ export function AlertChannelDialog({
onCheckedChange={(v) => setChannelForm({ ...channelForm, enabled: v })} onCheckedChange={(v) => setChannelForm({ ...channelForm, enabled: v })}
className="data-[state=checked]:bg-emerald-600" className="data-[state=checked]:bg-emerald-600"
/> />
<Label className="dg-text-secondary text-xs">启用此渠道</Label> <Label className="dg-text-secondary text-xs">{t('monitor.alertchanneldialog.sbdab1c')}</Label>
</div> </div>
)} )}
</div> </div>
@@ -266,7 +268,7 @@ export function AlertChannelDialog({
onClick={handleSaveChannel} onClick={handleSaveChannel}
> >
{channelSaving && <Loader2 className="h-4 w-4 mr-2 animate-spin" />} {channelSaving && <Loader2 className="h-4 w-4 mr-2 animate-spin" />}
{editingChannel ? '保存修改' : '添加渠道'} {editingChannel ? i18n.t('cloud.saveChanges') : i18n.t('monitor.alertchanneldialog.s22d04e')}
</Button> </Button>
</DialogFooter> </DialogFooter>
</DialogContent> </DialogContent>
@@ -20,8 +20,10 @@ import { PageShell } from '@/components/layout/PageShell';
import { StatStrip } from '@/components/ui/stat-strip'; import { StatStrip } from '@/components/ui/stat-strip';
import type { JsonData } from '@/types/common'; import type { JsonData } from '@/types/common';
import type { AlertEventRecord, AlertRuleRecord, AlertChannel } from '@/types'; import type { AlertEventRecord, AlertRuleRecord, AlertChannel } from '@/types';
import { useTranslation } from 'react-i18next';
export function AlertManager() { export function AlertManager() {
const { t } = useTranslation();
const [activeTab, setActiveTab] = useState('events'); const [activeTab, setActiveTab] = useState('events');
const [alerts, setAlerts] = useState<AlertEventRecord[]>([]); const [alerts, setAlerts] = useState<AlertEventRecord[]>([]);
const [rules, setRules] = useState<AlertRuleRecord[]>([]); const [rules, setRules] = useState<AlertRuleRecord[]>([]);
@@ -75,15 +77,15 @@ export function AlertManager() {
]; ];
const pageTabs = [ const pageTabs = [
{ id: 'events', label: '告警事件' }, { id: 'events', label: t('monitor.alertmanager.s0e5b83') },
{ id: 'rules', label: '告警规则' }, { id: 'rules', label: t('alert.tab.rules') },
]; ];
return ( return (
<PageShell <PageShell
variant="list" variant="list"
title="监控告警" title=t('monitor.alertmanager.sa57c10')
subtitle="告警规则管理与告警事件处理" subtitle=t('monitor.alertmanager.s1a70ca')
icon={<Bell className="h-5 w-5" />} icon={<Bell className="h-5 w-5" />}
tabs={pageTabs} tabs={pageTabs}
activeTab={activeTab} activeTab={activeTab}
@@ -91,10 +93,10 @@ export function AlertManager() {
metrics={( metrics={(
<StatStrip <StatStrip
items={[ items={[
{ label: '告警规则', value: rules.length, color: 'blue' }, { label: t('alert.tab.rules'), value: rules.length, color: 'blue' },
{ label: '触发中', value: alerts.filter((e) => e.status === 'firing').length, color: 'red' }, { label: t('monitor.firing'), value: alerts.filter((e) => e.status === 'firing').length, color: 'red' },
{ label: '今日告警', value: alerts.length, color: 'amber' }, { label: t('monitor.alertmanager.s240597'), value: alerts.length, color: 'amber' },
{ label: '已恢复', value: alerts.filter((e) => e.status === 'resolved').length, color: 'emerald' }, { label: t('kubernetes.deployment.resumed'), value: alerts.filter((e) => e.status === 'resolved').length, color: 'emerald' },
]} ]}
/> />
)} )}
@@ -117,8 +119,8 @@ export function AlertManager() {
> >
<Card className="dg-card"> <Card className="dg-card">
<CardHeader className="pb-2"> <CardHeader className="pb-2">
<CardTitle className="text-[var(--dg-text-primary)]">告警趋势</CardTitle> <CardTitle className="text-[var(--dg-text-primary)]">{t('monitor.alertmanager.s358b05')}</CardTitle>
<CardDescription className="dg-text-muted">过去24小时告警统计</CardDescription> <CardDescription className="dg-text-muted">{t('monitor.alertmanager.s615fa6')}</CardDescription>
</CardHeader> </CardHeader>
<CardContent> <CardContent>
<div className="h-[200px]"> <div className="h-[200px]">
@@ -151,7 +153,7 @@ export function AlertManager() {
stroke="#ef4444" stroke="#ef4444"
fillOpacity={1} fillOpacity={1}
fill="url(#colorCritical)" fill="url(#colorCritical)"
name="严重" name=t('monitor.critical')
/> />
<Area <Area
type="monotone" type="monotone"
@@ -159,7 +161,7 @@ export function AlertManager() {
stroke="#f59e0b" stroke="#f59e0b"
fillOpacity={1} fillOpacity={1}
fill="url(#colorWarning)" fill="url(#colorWarning)"
name="警告" name=t('common.warning')
/> />
</AreaChart> </AreaChart>
</ResponsiveContainer> </ResponsiveContainer>
@@ -16,6 +16,7 @@ import { Loader2 } from 'lucide-react';
import { alertApi, logCenterApi, type LogDataSource } from '@/api'; import { alertApi, logCenterApi, type LogDataSource } from '@/api';
import { parseChannels, getChannelIcon, getChannelTypeLabel } from './alertShared'; import { parseChannels, getChannelIcon, getChannelTypeLabel } from './alertShared';
import type { JsonData } from '@/types/common'; import type { JsonData } from '@/types/common';
import { useTranslation } from 'react-i18next';
const emptyRuleForm = { const emptyRuleForm = {
name: '', name: '',
@@ -45,6 +46,7 @@ export function AlertRuleDialog({
/** 新建时默认规则类型 // Logan.Li */ /** 新建时默认规则类型 // Logan.Li */
defaultType?: 'metric' | 'log' | 'event'; defaultType?: 'metric' | 'log' | 'event';
}) { }) {
const { t } = useTranslation();
const [ruleForm, setRuleForm] = useState({ ...emptyRuleForm }); const [ruleForm, setRuleForm] = useState({ ...emptyRuleForm });
const [ruleSaving, setRuleSaving] = useState(false); const [ruleSaving, setRuleSaving] = useState(false);
const [logSources, setLogSources] = useState<LogDataSource[]>([]); const [logSources, setLogSources] = useState<LogDataSource[]>([]);
@@ -127,30 +129,30 @@ export function AlertRuleDialog({
<DialogContent className="dg-input max-w-lg"> <DialogContent className="dg-input max-w-lg">
<DialogHeader> <DialogHeader>
<DialogTitle className="text-[var(--dg-text-primary)]"> <DialogTitle className="text-[var(--dg-text-primary)]">
{editingRule ? '编辑告警规则' : '新建告警规则'} {editingRule ? t('monitor.alertruledialog.sb62c8b') : t('monitor.alertruledialog.s3564fa')}
</DialogTitle> </DialogTitle>
<DialogDescription className="dg-text-muted"> <DialogDescription className="dg-text-muted">
{editingRule ? '修改告警规则的触发条件和通知方式' : '配置监控指标的告警触发条件'} {editingRule ? t('monitor.alertruledialog.s44a3bb') : t('monitor.alertruledialog.sb785ec')}
</DialogDescription> </DialogDescription>
</DialogHeader> </DialogHeader>
<div className="space-y-4 max-h-[60vh] overflow-y-auto pr-1"> <div className="space-y-4 max-h-[60vh] overflow-y-auto pr-1">
<div className="space-y-1.5"> <div className="space-y-1.5">
<Label className="text-[var(--dg-text-secondary)]">规则名称 <span className="dg-text-red">*</span></Label> <Label className="text-[var(--dg-text-secondary)]">{t('monitor.ruleName')} <span className="dg-text-red">*</span></Label>
<Input <Input
value={ruleForm.name} value={ruleForm.name}
onChange={(e) => setRuleForm({ ...ruleForm, name: e.target.value })} onChange={(e) => setRuleForm({ ...ruleForm, name: e.target.value })}
placeholder="如:CPU 使用率告警" placeholder=t('monitor.alertruledialog.sf111cd')
className="dg-input" className="dg-input"
/> />
</div> </div>
<div className="space-y-1.5"> <div className="space-y-1.5">
<Label className="text-[var(--dg-text-secondary)]">描述</Label> <Label className="text-[var(--dg-text-secondary)]">{t('common.description')}</Label>
<Textarea <Textarea
value={ruleForm.description} value={ruleForm.description}
onChange={(e) => setRuleForm({ ...ruleForm, description: e.target.value })} onChange={(e) => setRuleForm({ ...ruleForm, description: e.target.value })}
placeholder="规则说明" placeholder=t('monitor.alertruledialog.scc807b')
rows={2} rows={2}
className="dg-input resize-none" className="dg-input resize-none"
/> />
@@ -158,7 +160,7 @@ export function AlertRuleDialog({
<div className="grid grid-cols-2 gap-3"> <div className="grid grid-cols-2 gap-3">
<div className="space-y-1.5"> <div className="space-y-1.5">
<Label className="text-[var(--dg-text-secondary)]">规则类型</Label> <Label className="text-[var(--dg-text-secondary)]">{t('monitor.alertruledialog.s365825')}</Label>
<select <select
value={ruleForm.type} value={ruleForm.type}
onChange={(e) => { onChange={(e) => {
@@ -168,13 +170,13 @@ export function AlertRuleDialog({
}} }}
className="w-full h-9 px-3 rounded-md bg-[var(--dg-bg-tertiary)]/50 border border-[var(--dg-border)] text-[var(--dg-text-primary)] text-sm" className="w-full h-9 px-3 rounded-md bg-[var(--dg-bg-tertiary)]/50 border border-[var(--dg-border)] text-[var(--dg-text-primary)] text-sm"
> >
<option value="metric">指标监控</option> <option value="metric">{t('monitor.alertruledialog.s38546d')}</option>
<option value="log">日志告警</option> <option value="log">{t('menu.logAlerts')}</option>
<option value="event">事件告警</option> <option value="event">{t('monitor.alertruledialog.s80069b')}</option>
</select> </select>
</div> </div>
<div className="space-y-1.5"> <div className="space-y-1.5">
<Label className="text-[var(--dg-text-secondary)]">数据源</Label> <Label className="text-[var(--dg-text-secondary)]">{t('menu.datasources')}</Label>
<select <select
value={ruleForm.source} value={ruleForm.source}
onChange={(e) => setRuleForm({ ...ruleForm, source: e.target.value, datasource_id: undefined })} onChange={(e) => setRuleForm({ ...ruleForm, source: e.target.value, datasource_id: undefined })}
@@ -189,7 +191,7 @@ export function AlertRuleDialog({
<> <>
<option value="prometheus">Prometheus</option> <option value="prometheus">Prometheus</option>
<option value="zabbix">Zabbix</option> <option value="zabbix">Zabbix</option>
<option value="custom">自定义</option> <option value="custom">{t('common.custom')}</option>
</> </>
)} )}
</select> </select>
@@ -198,15 +200,15 @@ export function AlertRuleDialog({
{ruleForm.type === 'log' && ( {ruleForm.type === 'log' && (
<div className="space-y-1.5"> <div className="space-y-1.5">
<Label className="text-[var(--dg-text-secondary)]">日志数据源 <span className="dg-text-red">*</span></Label> <Label className="text-[var(--dg-text-secondary)]">{t('monitor.alertruledialog.sa2bc1e')} <span className="dg-text-red">*</span></Label>
<select <select
value={ruleForm.datasource_id || ''} value={ruleForm.datasource_id || ''}
onChange={(e) => setRuleForm({ ...ruleForm, datasource_id: Number(e.target.value) || undefined })} onChange={(e) => setRuleForm({ ...ruleForm, datasource_id: Number(e.target.value) || undefined })}
className="w-full h-9 px-3 rounded-md bg-[var(--dg-bg-tertiary)]/50 border border-[var(--dg-border)] text-[var(--dg-text-primary)] text-sm" className="w-full h-9 px-3 rounded-md bg-[var(--dg-bg-tertiary)]/50 border border-[var(--dg-border)] text-[var(--dg-text-primary)] text-sm"
> >
<option value="">请选择数据源</option> <option value="">{t('monitor.alertruledialog.s9acb96')}</option>
{logSources.map((s) => ( {logSources.map((s) => (
<option key={s.id} value={s.id}>{s.name}{s.is_default ? ' (默认)' : ''}</option> <option key={s.id} value={s.id}>{s.name}{s.is_default ? t('monitor.alertruledialog.see1f37') : ''}</option>
))} ))}
</select> </select>
{logSources.length === 0 && ( {logSources.length === 0 && (
@@ -216,7 +218,7 @@ export function AlertRuleDialog({
)} )}
<div className="space-y-1.5"> <div className="space-y-1.5">
<Label className="text-[var(--dg-text-secondary)]">触发表达式 <span className="dg-text-red">*</span></Label> <Label className="text-[var(--dg-text-secondary)]">{t('monitor.alertruledialog.s57ee9a')} <span className="dg-text-red">*</span></Label>
<Input <Input
value={ruleForm.expression} value={ruleForm.expression}
onChange={(e) => setRuleForm({ ...ruleForm, expression: e.target.value })} onChange={(e) => setRuleForm({ ...ruleForm, expression: e.target.value })}
@@ -225,26 +227,26 @@ export function AlertRuleDialog({
/> />
<p className="text-xs dg-text-muted"> <p className="text-xs dg-text-muted">
{ruleForm.type === 'log' {ruleForm.type === 'log'
? (ruleForm.source === 'loki' ? 'LogQL 查询或 count_over_time 表达式' : 'Elasticsearch Lucene 查询') ? (ruleForm.source === 'loki' ? t('monitor.alertruledialog.s465c2b') : t('monitor.alertruledialog.s7072bc'))
: 'PromQL 或指标表达式,例如 cpu_usage > 80'} : t('monitor.alertruledialog.se2017e')}
</p> </p>
</div> </div>
<div className="grid grid-cols-2 gap-3"> <div className="grid grid-cols-2 gap-3">
<div className="space-y-1.5"> <div className="space-y-1.5">
<Label className="text-[var(--dg-text-secondary)]">告警级别</Label> <Label className="text-[var(--dg-text-secondary)]">{t('monitor.alertruledialog.sfce93b')}</Label>
<select <select
value={ruleForm.severity} value={ruleForm.severity}
onChange={(e) => setRuleForm({ ...ruleForm, severity: e.target.value })} onChange={(e) => setRuleForm({ ...ruleForm, severity: e.target.value })}
className="w-full h-9 px-3 rounded-md bg-[var(--dg-bg-tertiary)]/50 border border-[var(--dg-border)] text-[var(--dg-text-primary)] text-sm" className="w-full h-9 px-3 rounded-md bg-[var(--dg-bg-tertiary)]/50 border border-[var(--dg-border)] text-[var(--dg-text-primary)] text-sm"
> >
<option value="info">提示</option> <option value="info">{t('common.info')}</option>
<option value="warning">警告</option> <option value="warning">{t('common.warning')}</option>
<option value="critical">严重</option> <option value="critical">{t('monitor.critical')}</option>
</select> </select>
</div> </div>
<div className="space-y-1.5"> <div className="space-y-1.5">
<Label className="text-[var(--dg-text-secondary)]">持续时间(秒)</Label> <Label className="text-[var(--dg-text-secondary)]">{t('monitor.alertruledialog.scce774')}</Label>
<Input <Input
type="number" type="number"
value={ruleForm.duration} value={ruleForm.duration}
@@ -255,7 +257,7 @@ export function AlertRuleDialog({
</div> </div>
<div className="space-y-1.5"> <div className="space-y-1.5">
<Label className="text-[var(--dg-text-secondary)]">通知渠道</Label> <Label className="text-[var(--dg-text-secondary)]">{t('monitor.notificationChannel')}</Label>
{notifyChannels.length === 0 ? ( {notifyChannels.length === 0 ? (
<div className="text-xs dg-text-yellow/80 bg-amber-500/5 border border-amber-500/20 rounded-md px-3 py-2"> <div className="text-xs dg-text-yellow/80 bg-amber-500/5 border border-amber-500/20 rounded-md px-3 py-2">
暂无已配置的通知渠道,请先在「通知渠道配置」中添加 暂无已配置的通知渠道,请先在「通知渠道配置」中添加
@@ -302,7 +304,7 @@ export function AlertRuleDialog({
onClick={handleSaveRule} onClick={handleSaveRule}
> >
{ruleSaving && <Loader2 className="h-4 w-4 mr-2 animate-spin" />} {ruleSaving && <Loader2 className="h-4 w-4 mr-2 animate-spin" />}
{editingRule ? '保存修改' : '创建规则'} {editingRule ? i18n.t('cloud.saveChanges') : i18n.t('monitor.alertruledialog.s8e1e3d')}
</Button> </Button>
</DialogFooter> </DialogFooter>
</DialogContent> </DialogContent>
@@ -18,6 +18,7 @@ import { toast } from 'sonner';
import { alertApi } from '@/api'; import { alertApi } from '@/api';
import { renderRuleChannels } from './alertShared'; import { renderRuleChannels } from './alertShared';
import type { AlertChannel, AlertRuleRecord } from '@/types'; import type { AlertChannel, AlertRuleRecord } from '@/types';
import { useTranslation } from 'react-i18next';
const COL_SPAN = 9; // 复选框 + 7 数据列 + 操作列 // Logan.Li const COL_SPAN = 9; // 复选框 + 7 数据列 + 操作列 // Logan.Li
@@ -32,6 +33,7 @@ export function AlertRulesTab({
onReload: () => void; onReload: () => void;
onEditRule: ( rule: AlertRuleRecord) => void; onEditRule: ( rule: AlertRuleRecord) => void;
}) { }) {
const { t } = useTranslation();
const confirm = useConfirm(); const confirm = useConfirm();
const [selectedIds, setSelectedIds] = useState<number[]>([]); const [selectedIds, setSelectedIds] = useState<number[]>([]);
@@ -53,19 +55,19 @@ export function AlertRulesTab({
const handleDeleteRule = async ( id: number) => { const handleDeleteRule = async ( id: number) => {
const ok = await confirm({ const ok = await confirm({
title: '删除告警规则', title: t('monitor.alertrulestab.sfa5bfd'),
description: '确定删除此告警规则?', description: t('monitor.alertrulestab.sd30155'),
confirmText: '删除', confirmText: t('common.delete'),
variant: 'destructive', variant: 'destructive',
}); });
if (!ok) return; if (!ok) return;
try { try {
await alertApi.deleteRule(id); await alertApi.deleteRule(id);
toast.success('告警规则已删除'); toast.success(t('monitor.alertrulestab.s20b3fd'));
onReload(); onReload();
} catch (error) { } catch (error) {
console.error('Failed to delete rule:', error); console.error('Failed to delete rule:', error);
toast.error('删除失败'); toast.error(t('common.deleteFailed'));
} }
}; };
@@ -73,20 +75,20 @@ export function AlertRulesTab({
const handleBatchDelete = async () => { const handleBatchDelete = async () => {
if (selectedIds.length === 0) return; if (selectedIds.length === 0) return;
const ok = await confirm({ const ok = await confirm({
title: '批量删除告警规则', title: t('monitor.alertrulestab.sbb457b'),
description: `确定删除选中的 ${selectedIds.length} 条告警规则吗?此操作不可撤销。`, description: t('monitor.alertrulestab.s12d681', { selectedIds.length: selectedIds.length }),
confirmText: '批量删除', confirmText: t('common.batchDelete'),
variant: 'destructive', variant: 'destructive',
}); });
if (!ok) return; if (!ok) return;
try { try {
await alertApi.batchDeleteRules(selectedIds); await alertApi.batchDeleteRules(selectedIds);
toast.success(`已删除 ${selectedIds.length} 条告警规则`); toast.success(t('monitor.alertrulestab.s327a78', { selectedIds.length: selectedIds.length }));
setSelectedIds([]); setSelectedIds([]);
onReload(); onReload();
} catch (error) { } catch (error) {
console.error('Failed to batch delete rules:', error); console.error('Failed to batch delete rules:', error);
toast.error('批量删除失败'); toast.error(t('cloud.batchDeleteFailed'));
} }
}; };
@@ -132,14 +134,14 @@ export function AlertRulesTab({
className="border-[var(--dg-border-hover)]" className="border-[var(--dg-border-hover)]"
/> />
</TableHead> </TableHead>
<TableHead className="dg-text-secondary">规则名称</TableHead> <TableHead className="dg-text-secondary">{t('monitor.ruleName')}</TableHead>
<TableHead className="dg-text-secondary">数据源</TableHead> <TableHead className="dg-text-secondary">{t('menu.datasources')}</TableHead>
<TableHead className="dg-text-secondary">触发条件</TableHead> <TableHead className="dg-text-secondary">{t('monitor.alertrulestab.s65939c')}</TableHead>
<TableHead className="dg-text-secondary">级别</TableHead> <TableHead className="dg-text-secondary">{t('common.level')}</TableHead>
<TableHead className="dg-text-secondary">持续时间</TableHead> <TableHead className="dg-text-secondary">{t('monitor.alertDuration')}</TableHead>
<TableHead className="dg-text-secondary">通知渠道</TableHead> <TableHead className="dg-text-secondary">{t('monitor.notificationChannel')}</TableHead>
<TableHead className="dg-text-secondary">状态</TableHead> <TableHead className="dg-text-secondary">{t('common.status')}</TableHead>
<TableHead className="dg-text-secondary text-right">操作</TableHead> <TableHead className="dg-text-secondary text-right">{t('common.actions')}</TableHead>
</TableRow> </TableRow>
</TableHeader> </TableHeader>
<TableBody> <TableBody>
@@ -12,13 +12,15 @@ import {
import { toast } from 'sonner'; import { toast } from 'sonner';
import { alertApi } from '@/api'; import { alertApi } from '@/api';
import type { NotificationChannel } from './alert-center-helpers'; import type { NotificationChannel } from './alert-center-helpers';
import { useTranslation } from 'react-i18next';
import i18n from '@/i18n';
const CHANNEL_TYPES = [ const CHANNEL_TYPES = [
{ value: 'dingtalk', label: '钉钉', hint: '钉钉机器人: webhook URL + secret' }, { value: 'dingtalk', label: i18n.t('monitor.contactDingtalk'), hint: i18n.t('monitor.alertchanneldialog.sdedd24') },
{ value: 'wechat', label: '企业微信', hint: '企业微信: webhook URL' }, { value: 'wechat', label: i18n.t('monitor.contactWechat'), hint: i18n.t('monitor.alertchanneldialog.s9c267e') },
{ value: 'feishu', label: '飞书', hint: '飞书机器人: {"url":"https://open.feishu.cn/open-apis/bot/v2/hook/..."}' }, { value: 'feishu', label: i18n.t('monitor.alertchanneldialog.s7714e5'), hint: i18n.t('monitor.alertchanneldialog.s98d805') },
{ value: 'email', label: '邮件', hint: '邮件: {"to":"ops@ezops.io"}' }, { value: 'email', label: i18n.t('common.email'), hint: i18n.t('monitor.alertchanneldialog.s0cb420') },
{ value: 'sms', label: '短信', hint: '短信: {"phones":"13800138000"}' }, { value: 'sms', label: i18n.t('common.sms'), hint: i18n.t('monitor.alertchanneldialog.s1ad98b') },
{ value: 'webhook', label: 'Webhook', hint: 'Webhook: {"url":"https://..."}' }, { value: 'webhook', label: 'Webhook', hint: 'Webhook: {"url":"https://..."}' },
]; ];
@@ -33,6 +35,7 @@ export function AlertChannelDialog({
editingChannel: NotificationChannel | null; editingChannel: NotificationChannel | null;
onSaved: () => void; onSaved: () => void;
}) { }) {
const { t } = useTranslation();
const [form, setForm] = useState({ name: '', type: 'dingtalk', config: '' }); const [form, setForm] = useState({ name: '', type: 'dingtalk', config: '' });
const [saving, setSaving] = useState(false); const [saving, setSaving] = useState(false);
@@ -54,15 +57,15 @@ export function AlertChannelDialog({
const payload = { name: form.name.trim(), type: form.type, config: form.config.trim() }; const payload = { name: form.name.trim(), type: form.type, config: form.config.trim() };
if (editingChannel) { if (editingChannel) {
await alertApi.updateNotifyChannel(editingChannel.id, payload); await alertApi.updateNotifyChannel(editingChannel.id, payload);
toast.success('渠道已更新'); toast.success(t('monitor.alertchanneldialog.s0cca4d'));
} else { } else {
await alertApi.createNotifyChannel(payload); await alertApi.createNotifyChannel(payload);
toast.success('渠道已添加'); toast.success(t('monitor.alertchanneldialog.s70dea9'));
} }
onOpenChange(false); onOpenChange(false);
onSaved(); onSaved();
} catch { } catch {
toast.error('保存失败'); toast.error(t('common.saveFailed'));
} finally { } finally {
setSaving(false); setSaving(false);
} }
@@ -74,20 +77,20 @@ export function AlertChannelDialog({
<Dialog open={open} onOpenChange={onOpenChange}> <Dialog open={open} onOpenChange={onOpenChange}>
<DialogContent> <DialogContent>
<DialogHeader> <DialogHeader>
<DialogTitle>{editingChannel ? '编辑通知渠道' : '添加通知渠道'}</DialogTitle> <DialogTitle>{editingChannel ? t('monitor.alertchanneldialog.sa605a7') : t('monitor.alertchanneldialog.sc7f8b8')}</DialogTitle>
<DialogDescription>配置告警通知渠道(钉钉/企业微信/邮件/短信/Webhook)</DialogDescription> <DialogDescription>{t('monitor.alertchanneldialog.sd0af2a')}</DialogDescription>
</DialogHeader> </DialogHeader>
<div className="space-y-4"> <div className="space-y-4">
<div className="space-y-2"> <div className="space-y-2">
<Label>渠道名称 *</Label> <Label>{t('monitor.alertchanneldialog.s8b7c73')}</Label>
<Input <Input
value={form.name} value={form.name}
onChange={(e) => setForm({ ...form, name: e.target.value })} onChange={(e) => setForm({ ...form, name: e.target.value })}
placeholder="如:运维告警群" placeholder=t('monitor.alertchanneldialog.s6906c9')
/> />
</div> </div>
<div className="space-y-2"> <div className="space-y-2">
<Label>渠道类型</Label> <Label>{t('monitor.channelType')}</Label>
<Select value={form.type} onValueChange={(v) => setForm({ ...form, type: v })}> <Select value={form.type} onValueChange={(v) => setForm({ ...form, type: v })}>
<SelectTrigger> <SelectTrigger>
<SelectValue /> <SelectValue />
@@ -100,7 +103,7 @@ export function AlertChannelDialog({
</Select> </Select>
</div> </div>
<div className="space-y-2"> <div className="space-y-2">
<Label>配置(JSON)</Label> <Label>{t('monitor.alertchanneldialog.s9ca77d')}</Label>
<Input <Input
value={form.config} value={form.config}
onChange={(e) => setForm({ ...form, config: e.target.value })} onChange={(e) => setForm({ ...form, config: e.target.value })}
@@ -111,9 +114,9 @@ export function AlertChannelDialog({
</div> </div>
</div> </div>
<DialogFooter> <DialogFooter>
<Button variant="outline" onClick={() => onOpenChange(false)}>取消</Button> <Button variant="outline" onClick={() => onOpenChange(false)}>{t('common.cancel')}</Button>
<Button onClick={handleSave} disabled={!form.name.trim() || saving}> <Button onClick={handleSave} disabled={!form.name.trim() || saving}>
{saving ? '保存中...' : editingChannel ? '保存修改' : '添加渠道'} {saving ? t('k8s.topology.saving') : editingChannel ? i18n.t('cloud.saveChanges') : i18n.t('monitor.alertchanneldialog.s22d04e')}
</Button> </Button>
</DialogFooter> </DialogFooter>
</DialogContent> </DialogContent>
@@ -12,8 +12,10 @@ import {
} from './alert-center-helpers'; } from './alert-center-helpers';
import { AlertChannelDialog } from './AlertChannelDialog'; import { AlertChannelDialog } from './AlertChannelDialog';
import type { JsonData } from '@/types/common'; import type { JsonData } from '@/types/common';
import { useTranslation } from 'react-i18next';
export const AlertChannelsTab: React.FC<{ refreshKey: number }> = ({ refreshKey }) => { export const AlertChannelsTab: React.FC<{ refreshKey: number }> = ({ refreshKey }) => {
const { t } = useTranslation();
const _confirm = useConfirm(); const _confirm = useConfirm();
const [channels, setChannels] = useState<NotificationChannel[]>([]); const [channels, setChannels] = useState<NotificationChannel[]>([]);
const [loading, setLoading] = useState(false); const [loading, setLoading] = useState(false);
@@ -28,7 +30,7 @@ export const AlertChannelsTab: React.FC<{ refreshKey: number }> = ({ refreshKey
const list = (res as JsonData)?.list || []; const list = (res as JsonData)?.list || [];
setChannels(list); setChannels(list);
} catch { } catch {
toast.error('获取通知渠道失败'); toast.error(t('monitor.alertchannelstab.s84d8b4'));
} finally { } finally {
setLoading(false); setLoading(false);
} }
@@ -47,14 +49,14 @@ export const AlertChannelsTab: React.FC<{ refreshKey: number }> = ({ refreshKey
}; };
const handleDelete = async (id: number) => { const handleDelete = async (id: number) => {
const ok = await _confirm({ title: '删除通知渠道', description: '确定删除此通知渠道?', confirmText: '删除', variant: 'destructive' }); const ok = await _confirm({ title: t('monitor.alertchannelstab.sa4450b'), description: t('monitor.alertchannelstab.sb1a9e5'), confirmText: t('common.delete'), variant: 'destructive' });
if (!ok) return; if (!ok) return;
try { try {
await alertApi.deleteNotifyChannel(id); await alertApi.deleteNotifyChannel(id);
toast.success('渠道已删除'); toast.success(t('monitor.alertchannelstab.s6fad11'));
fetchChannels(); fetchChannels();
} catch { } catch {
toast.error('删除失败'); toast.error(t('common.deleteFailed'));
} }
}; };
@@ -63,13 +65,13 @@ export const AlertChannelsTab: React.FC<{ refreshKey: number }> = ({ refreshKey
const res = await alertApi.testNotifyChannel(id); const res = await alertApi.testNotifyChannel(id);
const status = (res as JsonData)?.status; const status = (res as JsonData)?.status;
if (status === 'success') { if (status === 'success') {
toast.success('测试通知已发送'); toast.success(t('monitor.alertchannelstab.s1e710e'));
} else { } else {
toast.warning('渠道未配置参数,请先完善配置'); toast.warning(t('monitor.alertchannelstab.s9b3fda'));
} }
fetchChannels(); fetchChannels();
} catch { } catch {
toast.error('测试失败'); toast.error(t('monitor.alertchannelstab.s9710d9'));
} }
}; };
@@ -78,7 +80,7 @@ export const AlertChannelsTab: React.FC<{ refreshKey: number }> = ({ refreshKey
await alertApi.updateNotifyChannel(ch.id, { enabled: !ch.enabled }); await alertApi.updateNotifyChannel(ch.id, { enabled: !ch.enabled });
fetchChannels(); fetchChannels();
} catch { } catch {
toast.error('操作失败'); toast.error(t('common.operationFailed'));
} }
}; };
@@ -96,7 +98,7 @@ export const AlertChannelsTab: React.FC<{ refreshKey: number }> = ({ refreshKey
</div> </div>
{loading ? ( {loading ? (
<div className="text-center py-16 text-muted-foreground">加载中...</div> <div className="text-center py-16 text-muted-foreground">{t('common.loading')}</div>
) : channels.length === 0 ? ( ) : channels.length === 0 ? (
<div className="text-center py-16 text-muted-foreground border border-dashed rounded-lg"> <div className="text-center py-16 text-muted-foreground border border-dashed rounded-lg">
暂无通知渠道,点击「添加渠道」创建 暂无通知渠道,点击「添加渠道」创建
@@ -112,7 +114,7 @@ export const AlertChannelsTab: React.FC<{ refreshKey: number }> = ({ refreshKey
<CardTitle className="text-base">{channel.name}</CardTitle> <CardTitle className="text-base">{channel.name}</CardTitle>
</div> </div>
<Badge variant={channel.enabled ? 'default' : 'secondary'} className={channel.enabled ? 'bg-green-600' : ''}> <Badge variant={channel.enabled ? 'default' : 'secondary'} className={channel.enabled ? 'bg-green-600' : ''}>
{channel.enabled ? '已启用' : '已禁用'} {channel.enabled ? t('alert.enabled') : t('alert.disabled')}
</Badge> </Badge>
</div> </div>
</CardHeader> </CardHeader>
@@ -120,7 +122,7 @@ export const AlertChannelsTab: React.FC<{ refreshKey: number }> = ({ refreshKey
<div className="text-sm text-muted-foreground mb-3"> <div className="text-sm text-muted-foreground mb-3">
类型: {getChannelTypeLabel(channel.type)} 类型: {getChannelTypeLabel(channel.type)}
{channel.test_status === 'success' && ( {channel.test_status === 'success' && (
<span className="ml-2 dg-text-green">测试通过</span> <span className="ml-2 dg-text-green">{t('monitor.alertchannelstab.sd25431')}</span>
)} )}
</div> </div>
<div className="flex gap-2"> <div className="flex gap-2">
@@ -130,7 +132,7 @@ export const AlertChannelsTab: React.FC<{ refreshKey: number }> = ({ refreshKey
</Button> </Button>
<Button variant="outline" size="sm" className="flex-1" onClick={() => handleToggle(channel)}> <Button variant="outline" size="sm" className="flex-1" onClick={() => handleToggle(channel)}>
<Settings className="w-4 h-4 mr-1.5" /> <Settings className="w-4 h-4 mr-1.5" />
{channel.enabled ? '禁用' : '启用'} {channel.enabled ? t('common.disable') : t('common.enable')}
</Button> </Button>
<Button variant="outline" size="sm" onClick={() => handleDelete(channel.id)}> <Button variant="outline" size="sm" onClick={() => handleDelete(channel.id)}>
<X className="w-4 h-4" /> <X className="w-4 h-4" />
@@ -12,6 +12,8 @@ import { AgentRuleDialog } from '@/components/agent/AgentRuleDialog';
import { MonitorRuleDialog } from './MonitorRuleDialog'; import { MonitorRuleDialog } from './MonitorRuleDialog';
import type { MetricCatalogCategory, UnifiedAlertRule } from '@/api'; import type { MetricCatalogCategory, UnifiedAlertRule } from '@/api';
import type { JsonData } from '@/types/common'; import type { JsonData } from '@/types/common';
import { useTranslation } from 'react-i18next';
import i18n from '@/i18n';
type RuleCategory = 'host' | 'middleware' | 'snmp' | 'site'; type RuleCategory = 'host' | 'middleware' | 'snmp' | 'site';
type MonitorCategory = 'middleware' | 'snmp' | 'site'; type MonitorCategory = 'middleware' | 'snmp' | 'site';
@@ -22,10 +24,10 @@ const RULE_CATEGORIES: Array<{
icon: typeof Server; icon: typeof Server;
desc: string; desc: string;
}> = [ }> = [
{ id: 'host', label: '主机监控', icon: Server, desc: 'Agent CPU/内存/磁盘/离线' }, { id: 'host', label: i18n.t('monitor.hostMonitor'), icon: Server, desc: i18n.t('monitor.alertrulestab.s836f7b') },
{ id: 'middleware', label: '中间件', icon: Database, desc: 'Redis / MySQL 指标' }, { id: 'middleware', label: i18n.t('dashboard.ops.middleware'), icon: Database, desc: i18n.t('monitor.alertrulestab.sf3e5db') },
{ id: 'snmp', label: 'SNMP', icon: Network, desc: '网络设备 / BMC' }, { id: 'snmp', label: 'SNMP', icon: Network, desc: i18n.t('monitor.alertrulestab.s086e4c') },
{ id: 'site', label: '站点拨测', icon: Globe, desc: 'HTTP/HTTPS 可用性与证书' }, { id: 'site', label: i18n.t('monitor.siteProbe'), icon: Globe, desc: i18n.t('monitor.alertrulestab.sf9f400') },
]; ];
interface Props { interface Props {
@@ -47,6 +49,7 @@ export function AlertRulesTab({
onToggleAgent, onDeleteAgent, onDeleteMonitor, onToggleMonitor, onToggleAgent, onDeleteAgent, onDeleteMonitor, onToggleMonitor,
onQuickSetupHost, onQuickSetupMonitor, quickSetupPending, onQuickSetupHost, onQuickSetupMonitor, quickSetupPending,
}: Props) { }: Props) {
const { t } = useTranslation();
const [activeCat, setActiveCat] = useState<RuleCategory>('host'); const [activeCat, setActiveCat] = useState<RuleCategory>('host');
const [agentDialogOpen, setAgentDialogOpen] = useState(false); const [agentDialogOpen, setAgentDialogOpen] = useState(false);
const [monitorDialogOpen, setMonitorDialogOpen] = useState(false); const [monitorDialogOpen, setMonitorDialogOpen] = useState(false);
@@ -79,7 +82,7 @@ export function AlertRulesTab({
} }
}; };
if (loading) return <PageLoading label="加载规则..." />; if (loading) return <PageLoading label=t('monitor.alertrulestab.s1e637e') />;
return ( return (
<div className="space-y-4"> <div className="space-y-4">
@@ -116,7 +119,7 @@ export function AlertRulesTab({
</div> </div>
{filtered.length === 0 ? ( {filtered.length === 0 ? (
<PageEmpty title={`暂无${catMeta.label}规则`} description="点击「添加规则」或「默认规则」创建" /> <PageEmpty title={t('monitor.alertrulestab.sb2f604', { catMeta.label: catMeta.label })} description=t('monitor.alertrulestab.s1f2385') />
) : ( ) : (
<div className="grid grid-cols-1 gap-3"> <div className="grid grid-cols-1 gap-3">
{filtered.map((rule) => ( {filtered.map((rule) => (
@@ -128,7 +131,7 @@ export function AlertRulesTab({
<span className="font-medium text-sm">{rule.name}</span> <span className="font-medium text-sm">{rule.name}</span>
{getSeverityBadge(rule.severity)} {getSeverityBadge(rule.severity)}
<Badge variant={rule.enabled ? 'default' : 'secondary'} className="text-[10px]"> <Badge variant={rule.enabled ? 'default' : 'secondary'} className="text-[10px]">
{rule.enabled ? '启用' : '停用'} {rule.enabled ? t('common.enable') : t('common.deactivate')}
</Badge> </Badge>
</div> </div>
<p className="text-xs text-muted-foreground font-mono"> <p className="text-xs text-muted-foreground font-mono">
@@ -150,9 +153,9 @@ export function AlertRulesTab({
setMonitorCategory(rule.category as MonitorCategory); setMonitorCategory(rule.category as MonitorCategory);
setMonitorDialogOpen(true); setMonitorDialogOpen(true);
} }
}}>编辑</Button> }}>{t('common.edit')}</Button>
<Button variant="ghost" size="sm" className="h-7 text-xs dg-text-red" <Button variant="ghost" size="sm" className="h-7 text-xs dg-text-red"
onClick={() => rule.rule_type === 'agent' ? onDeleteAgent(rule) : onDeleteMonitor(rule)}>删除</Button> onClick={() => rule.rule_type === 'agent' ? onDeleteAgent(rule) : onDeleteMonitor(rule)}>{t('common.delete')}</Button>
<Switch checked={rule.enabled} <Switch checked={rule.enabled}
onCheckedChange={(v) => rule.rule_type === 'agent' onCheckedChange={(v) => rule.rule_type === 'agent'
? onToggleAgent(rule.id, v) ? onToggleAgent(rule.id, v)
@@ -12,12 +12,14 @@ import {
import { toast } from 'sonner'; import { toast } from 'sonner';
import { alertApi } from '@/api'; import { alertApi } from '@/api';
import type { Contact } from './alert-center-helpers'; import type { Contact } from './alert-center-helpers';
import { useTranslation } from 'react-i18next';
import i18n from '@/i18n';
const CHANNEL_OPTIONS = [ const CHANNEL_OPTIONS = [
{ value: 'feishu', label: '飞书', placeholder: 'https://open.feishu.cn/open-apis/bot/v2/hook/...' }, { value: 'feishu', label: i18n.t('monitor.contactdialog.s7714e5'), placeholder: 'https://open.feishu.cn/open-apis/bot/v2/hook/...' },
{ value: 'dingtalk', label: '钉钉', placeholder: 'https://oapi.dingtalk.com/robot/send?access_token=...' }, { value: 'dingtalk', label: i18n.t('monitor.contactDingtalk'), placeholder: 'https://oapi.dingtalk.com/robot/send?access_token=...' },
{ value: 'wechat', label: '企业微信', placeholder: 'https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=...' }, { value: 'wechat', label: i18n.t('monitor.contactWechat'), placeholder: 'https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=...' },
{ value: 'webhook', label: '自定义Webhook', placeholder: 'https://your-webhook-url...' }, { value: 'webhook', label: i18n.t('monitor.contactdialog.s3ccb7a'), placeholder: 'https://your-webhook-url...' },
]; ];
export function ContactDialog({ export function ContactDialog({
@@ -31,6 +33,7 @@ export function ContactDialog({
editingContact: Contact | null; editingContact: Contact | null;
onSaved: () => void; onSaved: () => void;
}) { }) {
const { t } = useTranslation();
const [channelType, setChannelType] = useState('feishu'); const [channelType, setChannelType] = useState('feishu');
const [form, setForm] = useState({ name: '', phone: '', email: '', webhook_url: '' }); const [form, setForm] = useState({ name: '', phone: '', email: '', webhook_url: '' });
const [saving, setSaving] = useState(false); const [saving, setSaving] = useState(false);
@@ -65,15 +68,15 @@ export function ContactDialog({
}; };
if (editingContact) { if (editingContact) {
await alertApi.updateContact(editingContact.id, payload); await alertApi.updateContact(editingContact.id, payload);
toast.success('联系人已更新'); toast.success(t('monitor.contactdialog.sa0fe38'));
} else { } else {
await alertApi.createContact(payload); await alertApi.createContact(payload);
toast.success('联系人已添加'); toast.success(t('monitor.contactdialog.s50ee3f'));
} }
onOpenChange(false); onOpenChange(false);
onSaved(); onSaved();
} catch { } catch {
toast.error('保存失败'); toast.error(t('common.saveFailed'));
} finally { } finally {
setSaving(false); setSaving(false);
} }
@@ -85,21 +88,21 @@ export function ContactDialog({
<Dialog open={open} onOpenChange={onOpenChange}> <Dialog open={open} onOpenChange={onOpenChange}>
<DialogContent> <DialogContent>
<DialogHeader> <DialogHeader>
<DialogTitle>{editingContact ? '编辑报警联系人' : '添加报警联系人'}</DialogTitle> <DialogTitle>{editingContact ? t('monitor.contactdialog.sbc3c27') : t('monitor.contactdialog.sc044d1')}</DialogTitle>
<DialogDescription>选择通知渠道并填入 Webhook 地址</DialogDescription> <DialogDescription>{t('monitor.contactdialog.s04b40a')}</DialogDescription>
</DialogHeader> </DialogHeader>
<div className="space-y-4"> <div className="space-y-4">
<div className="space-y-2"> <div className="space-y-2">
<Label>姓名 *</Label> <Label>{t('monitor.contactdialog.s7c46af')}</Label>
<Input <Input
value={form.name} value={form.name}
onChange={(e) => setForm({ ...form, name: e.target.value })} onChange={(e) => setForm({ ...form, name: e.target.value })}
placeholder="如:张三" placeholder=t('monitor.contactdialog.s6b9850')
/> />
</div> </div>
<div className="grid grid-cols-2 gap-3"> <div className="grid grid-cols-2 gap-3">
<div className="space-y-2"> <div className="space-y-2">
<Label>手机号</Label> <Label>{t('system.userPhone')}</Label>
<Input <Input
value={form.phone} value={form.phone}
onChange={(e) => setForm({ ...form, phone: e.target.value })} onChange={(e) => setForm({ ...form, phone: e.target.value })}
@@ -107,7 +110,7 @@ export function ContactDialog({
/> />
</div> </div>
<div className="space-y-2"> <div className="space-y-2">
<Label>邮箱</Label> <Label>{t('system.userEmail')}</Label>
<Input <Input
value={form.email} value={form.email}
onChange={(e) => setForm({ ...form, email: e.target.value })} onChange={(e) => setForm({ ...form, email: e.target.value })}
@@ -116,10 +119,10 @@ export function ContactDialog({
</div> </div>
</div> </div>
<div className="space-y-2"> <div className="space-y-2">
<Label>渠道类型 *</Label> <Label>{t('monitor.contactdialog.sc84995')}</Label>
<Select value={channelType} onValueChange={setChannelType}> <Select value={channelType} onValueChange={setChannelType}>
<SelectTrigger> <SelectTrigger>
<SelectValue placeholder="选择渠道类型" /> <SelectValue placeholder=t('monitor.contactdialog.seb8768') />
</SelectTrigger> </SelectTrigger>
<SelectContent> <SelectContent>
{CHANNEL_OPTIONS.map(opt => ( {CHANNEL_OPTIONS.map(opt => (
@@ -139,9 +142,9 @@ export function ContactDialog({
</div> </div>
</div> </div>
<DialogFooter> <DialogFooter>
<Button variant="outline" onClick={() => onOpenChange(false)}>取消</Button> <Button variant="outline" onClick={() => onOpenChange(false)}>{t('common.cancel')}</Button>
<Button onClick={handleSave} disabled={!form.name.trim() || !form.webhook_url.trim() || saving}> <Button onClick={handleSave} disabled={!form.name.trim() || !form.webhook_url.trim() || saving}>
{saving ? '保存中...' : editingContact ? '保存修改' : '添加联系人'} {saving ? i18n.t('k8s.topology.saving') : editingContact ? i18n.t('cloud.saveChanges') : i18n.t('alert.addContact')}
</Button> </Button>
</DialogFooter> </DialogFooter>
</DialogContent> </DialogContent>
@@ -11,6 +11,7 @@ import { Badge } from '@/components/ui/badge';
import { toast } from 'sonner'; import { toast } from 'sonner';
import { alertApi } from '@/api'; import { alertApi } from '@/api';
import type { Contact, ContactGroup } from './alert-center-helpers'; import type { Contact, ContactGroup } from './alert-center-helpers';
import { useTranslation } from 'react-i18next';
export function ContactGroupDialog({ export function ContactGroupDialog({
open, open,
@@ -25,6 +26,7 @@ export function ContactGroupDialog({
contacts: Contact[]; contacts: Contact[];
onSaved: () => void; onSaved: () => void;
}) { }) {
const { t } = useTranslation();
const [form, setForm] = useState({ group_name: '', notes: '', contact_ids: [] as number[] }); const [form, setForm] = useState({ group_name: '', notes: '', contact_ids: [] as number[] });
const [saving, setSaving] = useState(false); const [saving, setSaving] = useState(false);
@@ -66,15 +68,15 @@ export function ContactGroupDialog({
}; };
if (editingGroup) { if (editingGroup) {
await alertApi.updateContactGroup(editingGroup.id, payload); await alertApi.updateContactGroup(editingGroup.id, payload);
toast.success('联系组已更新'); toast.success(t('monitor.contactgroupdialog.s493f94'));
} else { } else {
await alertApi.createContactGroup(payload); await alertApi.createContactGroup(payload);
toast.success('联系组已添加'); toast.success(t('monitor.contactgroupdialog.sda7160'));
} }
onOpenChange(false); onOpenChange(false);
onSaved(); onSaved();
} catch { } catch {
toast.error('保存失败'); toast.error(t('common.saveFailed'));
} finally { } finally {
setSaving(false); setSaving(false);
} }
@@ -84,31 +86,31 @@ export function ContactGroupDialog({
<Dialog open={open} onOpenChange={onOpenChange}> <Dialog open={open} onOpenChange={onOpenChange}>
<DialogContent> <DialogContent>
<DialogHeader> <DialogHeader>
<DialogTitle>{editingGroup ? '编辑报警联系组' : '添加报警联系组'}</DialogTitle> <DialogTitle>{editingGroup ? t('monitor.contactgroupdialog.s5fb6c5') : t('monitor.contactgroupdialog.s462488')}</DialogTitle>
<DialogDescription>配置报警联系组,选择组内成员</DialogDescription> <DialogDescription>{t('monitor.contactgroupdialog.s112855')}</DialogDescription>
</DialogHeader> </DialogHeader>
<div className="space-y-4"> <div className="space-y-4">
<div className="space-y-2"> <div className="space-y-2">
<Label>组名称 *</Label> <Label>{t('monitor.contactgroupdialog.s0e18f7')}</Label>
<Input <Input
value={form.group_name} value={form.group_name}
onChange={(e) => setForm({ ...form, group_name: e.target.value })} onChange={(e) => setForm({ ...form, group_name: e.target.value })}
placeholder="如:运维值班组" placeholder=t('monitor.contactgroupdialog.s937123')
/> />
</div> </div>
<div className="space-y-2"> <div className="space-y-2">
<Label>备注</Label> <Label>{t('common.remark')}</Label>
<Textarea <Textarea
value={form.notes} value={form.notes}
onChange={(e) => setForm({ ...form, notes: e.target.value })} onChange={(e) => setForm({ ...form, notes: e.target.value })}
placeholder="如:周一至周五 9:00-21:00" placeholder=t('monitor.contactgroupdialog.s19f365')
rows={2} rows={2}
/> />
</div> </div>
<div className="space-y-2"> <div className="space-y-2">
<Label>选择联系人</Label> <Label>{t('monitor.contactgroupdialog.s3dada7')}</Label>
{contacts.length === 0 ? ( {contacts.length === 0 ? (
<p className="text-xs text-muted-foreground">暂无联系人,请先在「报警联系人」标签页添加</p> <p className="text-xs text-muted-foreground">{t('monitor.contactgroupdialog.s2bade1')}</p>
) : ( ) : (
<div className="flex flex-wrap gap-1.5 max-h-[180px] overflow-y-auto border rounded-md p-2"> <div className="flex flex-wrap gap-1.5 max-h-[180px] overflow-y-auto border rounded-md p-2">
{contacts.map(c => ( {contacts.map(c => (
@@ -130,9 +132,9 @@ export function ContactGroupDialog({
</div> </div>
</div> </div>
<DialogFooter> <DialogFooter>
<Button variant="outline" onClick={() => onOpenChange(false)}>取消</Button> <Button variant="outline" onClick={() => onOpenChange(false)}>{t('common.cancel')}</Button>
<Button onClick={handleSave} disabled={!form.group_name.trim() || saving}> <Button onClick={handleSave} disabled={!form.group_name.trim() || saving}>
{saving ? '保存中...' : editingGroup ? '保存修改' : '添加联系组'} {saving ? i18n.t('k8s.topology.saving') : editingGroup ? i18n.t('cloud.saveChanges') : i18n.t('alert.addGroup')}
</Button> </Button>
</DialogFooter> </DialogFooter>
</DialogContent> </DialogContent>
@@ -5,6 +5,7 @@ import { Badge } from '@/components/ui/badge';
import { Button } from '@/components/ui/button'; import { Button } from '@/components/ui/button';
import { Loader2, RefreshCw, Server, Database, Globe, Network } from 'lucide-react'; import { Loader2, RefreshCw, Server, Database, Globe, Network } from 'lucide-react';
import { alertMetricsApi, type MetricCatalogCategory } from '@/api'; import { alertMetricsApi, type MetricCatalogCategory } from '@/api';
import { useTranslation } from 'react-i18next';
const CATEGORY_ORDER = ['host', 'middleware', 'snmp', 'site']; const CATEGORY_ORDER = ['host', 'middleware', 'snmp', 'site'];
@@ -16,6 +17,7 @@ const categoryIcons: Record<string, typeof Server> = {
}; };
export function MetricCatalogTab() { export function MetricCatalogTab() {
const { t } = useTranslation();
const [categories, setCategories] = useState<MetricCatalogCategory[]>([]); const [categories, setCategories] = useState<MetricCatalogCategory[]>([]);
const [loading, setLoading] = useState(true); const [loading, setLoading] = useState(true);
const [activeCat, setActiveCat] = useState<string>('host'); const [activeCat, setActiveCat] = useState<string>('host');
@@ -88,13 +90,13 @@ export function MetricCatalogTab() {
<table className="w-full text-xs"> <table className="w-full text-xs">
<thead className="bg-muted/50"> <thead className="bg-muted/50">
<tr> <tr>
<th className="px-2 py-2 text-left font-medium">指标</th> <th className="px-2 py-2 text-left font-medium">{t('cloud.colMetric')}</th>
<th className="px-2 py-2 text-left font-medium">单位</th> <th className="px-2 py-2 text-left font-medium">{t('common.unit')}</th>
<th className="px-2 py-2 text-left font-medium">类型</th> <th className="px-2 py-2 text-left font-medium">{t('common.type')}</th>
<th className="px-2 py-2 text-left font-medium">警告阈值</th> <th className="px-2 py-2 text-left font-medium">{t('monitor.metriccatalogtab.s037989')}</th>
<th className="px-2 py-2 text-left font-medium">严重阈值</th> <th className="px-2 py-2 text-left font-medium">{t('monitor.metriccatalogtab.s3780c1')}</th>
<th className="px-2 py-2 text-left font-medium">上限</th> <th className="px-2 py-2 text-left font-medium">{t('monitor.metriccatalogtab.s726bfb')}</th>
<th className="px-2 py-2 text-left font-medium">说明</th> <th className="px-2 py-2 text-left font-medium">{t('cloud.colDescription')}</th>
</tr> </tr>
</thead> </thead>
<tbody className="divide-y"> <tbody className="divide-y">
@@ -14,6 +14,8 @@ import {
import { Loader2 } from 'lucide-react'; import { Loader2 } from 'lucide-react';
import { alertMetricsApi, type MetricCatalogItem } from '@/api'; import { alertMetricsApi, type MetricCatalogItem } from '@/api';
import { SEVERITY_OPTIONS } from '@/components/agent/agentAlertHelper'; import { SEVERITY_OPTIONS } from '@/components/agent/agentAlertHelper';
import { useTranslation } from 'react-i18next';
import i18n from '@/i18n';
interface Props { interface Props {
open: boolean; open: boolean;
@@ -25,14 +27,15 @@ interface Props {
} }
const OPERATORS = [ const OPERATORS = [
{ value: '>', label: '> 大于' }, { value: '>', label: i18n.t('monitor.monitorruledialog.s552612') },
{ value: '<', label: '< 小于' }, { value: '<', label: i18n.t('monitor.monitorruledialog.sdd29ed') },
{ value: '>=', label: '≥ 大于等于' }, { value: '>=', label: i18n.t('monitor.monitorruledialog.sef2679') },
{ value: '<=', label: '≤ 小于等于' }, { value: '<=', label: i18n.t('monitor.monitorruledialog.s847d07') },
{ value: '==', label: '= 等于' }, { value: '==', label: i18n.t('monitor.monitorruledialog.s9cd6c2') },
]; ];
export function MonitorRuleDialog({ open, onOpenChange, category, metrics, editing, onSaved }: Props) { export function MonitorRuleDialog({ open, onOpenChange, category, metrics, editing, onSaved }: Props) {
const { t } = useTranslation();
const [form, setForm] = useState({ const [form, setForm] = useState({
name: '', metric: '', operator: '>', threshold: '0', severity: 'warning', enabled: true, name: '', metric: '', operator: '>', threshold: '0', severity: 'warning', enabled: true,
}); });
@@ -72,7 +75,7 @@ export function MonitorRuleDialog({ open, onOpenChange, category, metrics, editi
const handleSave = async () => { const handleSave = async () => {
if (!form.name.trim() || !form.metric) { if (!form.name.trim() || !form.metric) {
toast.error('请填写规则名称和指标'); toast.error(t('monitor.monitorruledialog.sace3bf'));
return; return;
} }
setSaving(true); setSaving(true);
@@ -84,22 +87,22 @@ export function MonitorRuleDialog({ open, onOpenChange, category, metrics, editi
}; };
if (editing) { if (editing) {
await alertMetricsApi.updateMonitorRule(editing.id, payload); await alertMetricsApi.updateMonitorRule(editing.id, payload);
toast.success('规则已更新'); toast.success(t('monitor.monitorruledialog.sa716ef'));
} else { } else {
await alertMetricsApi.createMonitorRule(payload); await alertMetricsApi.createMonitorRule(payload);
toast.success('规则已创建'); toast.success(t('monitor.monitorruledialog.s5702a3'));
} }
onOpenChange(false); onOpenChange(false);
onSaved(); onSaved();
} catch (e) { } catch (e) {
toast.error((e as { message?: string }).message || '保存失败'); toast.error((e as { message?: string }).message || t('common.saveFailed'));
} finally { } finally {
setSaving(false); setSaving(false);
} }
}; };
const catLabels: Record<string, string> = { const catLabels: Record<string, string> = {
middleware: '中间件', snmp: 'SNMP', site: '站点拨测', middleware: t('dashboard.ops.middleware'), snmp: 'SNMP', site: t('monitor.siteProbe'),
}; };
const catLabel = catLabels[category] || category; const catLabel = catLabels[category] || category;
@@ -107,18 +110,18 @@ export function MonitorRuleDialog({ open, onOpenChange, category, metrics, editi
<Dialog open={open} onOpenChange={onOpenChange}> <Dialog open={open} onOpenChange={onOpenChange}>
<DialogContent className="sm:max-w-md bg-[var(--dg-bg-secondary)] border-[var(--dg-border)]"> <DialogContent className="sm:max-w-md bg-[var(--dg-bg-secondary)] border-[var(--dg-border)]">
<DialogHeader> <DialogHeader>
<DialogTitle>{editing ? '编辑' : '新建'}{catLabel}告警规则</DialogTitle> <DialogTitle>{editing ? t('common.edit') : t('monitor.dashboard.custom.create')}{catLabel}告警规则</DialogTitle>
<DialogDescription className="text-[var(--dg-text-muted)]"> <DialogDescription className="text-[var(--dg-text-muted)]">
基于监控中心采集指标配置阈值告警 基于监控中心采集指标配置阈值告警
</DialogDescription> </DialogDescription>
</DialogHeader> </DialogHeader>
<div className="grid gap-3 py-2"> <div className="grid gap-3 py-2">
<div className="grid gap-1.5"> <div className="grid gap-1.5">
<Label>规则名称</Label> <Label>{t('monitor.ruleName')}</Label>
<Input value={form.name} onChange={e => setForm({ ...form, name: e.target.value })} placeholder="例如:Redis 连接数过高" /> <Input value={form.name} onChange={e => setForm({ ...form, name: e.target.value })} placeholder=t('monitor.monitorruledialog.s23b9f8') />
</div> </div>
<div className="grid gap-1.5"> <div className="grid gap-1.5">
<Label>监控指标</Label> <Label>{t('monitor.monitorruledialog.s9a51fb')}</Label>
<Select value={form.metric} onValueChange={handleMetricChange}> <Select value={form.metric} onValueChange={handleMetricChange}>
<SelectTrigger><SelectValue /></SelectTrigger> <SelectTrigger><SelectValue /></SelectTrigger>
<SelectContent> <SelectContent>
@@ -133,7 +136,7 @@ export function MonitorRuleDialog({ open, onOpenChange, category, metrics, editi
</div> </div>
<div className="grid grid-cols-2 gap-3"> <div className="grid grid-cols-2 gap-3">
<div className="grid gap-1.5"> <div className="grid gap-1.5">
<Label>运算符</Label> <Label>{t('monitor.ruleOperator')}</Label>
<Select value={form.operator} onValueChange={v => setForm({ ...form, operator: v })}> <Select value={form.operator} onValueChange={v => setForm({ ...form, operator: v })}>
<SelectTrigger><SelectValue /></SelectTrigger> <SelectTrigger><SelectValue /></SelectTrigger>
<SelectContent> <SelectContent>
@@ -149,7 +152,7 @@ export function MonitorRuleDialog({ open, onOpenChange, category, metrics, editi
</div> </div>
</div> </div>
<div className="grid gap-1.5"> <div className="grid gap-1.5">
<Label>严重程度</Label> <Label>{t('monitor.ruleSeverity')}</Label>
<Select value={form.severity} onValueChange={v => setForm({ ...form, severity: v })}> <Select value={form.severity} onValueChange={v => setForm({ ...form, severity: v })}>
<SelectTrigger><SelectValue /></SelectTrigger> <SelectTrigger><SelectValue /></SelectTrigger>
<SelectContent> <SelectContent>
@@ -159,11 +162,11 @@ export function MonitorRuleDialog({ open, onOpenChange, category, metrics, editi
</div> </div>
<div className="flex items-center gap-2"> <div className="flex items-center gap-2">
<Switch checked={form.enabled} onCheckedChange={v => setForm({ ...form, enabled: v })} /> <Switch checked={form.enabled} onCheckedChange={v => setForm({ ...form, enabled: v })} />
<Label>启用规则</Label> <Label>{t('monitor.monitorruledialog.sfd2ea0')}</Label>
</div> </div>
</div> </div>
<DialogFooter> <DialogFooter>
<Button variant="outline" onClick={() => onOpenChange(false)} disabled={saving}>取消</Button> <Button variant="outline" onClick={() => onOpenChange(false)} disabled={saving}>{t('common.cancel')}</Button>
<Button onClick={handleSave} disabled={saving}> <Button onClick={handleSave} disabled={saving}>
{saving && <Loader2 className="h-4 w-4 animate-spin mr-1" />} 保存 {saving && <Loader2 className="h-4 w-4 animate-spin mr-1" />} 保存
</Button> </Button>
@@ -28,19 +28,21 @@ export interface NotifyPolicy {
} }
import type { NotifyMessageSettings } from '@/api/monitor/alert'; import type { NotifyMessageSettings } from '@/api/monitor/alert';
import { useTranslation } from 'react-i18next';
import i18n from '@/i18n';
type PolicyDraft = { enabled: boolean; groupIds: number[]; contactIds: number[] }; type PolicyDraft = { enabled: boolean; groupIds: number[]; contactIds: number[] };
const CATEGORIES = [ const CATEGORIES = [
{ id: 'host' as const, label: '主机监控', desc: 'Agent 采集 CPU/内存/磁盘/离线等', icon: Server }, { id: 'host' as const, label: i18n.t('monitor.hostMonitor'), desc: i18n.t('monitor.notifypolicytab.s055f5a'), icon: Server },
{ id: 'middleware' as const, label: '中间件监控', desc: 'Redis/MySQL 等指标告警', icon: Database }, { id: 'middleware' as const, label: i18n.t('monitor.middleware'), desc: i18n.t('monitor.notifypolicytab.s420c7c'), icon: Database },
{ id: 'site' as const, label: '站点拨测', desc: 'HTTP/TCP/DNS 拨测失败与延迟', icon: Globe }, { id: 'site' as const, label: i18n.t('monitor.siteProbe'), desc: i18n.t('monitor.notifypolicytab.sbe6b21'), icon: Globe },
{ id: 'snmp' as const, label: 'SNMP 监控', desc: 'H3C/华为/Cisco/锐捷/Dell/浪潮', icon: Network }, { id: 'snmp' as const, label: i18n.t('monitor.snmp.title'), desc: i18n.t('monitor.notifypolicytab.sa48251'), icon: Network },
]; ];
const DEFAULT_TITLE = '[{{severity_label}}] {{rule_name}} — {{hostname}} ({{metric}})'; const DEFAULT_TITLE = '[{{severity_label}}] {{rule_name}} — {{hostname}} ({{metric}})';
const DEFAULT_FOOTER = '{{time}} | {{platform}}'; const DEFAULT_FOOTER = '{{time}} | {{platform}}';
const DEFAULT_PLATFORM = 'AIOps 智能运维平台'; const DEFAULT_PLATFORM = i18n.t('login.title');
const TEMPLATE_VARS = [ const TEMPLATE_VARS = [
'{{time}}', '{{platform}}', '{{rule_name}}', '{{hostname}}', '{{time}}', '{{platform}}', '{{rule_name}}', '{{hostname}}',
@@ -62,6 +64,7 @@ function draftKey(d: PolicyDraft) {
} }
export function NotifyPolicyTab() { export function NotifyPolicyTab() {
const { t } = useTranslation();
const [loading, setLoading] = useState(true); const [loading, setLoading] = useState(true);
const [saving, setSaving] = useState(false); const [saving, setSaving] = useState(false);
const [testing, setTesting] = useState<string | null>(null); const [testing, setTesting] = useState<string | null>(null);
@@ -125,7 +128,7 @@ export function NotifyPolicyTab() {
setMsgSettings(merged); setMsgSettings(merged);
setSavedMsgSettings(merged); setSavedMsgSettings(merged);
} catch { } catch {
toast.error('加载通知策略失败'); toast.error(t('monitor.notifypolicytab.s221fbe'));
} finally { } finally {
setLoading(false); setLoading(false);
} }
@@ -183,10 +186,10 @@ export function NotifyPolicyTab() {
}), }),
alertApi.saveNotifyMessageSettings(msgSettings), alertApi.saveNotifyMessageSettings(msgSettings),
]); ]);
toast.success('通知配置已保存'); toast.success(t('monitor.notifypolicytab.sb1226a'));
load(); load();
} catch (e) { } catch (e) {
toast.error((e as { message?: string }).message || '保存失败'); toast.error((e as { message?: string }).message || t('common.saveFailed'));
} finally { } finally {
setSaving(false); setSaving(false);
} }
@@ -196,15 +199,15 @@ export function NotifyPolicyTab() {
setTesting(category); setTesting(category);
try { try {
await alertApi.testNotifyPolicy(category); await alertApi.testNotifyPolicy(category);
toast.success('测试通知已发送'); toast.success(t('monitor.notifypolicytab.s1e710e'));
} catch (e) { } catch (e) {
toast.error((e as { message?: string }).message || '测试失败,请检查策略与联系人'); toast.error((e as { message?: string }).message || t('monitor.notifypolicytab.s84573c'));
} finally { } finally {
setTesting(null); setTesting(null);
} }
}; };
if (loading) return <PageLoading label="加载通知策略..." />; if (loading) return <PageLoading label=t('monitor.notifypolicytab.s37ea07') />;
return ( return (
<div className="space-y-4"> <div className="space-y-4">
@@ -263,7 +266,7 @@ export function NotifyPolicyTab() {
<CardContent className="space-y-3"> <CardContent className="space-y-3">
<div className="grid gap-3 md:grid-cols-2"> <div className="grid gap-3 md:grid-cols-2">
<div className="space-y-1.5"> <div className="space-y-1.5">
<Label className="text-xs text-[var(--dg-text-secondary)]">标题模版</Label> <Label className="text-xs text-[var(--dg-text-secondary)]">{t('monitor.notifypolicytab.s8e32c9')}</Label>
<Input <Input
className="dg-input text-xs" className="dg-input text-xs"
value={msgSettings.title_template} value={msgSettings.title_template}
@@ -272,7 +275,7 @@ export function NotifyPolicyTab() {
/> />
</div> </div>
<div className="space-y-1.5"> <div className="space-y-1.5">
<Label className="text-xs text-[var(--dg-text-secondary)]">平台署名</Label> <Label className="text-xs text-[var(--dg-text-secondary)]">{t('monitor.notifypolicytab.s8fae79')}</Label>
<Input <Input
className="dg-input text-xs" className="dg-input text-xs"
value={msgSettings.platform_name} value={msgSettings.platform_name}
@@ -282,7 +285,7 @@ export function NotifyPolicyTab() {
</div> </div>
</div> </div>
<div className="space-y-1.5"> <div className="space-y-1.5">
<Label className="text-xs text-[var(--dg-text-secondary)]">卡片底部</Label> <Label className="text-xs text-[var(--dg-text-secondary)]">{t('monitor.notifypolicytab.s9da0d8')}</Label>
<Input <Input
className="dg-input text-xs" className="dg-input text-xs"
value={msgSettings.footer_template} value={msgSettings.footer_template}
@@ -319,7 +322,7 @@ export function NotifyPolicyTab() {
<div> <div>
<CardTitle className="text-sm flex items-center gap-2"> <CardTitle className="text-sm flex items-center gap-2">
{cat.label} {cat.label}
{catDirty && <span className="text-[10px] text-[var(--dg-orange)]">未保存</span>} {catDirty && <span className="text-[10px] text-[var(--dg-orange)]">{t('common.unsaved')}</span>}
</CardTitle> </CardTitle>
<p className="text-[10px] text-[var(--dg-text-muted)] mt-0.5">{cat.desc}</p> <p className="text-[10px] text-[var(--dg-text-muted)] mt-0.5">{cat.desc}</p>
</div> </div>
@@ -333,16 +336,16 @@ export function NotifyPolicyTab() {
}))} }))}
/> />
<Label className="text-xs text-[var(--dg-text-secondary)] min-w-[2rem]"> <Label className="text-xs text-[var(--dg-text-secondary)] min-w-[2rem]">
{d.enabled ? '启用' : '停用'} {d.enabled ? t('common.enable') : t('common.deactivate')}
</Label> </Label>
</div> </div>
</div> </div>
</CardHeader> </CardHeader>
<CardContent className="space-y-3"> <CardContent className="space-y-3">
<div> <div>
<Label className="text-xs text-[var(--dg-text-secondary)]">通知联系组</Label> <Label className="text-xs text-[var(--dg-text-secondary)]">{t('monitor.notifypolicytab.sad2dee')}</Label>
{groups.length === 0 ? ( {groups.length === 0 ? (
<p className="text-[10px] text-[var(--dg-text-muted)] mt-1">暂无联系组</p> <p className="text-[10px] text-[var(--dg-text-muted)] mt-1">{t('monitor.noGroups')}</p>
) : ( ) : (
<div className="flex flex-wrap gap-1.5 mt-1.5"> <div className="flex flex-wrap gap-1.5 mt-1.5">
{groups.map(g => ( {groups.map(g => (
@@ -361,9 +364,9 @@ export function NotifyPolicyTab() {
)} )}
</div> </div>
<div> <div>
<Label className="text-xs text-[var(--dg-text-secondary)]">额外联系人</Label> <Label className="text-xs text-[var(--dg-text-secondary)]">{t('monitor.notifypolicytab.s762805')}</Label>
{contacts.length === 0 ? ( {contacts.length === 0 ? (
<p className="text-[10px] text-[var(--dg-text-muted)] mt-1">暂无联系人</p> <p className="text-[10px] text-[var(--dg-text-muted)] mt-1">{t('monitor.noContacts')}</p>
) : ( ) : (
<div className="flex flex-wrap gap-1.5 mt-1.5"> <div className="flex flex-wrap gap-1.5 mt-1.5">
{contacts.map(c => ( {contacts.map(c => (
@@ -12,15 +12,17 @@ import {
import { toast } from 'sonner'; import { toast } from 'sonner';
import { alertCenterApi } from '@/api'; import { alertCenterApi } from '@/api';
import type { JsonData } from '@/types/common'; import type { JsonData } from '@/types/common';
import { useTranslation } from 'react-i18next';
import i18n from '@/i18n';
// 静默类型中文标签 // 静默类型中文标签
const SILENCE_TYPE_LABELS: Record<string, string> = { const SILENCE_TYPE_LABELS: Record<string, string> = {
onetime: '一次性', onetime: i18n.t('monitor.silencedialog.sebc149'),
daily: '每天循环', daily: i18n.t('monitor.silencedialog.s256eba'),
weekly: '每周循环', weekly: i18n.t('monitor.silencedialog.s4dff11'),
}; };
const WEEKDAY_LABELS = ['周日', '周一', '周二', '周三', '周四', '周五', '周六']; const WEEKDAY_LABELS = [i18n.t('monitor.silencedialog.s562d74'), i18n.t('monitor.silencedialog.s1603b0'), i18n.t('monitor.silencedialog.sb5a6a0'), i18n.t('monitor.silencedialog.se60725'), i18n.t('monitor.silencedialog.s170fc8'), i18n.t('monitor.silencedialog.seb79ce'), i18n.t('monitor.silencedialog.s245751')];
export interface SilenceData { export interface SilenceData {
id?: number; id?: number;
@@ -53,6 +55,7 @@ export function SilenceDialog({
editingSilence?: JsonData; editingSilence?: JsonData;
onSaved: () => void; onSaved: () => void;
}) { }) {
const { t } = useTranslation();
const [saving, setSaving] = useState(false); const [saving, setSaving] = useState(false);
const [name, setName] = useState(''); const [name, setName] = useState('');
const [description, setDescription] = useState(''); const [description, setDescription] = useState('');
@@ -99,15 +102,15 @@ export function SilenceDialog({
const handleSave = async () => { const handleSave = async () => {
if (!name.trim()) { if (!name.trim()) {
toast.error('请填写规则名称'); toast.error(t('monitor.silencedialog.s411cac'));
return; return;
} }
if (!endTime) { if (!endTime) {
toast.error('请设置结束时间'); toast.error(t('monitor.silencedialog.s2ad542'));
return; return;
} }
if (silenceType === 'weekly' && weekdays.length === 0) { if (silenceType === 'weekly' && weekdays.length === 0) {
toast.error('每周静默需要选择至少一个星期'); toast.error(t('monitor.silencedialog.s1f832d'));
return; return;
} }
@@ -124,15 +127,15 @@ export function SilenceDialog({
try { try {
if (editingSilence) { if (editingSilence) {
await alertCenterApi.updateSilence(editingSilence.id, payload); await alertCenterApi.updateSilence(editingSilence.id, payload);
toast.success('静默规则已更新'); toast.success(t('monitor.silencedialog.s1cf989'));
} else { } else {
await alertCenterApi.createSilence(payload); await alertCenterApi.createSilence(payload);
toast.success('静默规则已创建'); toast.success(t('monitor.silencedialog.s56a18d'));
} }
onOpenChange(false); onOpenChange(false);
onSaved(); onSaved();
} catch { } catch {
toast.error('保存失败'); toast.error(t('common.saveFailed'));
} finally { } finally {
setSaving(false); setSaving(false);
} }
@@ -143,7 +146,7 @@ export function SilenceDialog({
<DialogContent showOverlay={false} className="bg-[var(--dg-bg-secondary)] border-[var(--dg-border)] max-w-lg"> <DialogContent showOverlay={false} className="bg-[var(--dg-bg-secondary)] border-[var(--dg-border)] max-w-lg">
<DialogHeader> <DialogHeader>
<DialogTitle className="text-[var(--dg-text-primary)]"> <DialogTitle className="text-[var(--dg-text-primary)]">
{editingSilence ? '编辑静默规则' : '创建静默规则'} {editingSilence ? t('monitor.silencedialog.sab13fe') : t('monitor.silencedialog.s22ebe5')}
</DialogTitle> </DialogTitle>
<DialogDescription className="text-[var(--dg-text-secondary)]"> <DialogDescription className="text-[var(--dg-text-secondary)]">
静默期间匹配的告警将不会触发通知 静默期间匹配的告警将不会触发通知
@@ -152,29 +155,29 @@ export function SilenceDialog({
<div className="space-y-4 max-h-[60vh] overflow-y-auto pr-1"> <div className="space-y-4 max-h-[60vh] overflow-y-auto pr-1">
{/* 名称 */} {/* 名称 */}
<div className="space-y-1.5"> <div className="space-y-1.5">
<Label className="text-[var(--dg-text-primary)]">规则名称 *</Label> <Label className="text-[var(--dg-text-primary)]">{t('monitor.silencedialog.s34fe90')}</Label>
<Input <Input
value={name} value={name}
onChange={(e) => setName(e.target.value)} onChange={(e) => setName(e.target.value)}
placeholder="如:维护窗口静默" placeholder=t('monitor.silencedialog.s397662')
className="bg-[var(--dg-bg-primary)]" className="bg-[var(--dg-bg-primary)]"
/> />
</div> </div>
{/* 描述 */} {/* 描述 */}
<div className="space-y-1.5"> <div className="space-y-1.5">
<Label className="text-[var(--dg-text-primary)]">描述</Label> <Label className="text-[var(--dg-text-primary)]">{t('common.description')}</Label>
<Input <Input
value={description} value={description}
onChange={(e) => setDescription(e.target.value)} onChange={(e) => setDescription(e.target.value)}
placeholder="可选备注" placeholder=t('monitor.silencedialog.se67484')
className="bg-[var(--dg-bg-primary)]" className="bg-[var(--dg-bg-primary)]"
/> />
</div> </div>
{/* 静默类型 */} {/* 静默类型 */}
<div className="space-y-1.5"> <div className="space-y-1.5">
<Label className="text-[var(--dg-text-primary)]">静默类型</Label> <Label className="text-[var(--dg-text-primary)]">{t('monitor.silencedialog.s52aec8')}</Label>
<Select value={silenceType} onValueChange={setSilenceType}> <Select value={silenceType} onValueChange={setSilenceType}>
<SelectTrigger className="bg-[var(--dg-bg-primary)]"> <SelectTrigger className="bg-[var(--dg-bg-primary)]">
<SelectValue /> <SelectValue />
@@ -191,7 +194,7 @@ export function SilenceDialog({
<div className="grid grid-cols-2 gap-3"> <div className="grid grid-cols-2 gap-3">
<div className="space-y-1.5"> <div className="space-y-1.5">
<Label className="text-[var(--dg-text-primary)]"> <Label className="text-[var(--dg-text-primary)]">
{silenceType === 'onetime' ? '开始时间' : '每日开始'} {silenceType === 'onetime' ? t('common.startTime') : t('monitor.silencedialog.s48bccf')}
</Label> </Label>
<Input <Input
type="datetime-local" type="datetime-local"
@@ -202,7 +205,7 @@ export function SilenceDialog({
</div> </div>
<div className="space-y-1.5"> <div className="space-y-1.5">
<Label className="text-[var(--dg-text-primary)]"> <Label className="text-[var(--dg-text-primary)]">
{silenceType === 'onetime' ? '结束时间' : '每日结束'} {silenceType === 'onetime' ? t('common.endTime') : t('monitor.silencedialog.s18e2c5')}
</Label> </Label>
<Input <Input
type="datetime-local" type="datetime-local"
@@ -216,7 +219,7 @@ export function SilenceDialog({
{/* 星期选择(仅 weekly) */} {/* 星期选择(仅 weekly) */}
{silenceType === 'weekly' && ( {silenceType === 'weekly' && (
<div className="space-y-1.5"> <div className="space-y-1.5">
<Label className="text-[var(--dg-text-primary)]">生效星期</Label> <Label className="text-[var(--dg-text-primary)]">{t('monitor.silencedialog.s859824')}</Label>
<div className="flex flex-wrap gap-2"> <div className="flex flex-wrap gap-2">
{WEEKDAY_LABELS.map((label, idx) => ( {WEEKDAY_LABELS.map((label, idx) => (
<button <button
@@ -238,15 +241,15 @@ export function SilenceDialog({
{/* 提示 */} {/* 提示 */}
<div className="text-xs text-muted-foreground bg-muted/50 rounded-md p-2"> <div className="text-xs text-muted-foreground bg-muted/50 rounded-md p-2">
{silenceType === 'onetime' && '在指定时间窗口内,所有匹配条件的告警将被静默。窗口结束后自动恢复正常。'} {silenceType === 'onetime' && t('monitor.silencedialog.s67c15d')}
{silenceType === 'daily' && '每天在指定时段内静默告警,适合非工作时间免打扰。'} {silenceType === 'daily' && t('monitor.silencedialog.s2e62d4')}
{silenceType === 'weekly' && '仅在选定星期的指定时段内静默,适合周末维护窗口。'} {silenceType === 'weekly' && t('monitor.silencedialog.s5a3033')}
</div> </div>
</div> </div>
<DialogFooter> <DialogFooter>
<Button variant="outline" onClick={() => onOpenChange(false)}>取消</Button> <Button variant="outline" onClick={() => onOpenChange(false)}>{t('common.cancel')}</Button>
<Button onClick={handleSave} disabled={saving}> <Button onClick={handleSave} disabled={saving}>
{saving ? '保存中…' : '保存'} {saving ? i18n.t('monitor.silencedialog.s9b5d32') : i18n.t('common.save')}
</Button> </Button>
</DialogFooter> </DialogFooter>
</DialogContent> </DialogContent>
@@ -10,14 +10,16 @@ import { useConfirm } from '@/components/ui/confirm-dialog';
import { alertCenterApi } from '@/api'; import { alertCenterApi } from '@/api';
import { SilenceDialog } from './SilenceDialog'; import { SilenceDialog } from './SilenceDialog';
import type { JsonData } from '@/types/common'; import type { JsonData } from '@/types/common';
import { useTranslation } from 'react-i18next';
import i18n from '@/i18n';
const SILENCE_TYPE_LABELS: Record<string, string> = { const SILENCE_TYPE_LABELS: Record<string, string> = {
onetime: '一次性', onetime: i18n.t('monitor.silenceruletab.sebc149'),
daily: '每天', daily: i18n.t('monitor.silenceruletab.s78623e'),
weekly: '每周', weekly: i18n.t('monitor.silenceruletab.s09b03b'),
}; };
const WEEKDAY_LABELS = ['日', '一', '二', '三', '四', '五', '六']; const WEEKDAY_LABELS = [i18n.t('monitor.silenceruletab.s3edddd'), i18n.t('monitor.silenceruletab.s7941da'), i18n.t('monitor.silenceruletab.s2d8be2'), i18n.t('monitor.silenceruletab.se662ff'), i18n.t('monitor.silenceruletab.s21716c'), i18n.t('monitor.silenceruletab.s1fcc29'), i18n.t('monitor.silenceruletab.s61b453')];
function formatTime(t: string | Date): string { function formatTime(t: string | Date): string {
if (!t) return '—'; if (!t) return '—';
@@ -30,6 +32,7 @@ function formatTime(t: string | Date): string {
} }
const SilenceRuleTab: React.FC = () => { const SilenceRuleTab: React.FC = () => {
const { t } = useTranslation();
const confirm = useConfirm(); const confirm = useConfirm();
const [silences, setSilences] = useState<JsonData[]>([]); const [silences, setSilences] = useState<JsonData[]>([]);
const [loading, setLoading] = useState(false); const [loading, setLoading] = useState(false);
@@ -43,7 +46,7 @@ const SilenceRuleTab: React.FC = () => {
const list = res?.list || res?.data?.list || []; const list = res?.list || res?.data?.list || [];
setSilences(list); setSilences(list);
} catch { } catch {
toast.error('获取静默规则失败'); toast.error(t('monitor.silenceruletab.s48fb7a'));
} finally { } finally {
setLoading(false); setLoading(false);
} }
@@ -65,28 +68,28 @@ const SilenceRuleTab: React.FC = () => {
const handleDelete = async (silence: JsonData) => { const handleDelete = async (silence: JsonData) => {
const ok = await confirm({ const ok = await confirm({
title: '删除静默规则', title: t('monitor.silenceruletab.s7c9a53'),
description: `确定删除「${silence.name}」?删除后该规则匹配的告警将恢复通知。`, description: t('monitor.silenceruletab.s4fe220', { silence.name: silence.name }),
confirmText: '删除', confirmText: t('common.delete'),
variant: 'destructive', variant: 'destructive',
}); });
if (!ok) return; if (!ok) return;
try { try {
await alertCenterApi.deleteSilence(silence.id); await alertCenterApi.deleteSilence(silence.id);
toast.success('已删除'); toast.success(t('alert.deleted'));
fetchSilences(); fetchSilences();
} catch { } catch {
toast.error('删除失败'); toast.error(t('common.deleteFailed'));
} }
}; };
const handleToggle = async (silence: JsonData) => { const handleToggle = async (silence: JsonData) => {
try { try {
await alertCenterApi.toggleSilence(silence.id); await alertCenterApi.toggleSilence(silence.id);
toast.success(silence.status === 1 ? '已禁用' : '已启用'); toast.success(silence.status === 1 ? t('alert.disabled') : t('alert.enabled'));
fetchSilences(); fetchSilences();
} catch { } catch {
toast.error('操作失败'); toast.error(t('common.operationFailed'));
} }
}; };
@@ -122,13 +125,13 @@ const SilenceRuleTab: React.FC = () => {
{/* 规则列表 */} {/* 规则列表 */}
{loading && silences.length === 0 ? ( {loading && silences.length === 0 ? (
<div className="text-center py-12 text-muted-foreground"> <div className="text-center py-12 text-muted-foreground">
<p className="text-sm">加载中...</p> <p className="text-sm">{t('common.loading')}</p>
</div> </div>
) : silences.length === 0 ? ( ) : silences.length === 0 ? (
<div className="text-center py-12 text-muted-foreground border border-dashed rounded-lg"> <div className="text-center py-12 text-muted-foreground border border-dashed rounded-lg">
<VolumeX className="w-10 h-10 mx-auto mb-2 opacity-50" /> <VolumeX className="w-10 h-10 mx-auto mb-2 opacity-50" />
<p className="text-sm">暂无静默规则</p> <p className="text-sm">{t('monitor.noSilences')}</p>
<p className="text-xs mt-1">点击「添加静默规则」创建维护窗口或免打扰时段</p> <p className="text-xs mt-1">{t('monitor.silenceruletab.s862a1b')}</p>
</div> </div>
) : ( ) : (
<div className="grid grid-cols-1 gap-3"> <div className="grid grid-cols-1 gap-3">
@@ -156,10 +159,10 @@ const SilenceRuleTab: React.FC = () => {
</Badge> </Badge>
{/* 活跃状态 */} {/* 活跃状态 */}
{active && ( {active && (
<Badge className="bg-green-500 text-xs">生效中</Badge> <Badge className="bg-green-500 text-xs">{t('monitor.silenceActive')}</Badge>
)} )}
{!enabled && ( {!enabled && (
<Badge variant="secondary" className="text-xs">已禁用</Badge> <Badge variant="secondary" className="text-xs">{t('alert.disabled')}</Badge>
)} )}
</div> </div>
@@ -172,7 +175,7 @@ const SilenceRuleTab: React.FC = () => {
<span> <span>
{sType === 'onetime' {sType === 'onetime'
? `${formatTime(s.start_time)} — ${formatTime(s.end_time)}` ? `${formatTime(s.start_time)} — ${formatTime(s.end_time)}`
: `每日 ${formatTime(s.start_time)} — ${formatTime(s.end_time)}` : t('monitor.silenceruletab.s8bdc6c', { formatTime(s.start_time): formatTime(s.start_time), formatTime(s.end_time): formatTime(s.end_time) })
} }
</span> </span>
{sType === 'weekly' && weekdayList.length > 0 && ( {sType === 'weekly' && weekdayList.length > 0 && (
@@ -10,14 +10,16 @@ import { useConfirm } from '@/components/ui/confirm-dialog';
import { alertCenterApi } from '@/api'; import { alertCenterApi } from '@/api';
import { SilenceDialog } from './SilenceDialog'; import { SilenceDialog } from './SilenceDialog';
import type { JsonData } from '@/types/common'; import type { JsonData } from '@/types/common';
import { useTranslation } from 'react-i18next';
import i18n from '@/i18n';
const SILENCE_TYPE_LABELS: Record<string, string> = { const SILENCE_TYPE_LABELS: Record<string, string> = {
onetime: '一次性', onetime: i18n.t('monitor.silencerulespanel.sebc149'),
daily: '每天', daily: i18n.t('monitor.silencerulespanel.s78623e'),
weekly: '每周', weekly: i18n.t('monitor.silencerulespanel.s09b03b'),
}; };
const WEEKDAY_LABELS = ['日', '一', '二', '三', '四', '五', '六']; const WEEKDAY_LABELS = [i18n.t('monitor.silencerulespanel.s3edddd'), i18n.t('monitor.silencerulespanel.s7941da'), i18n.t('monitor.silencerulespanel.s2d8be2'), i18n.t('monitor.silencerulespanel.se662ff'), i18n.t('monitor.silencerulespanel.s21716c'), i18n.t('monitor.silencerulespanel.s1fcc29'), i18n.t('monitor.silencerulespanel.s61b453')];
function formatTime(t: string | Date): string { function formatTime(t: string | Date): string {
if (!t) return '—'; if (!t) return '—';
@@ -30,6 +32,7 @@ function formatTime(t: string | Date): string {
} }
export function SilenceRulesPanel() { export function SilenceRulesPanel() {
const { t } = useTranslation();
const confirm = useConfirm(); const confirm = useConfirm();
const [silences, setSilences] = useState<JsonData[]>([]); const [silences, setSilences] = useState<JsonData[]>([]);
const [loading, setLoading] = useState(false); const [loading, setLoading] = useState(false);
@@ -43,7 +46,7 @@ export function SilenceRulesPanel() {
const list = res?.list || res?.data?.list || []; const list = res?.list || res?.data?.list || [];
setSilences(list); setSilences(list);
} catch { } catch {
toast.error('获取静默规则失败'); toast.error(t('monitor.silencerulespanel.s48fb7a'));
} finally { } finally {
setLoading(false); setLoading(false);
} }
@@ -53,28 +56,28 @@ export function SilenceRulesPanel() {
const handleDelete = async (silence: JsonData) => { const handleDelete = async (silence: JsonData) => {
const ok = await confirm({ const ok = await confirm({
title: '删除静默规则', title: t('monitor.silencerulespanel.s7c9a53'),
description: `确定删除「${silence.name}」?`, description: t('monitor.silencerulespanel.seff173', { silence.name: silence.name }),
confirmText: '删除', confirmText: t('common.delete'),
variant: 'destructive', variant: 'destructive',
}); });
if (!ok) return; if (!ok) return;
try { try {
await alertCenterApi.deleteSilence(silence.id); await alertCenterApi.deleteSilence(silence.id);
toast.success('已删除'); toast.success(t('alert.deleted'));
fetchSilences(); fetchSilences();
} catch { } catch {
toast.error('删除失败'); toast.error(t('common.deleteFailed'));
} }
}; };
const handleToggle = async (silence: JsonData) => { const handleToggle = async (silence: JsonData) => {
try { try {
await alertCenterApi.toggleSilence(silence.id); await alertCenterApi.toggleSilence(silence.id);
toast.success(silence.status === 1 ? '已禁用' : '已启用'); toast.success(silence.status === 1 ? t('alert.disabled') : t('alert.enabled'));
fetchSilences(); fetchSilences();
} catch { } catch {
toast.error('操作失败'); toast.error(t('common.operationFailed'));
} }
}; };
@@ -90,8 +93,8 @@ export function SilenceRulesPanel() {
<div className="flex justify-between items-center"> <div className="flex justify-between items-center">
<div className="flex items-center gap-2"> <div className="flex items-center gap-2">
<VolumeX className="w-4 h-4 text-muted-foreground" /> <VolumeX className="w-4 h-4 text-muted-foreground" />
<h3 className="text-sm font-medium">静默规则</h3> <h3 className="text-sm font-medium">{t('monitor.silences')}</h3>
<span className="text-xs text-muted-foreground">维护窗口 / 免打扰时段</span> <span className="text-xs text-muted-foreground">{t('monitor.silencerulespanel.sed566e')}</span>
</div> </div>
<div className="flex items-center gap-2"> <div className="flex items-center gap-2">
<Button variant="outline" size="sm" className="h-7 text-xs" onClick={fetchSilences} disabled={loading}> <Button variant="outline" size="sm" className="h-7 text-xs" onClick={fetchSilences} disabled={loading}>
@@ -104,10 +107,10 @@ export function SilenceRulesPanel() {
</div> </div>
{loading && silences.length === 0 ? ( {loading && silences.length === 0 ? (
<p className="text-xs text-muted-foreground text-center py-6">加载中...</p> <p className="text-xs text-muted-foreground text-center py-6">{t('common.loading')}</p>
) : silences.length === 0 ? ( ) : silences.length === 0 ? (
<div className="text-center py-8 text-muted-foreground border border-dashed border-[var(--dg-border)] rounded-lg"> <div className="text-center py-8 text-muted-foreground border border-dashed border-[var(--dg-border)] rounded-lg">
<p className="text-xs">暂无静默规则,告警将按通知策略正常发送</p> <p className="text-xs">{t('monitor.silencerulespanel.s537761')}</p>
</div> </div>
) : ( ) : (
<div className="grid grid-cols-1 gap-2"> <div className="grid grid-cols-1 gap-2">
@@ -128,13 +131,13 @@ export function SilenceRulesPanel() {
<Badge variant="outline" className="text-[10px]"> <Badge variant="outline" className="text-[10px]">
{SILENCE_TYPE_LABELS[sType] || sType} {SILENCE_TYPE_LABELS[sType] || sType}
</Badge> </Badge>
{active && <Badge className="bg-green-500 text-[10px]">生效中</Badge>} {active && <Badge className="bg-green-500 text-[10px]">{t('monitor.silenceActive')}</Badge>}
{!enabled && <Badge variant="secondary" className="text-[10px]">已禁用</Badge>} {!enabled && <Badge variant="secondary" className="text-[10px]">{t('alert.disabled')}</Badge>}
</div> </div>
<p className="text-[10px] text-muted-foreground"> <p className="text-[10px] text-muted-foreground">
{sType === 'onetime' {sType === 'onetime'
? `${formatTime(s.start_time)} — ${formatTime(s.end_time)}` ? `${formatTime(s.start_time)} — ${formatTime(s.end_time)}`
: `每日 ${formatTime(s.start_time)} — ${formatTime(s.end_time)}`} : t('monitor.silencerulespanel.s8bdc6c', { formatTime(s.start_time): formatTime(s.start_time), formatTime(s.end_time): formatTime(s.end_time) })}
{sType === 'weekly' && weekdayList.length > 0 && ( {sType === 'weekly' && weekdayList.length > 0 && (
<span className="ml-2"> <span className="ml-2">
周{weekdayList.sort((a, b) => a - b).map((d) => WEEKDAY_LABELS[d]).join('')} 周{weekdayList.sort((a, b) => a - b).map((d) => WEEKDAY_LABELS[d]).join('')}
@@ -6,6 +6,7 @@ import {
} from 'lucide-react'; } from 'lucide-react';
import { Badge } from '@/components/ui/badge'; import { Badge } from '@/components/ui/badge';
import type { JsonData } from '@/types/common'; import type { JsonData } from '@/types/common';
import i18n from '@/i18n';
/** 前端 Alert 接口 */ /** 前端 Alert 接口 */
export interface Alert { export interface Alert {
@@ -77,7 +78,7 @@ export interface ContactGroup {
} }
const SOURCE_LABELS: Record<string, string> = { const SOURCE_LABELS: Record<string, string> = {
host: '主机监控', middleware: '中间件监控', site: '站点拨测', snmp: 'SNMP 监控', log: '日志告警', host: i18n.t('monitor.hostMonitor'), middleware: i18n.t('monitor.middleware'), site: i18n.t('monitor.siteProbe'), snmp: i18n.t('monitor.snmp.title'), log: i18n.t('menu.logAlerts'),
}; };
// Logan.Li — 后端字段映射到前端 Alert 接口 // Logan.Li — 后端字段映射到前端 Alert 接口
@@ -85,7 +86,7 @@ export function mapAlert(a: JsonData): Alert {
const sourceType = String(a.source_type || a.sourceType || ''); const sourceType = String(a.source_type || a.sourceType || '');
return { return {
id: String(a.id), id: String(a.id),
title: a.title || a.rule_name || `告警 #${a.id}`, title: a.title || a.rule_name || i18n.t('monitor.alertCenterHelpers.sd0abee', { a.id: a.id }),
description: a.message || a.description || '', description: a.message || a.description || '',
severity: (a.severity || 'info') as Alert['severity'], severity: (a.severity || 'info') as Alert['severity'],
status: (a.status || 'firing') as Alert['status'], status: (a.status || 'firing') as Alert['status'],
@@ -112,13 +113,13 @@ export function mapAlert(a: JsonData): Alert {
export function getSeverityBadge(severity: string) { export function getSeverityBadge(severity: string) {
switch (severity) { switch (severity) {
case 'critical': case 'critical':
return <Badge variant="destructive" className="gap-1"><AlertCircle className="w-3 h-3" />严重</Badge>; return <Badge variant="destructive" className="gap-1"><AlertCircle className="w-3 h-3" />{i18n.t('monitor.critical')}</Badge>;
case 'warning': case 'warning':
return <Badge variant="default" className="bg-orange-500 gap-1"><AlertTriangle className="w-3 h-3" />警告</Badge>; return <Badge variant="default" className="bg-orange-500 gap-1"><AlertTriangle className="w-3 h-3" />{i18n.t('common.warning')}</Badge>;
case 'info': case 'info':
return <Badge variant="default" className="bg-blue-500 gap-1"><Info className="w-3 h-3" />信息</Badge>; return <Badge variant="default" className="bg-blue-500 gap-1"><Info className="w-3 h-3" />{i18n.t('monitor.info')}</Badge>;
default: default:
return <Badge variant="secondary">未知</Badge>; return <Badge variant="secondary">{i18n.t('common.unknown')}</Badge>;
} }
} }
@@ -126,15 +127,15 @@ export function getSeverityBadge(severity: string) {
export function getStatusBadge(status: string) { export function getStatusBadge(status: string) {
switch (status) { switch (status) {
case 'firing': case 'firing':
return <Badge variant="destructive" className="gap-1 animate-pulse"><Zap className="w-3 h-3" />触发中</Badge>; return <Badge variant="destructive" className="gap-1 animate-pulse"><Zap className="w-3 h-3" />{i18n.t('monitor.firing')}</Badge>;
case 'acknowledged': case 'acknowledged':
return <Badge variant="default" className="bg-yellow-500 gap-1"><User className="w-3 h-3" />已确认</Badge>; return <Badge variant="default" className="bg-yellow-500 gap-1"><User className="w-3 h-3" />{i18n.t('monitor.acknowledged')}</Badge>;
case 'resolved': case 'resolved':
return <Badge variant="default" className="bg-green-500 gap-1"><CheckCircle className="w-3 h-3" />已解决</Badge>; return <Badge variant="default" className="bg-green-500 gap-1"><CheckCircle className="w-3 h-3" />{i18n.t('monitor.resolved')}</Badge>;
case 'suppressed': case 'suppressed':
return <Badge variant="secondary" className="gap-1"><VolumeX className="w-3 h-3" />已静默</Badge>; return <Badge variant="secondary" className="gap-1"><VolumeX className="w-3 h-3" />{i18n.t('monitor.alertCenterHelpers.s1325a8')}</Badge>;
default: default:
return <Badge variant="secondary">未知</Badge>; return <Badge variant="secondary">{i18n.t('common.unknown')}</Badge>;
} }
} }
@@ -155,8 +156,8 @@ export function getChannelIcon(type: string) {
/** 渠道类型中文标签 */ /** 渠道类型中文标签 */
export function getChannelTypeLabel(type: string) { export function getChannelTypeLabel(type: string) {
const map: Record<string, string> = { const map: Record<string, string> = {
dingtalk: '钉钉', wechat: '企业微信', feishu: '飞书', dingtalk: i18n.t('monitor.contactDingtalk'), wechat: i18n.t('monitor.contactWechat'), feishu: i18n.t('monitor.alertCenterHelpers.s7714e5'),
email: '邮件', sms: '短信', webhook: 'Webhook', email: i18n.t('common.email'), sms: i18n.t('common.sms'), webhook: 'Webhook',
}; };
return map[type] || type; return map[type] || type;
} }
@@ -1,5 +1,6 @@
import { Mail, Phone, MessageSquare, Bell } from 'lucide-react'; import { Mail, Phone, MessageSquare, Bell } from 'lucide-react';
import type { AlertChannel, AlertRuleRecord } from '@/types'; import type { AlertChannel, AlertRuleRecord } from '@/types';
import i18n from '@/i18n';
// 将 notify_channels (可能是数组/JSON字符串/逗号分隔) 解析为数组 // 将 notify_channels (可能是数组/JSON字符串/逗号分隔) 解析为数组
export function parseChannels( notifyChannels: unknown): string[] { export function parseChannels( notifyChannels: unknown): string[] {
@@ -22,10 +23,10 @@ export const KNOWN_CHANNEL_TYPES = ['email', 'sms', 'dingtalk', 'wechat', 'webho
// 根据渠道类型获取图标组件名(用字符串映射,组件内用 getChannelIcon 返回实际组件) // 根据渠道类型获取图标组件名(用字符串映射,组件内用 getChannelIcon 返回实际组件)
export const CHANNEL_TYPE_LABELS: Record<string, string> = { export const CHANNEL_TYPE_LABELS: Record<string, string> = {
dingtalk: '钉钉', dingtalk: i18n.t('monitor.contactDingtalk'),
wechat: '企业微信', wechat: i18n.t('monitor.contactWechat'),
email: '邮件', email: i18n.t('common.email'),
sms: '短信', sms: i18n.t('common.sms'),
webhook: 'Webhook', webhook: 'Webhook',
}; };
@@ -35,7 +36,7 @@ export function resolveChannelRef(value: string, channels: AlertChannel[]): { ty
if (!value) return null; if (!value) return null;
// 尝试按 ID 匹配已配置渠道 // 尝试按 ID 匹配已配置渠道
const ch = channels.find((c) => String(c.id) === String(value)); const ch = channels.find((c) => String(c.id) === String(value));
if (ch) return { type: ch.type || 'unknown', name: ch.name || ch.type || '未命名', isLegacy: false }; if (ch) return { type: ch.type || 'unknown', name: ch.name || ch.type || i18n.t('monitor.alertshared.s7f0425'), isLegacy: false };
// 兼容旧格式:值本身是类型字符串 // 兼容旧格式:值本身是类型字符串
if (KNOWN_CHANNEL_TYPES.includes(value)) { if (KNOWN_CHANNEL_TYPES.includes(value)) {
return { type: value, name: CHANNEL_TYPE_LABELS[value] || value, isLegacy: true }; return { type: value, name: CHANNEL_TYPE_LABELS[value] || value, isLegacy: true };
@@ -45,10 +46,10 @@ export function resolveChannelRef(value: string, channels: AlertChannel[]): { ty
// 渠道类型选项(供下拉选择) // 渠道类型选项(供下拉选择)
export const CHANNEL_TYPES: { key: string; label: string; placeholder: string }[] = [ export const CHANNEL_TYPES: { key: string; label: string; placeholder: string }[] = [
{ key: 'dingtalk', label: '钉钉', placeholder: '{\n "webhook": "https://oapi.dingtalk.com/robot/send?access_token=***",\n "secret": "SECxxx"\n}' }, { key: 'dingtalk', label: i18n.t('monitor.contactDingtalk'), placeholder: '{\n "webhook": "https://oapi.dingtalk.com/robot/send?access_token=***",\n "secret": "SECxxx"\n}' },
{ key: 'wechat', label: '企业微信', placeholder: '{\n "webhook": "https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=***"\n}' }, { key: 'wechat', label: i18n.t('monitor.contactWechat'), placeholder: '{\n "webhook": "https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=***"\n}' },
{ key: 'email', label: '邮件', placeholder: '{\n "to": "ops@ezops.io",\n "subject": "告警通知"\n}' }, { key: 'email', label: i18n.t('common.email'), placeholder: i18n.t('monitor.alertshared.s92382d') },
{ key: 'sms', label: '短信', placeholder: '{\n "phones": "13800138000",\n "sign": "AIOps"\n}' }, { key: 'sms', label: i18n.t('common.sms'), placeholder: '{\n "phones": "13800138000",\n "sign": "AIOps"\n}' },
{ key: 'webhook', label: 'Webhook', placeholder: '{\n "url": "https://example.com/alert"\n}' }, { key: 'webhook', label: 'Webhook', placeholder: '{\n "url": "https://example.com/alert"\n}' },
]; ];
@@ -5,6 +5,7 @@ import { TrendingUp, Loader2, AlertCircle } from 'lucide-react';
import { LineChart, Line, ResponsiveContainer, XAxis, YAxis, Tooltip, CartesianGrid } from 'recharts'; import { LineChart, Line, ResponsiveContainer, XAxis, YAxis, Tooltip, CartesianGrid } from 'recharts';
import type { Panel } from './GrafanaDashboard'; import type { Panel } from './GrafanaDashboard';
import { prometheusProxyApi, promDatasourceApi } from '@/api'; import { prometheusProxyApi, promDatasourceApi } from '@/api';
import { useTranslation } from 'react-i18next';
// 默认 Prometheus URL 缓存 // 默认 Prometheus URL 缓存
let _defaultPromURL: string | null = null; let _defaultPromURL: string | null = null;
@@ -70,6 +71,7 @@ function parseInstantResult(promResult: any): { labels: Record<string, string>;
/** 渲染面板内容 */ /** 渲染面板内容 */
export function GrafanaPanelContent({ panel, datasourceUrl }: { panel: Panel; datasourceUrl?: string }) { export function GrafanaPanelContent({ panel, datasourceUrl }: { panel: Panel; datasourceUrl?: string }) {
const { t } = useTranslation();
const [loading, setLoading] = useState(false); const [loading, setLoading] = useState(false);
const [error, setError] = useState(''); const [error, setError] = useState('');
const [chartData, setChartData] = useState<{ time: string; value: number }[]>([]); const [chartData, setChartData] = useState<{ time: string; value: number }[]>([]);
@@ -82,7 +84,7 @@ export function GrafanaPanelContent({ panel, datasourceUrl }: { panel: Panel; da
try { try {
const url = await getDefaultPromURL(datasourceUrl); const url = await getDefaultPromURL(datasourceUrl);
if (!url) { if (!url) {
setError('未配置 Prometheus 数据源'); setError(t('monitor.dashboard.prometheus.emptyTitle'));
setLoading(false); setLoading(false);
return; return;
} }
@@ -100,16 +102,16 @@ export function GrafanaPanelContent({ panel, datasourceUrl }: { panel: Panel; da
}); });
const parsed = parseRangeResult(res); const parsed = parseRangeResult(res);
setChartData(parsed.length > 0 ? parsed : []); setChartData(parsed.length > 0 ? parsed : []);
if (parsed.length === 0) setError('无数据'); if (parsed.length === 0) setError(t('kubernetes.configmap.noData'));
} else { } else {
// stat / gauge / table 用即时查询 // stat / gauge / table 用即时查询
const res = await prometheusProxyApi.query(url, panel.query); const res = await prometheusProxyApi.query(url, panel.query);
const parsed = parseInstantResult(res); const parsed = parseInstantResult(res);
setInstantData(parsed); setInstantData(parsed);
if (parsed.length === 0) setError('无数据'); if (parsed.length === 0) setError(t('kubernetes.configmap.noData'));
} }
} catch (e: any) { } catch (e: any) {
setError(e?.message ? String(e.message).slice(0, 80) : '查询失败'); setError(e?.message ? String(e.message).slice(0, 80) : t('monitor.grafanapanelcontent.s0d66ed'));
} finally { } finally {
setLoading(false); setLoading(false);
} }
@@ -153,7 +155,7 @@ export function GrafanaPanelContent({ panel, datasourceUrl }: { panel: Panel; da
{unit && <span className="text-sm text-[var(--dg-text-muted)] mt-2">{unit}</span>} {unit && <span className="text-sm text-[var(--dg-text-muted)] mt-2">{unit}</span>}
<div className="flex items-center gap-1 mt-2 dg-text-green text-sm"> <div className="flex items-center gap-1 mt-2 dg-text-green text-sm">
<TrendingUp className="w-4 h-4" /> <TrendingUp className="w-4 h-4" />
<span>实时</span> <span>{t('common.realtime')}</span>
</div> </div>
</div> </div>
); );
@@ -187,7 +189,7 @@ export function GrafanaPanelContent({ panel, datasourceUrl }: { panel: Panel; da
); );
} }
case 'table': { case 'table': {
if (instantData.length === 0) return <div className="text-center py-4 text-xs text-[var(--dg-text-muted)]">无数据</div>; if (instantData.length === 0) return <div className="text-center py-4 text-xs text-[var(--dg-text-muted)]">{t('kubernetes.configmap.noData')}</div>;
return ( return (
<div className="overflow-auto max-h-[200px]"> <div className="overflow-auto max-h-[200px]">
<table className="w-full text-[11px]"> <table className="w-full text-[11px]">
@@ -216,7 +218,7 @@ export function GrafanaPanelContent({ panel, datasourceUrl }: { panel: Panel; da
case 'graph': case 'graph':
default: { default: {
if (chartData.length === 0) { if (chartData.length === 0) {
return <div className="text-center py-4 text-xs text-[var(--dg-text-muted)]">无数据</div>; return <div className="text-center py-4 text-xs text-[var(--dg-text-muted)]">{t('kubernetes.configmap.noData')}</div>;
} }
return ( return (
<div className="h-full min-h-[120px]"> <div className="h-full min-h-[120px]">
@@ -30,6 +30,7 @@ import {
} from '@/components/ui/select'; } from '@/components/ui/select';
import { serverApi } from '@/api'; import { serverApi } from '@/api';
import type { JsonData } from '@/types/common'; import type { JsonData } from '@/types/common';
import { useTranslation } from 'react-i18next';
type SortField = 'hostname' | 'ip' | 'agent_version' | 'agent_status' | 'cpu_usage' | 'memory_usage' | 'disk_usage' | 'region'; type SortField = 'hostname' | 'ip' | 'agent_version' | 'agent_status' | 'cpu_usage' | 'memory_usage' | 'disk_usage' | 'region';
type SortDir = 'asc' | 'desc'; type SortDir = 'asc' | 'desc';
@@ -48,6 +49,7 @@ function getUsageBar(val: number) {
} }
export default function HostMonitorDashboard() { export default function HostMonitorDashboard() {
const { t } = useTranslation();
const navigate = useNavigate(); const navigate = useNavigate();
const [hosts, setHosts] = useState<JsonData[]>([]); const [hosts, setHosts] = useState<JsonData[]>([]);
const [total, setTotal] = useState(0); const [total, setTotal] = useState(0);
@@ -141,9 +143,9 @@ export default function HostMonitorDashboard() {
// 状态标签颜色 // 状态标签颜色
const statusBadge = (status: string) => { const statusBadge = (status: string) => {
if (status === 'online') return <Badge className="bg-emerald-500/20 dg-text-green border-emerald-500/30 text-[11px]">在线</Badge>; if (status === 'online') return <Badge className="bg-emerald-500/20 dg-text-green border-emerald-500/30 text-[11px]">{t('common.online')}</Badge>;
if (status === 'running') return <Badge className="bg-blue-500/20 dg-text-blue border-blue-500/30 text-[11px]">运行中</Badge>; if (status === 'running') return <Badge className="bg-blue-500/20 dg-text-blue border-blue-500/30 text-[11px]">{t('common.running')}</Badge>;
if (status === 'stopped') return <Badge className="bg-[var(--dg-bg-active)]/20 dg-text-secondary border-[var(--dg-border)] text-[11px]">已停止</Badge>; if (status === 'stopped') return <Badge className="bg-[var(--dg-bg-active)]/20 dg-text-secondary border-[var(--dg-border)] text-[11px]">{t('common.stopped')}</Badge>;
return <Badge variant="outline" className="text-[11px] dg-text-muted">{status || '--'}</Badge>; return <Badge variant="outline" className="text-[11px] dg-text-muted">{status || '--'}</Badge>;
}; };
@@ -156,7 +158,7 @@ export default function HostMonitorDashboard() {
<div className="p-1.5 rounded-lg bg-blue-500/10"><Server className="h-4 w-4 dg-text-blue" /></div> <div className="p-1.5 rounded-lg bg-blue-500/10"><Server className="h-4 w-4 dg-text-blue" /></div>
<div> <div>
<div className="text-xl font-bold text-[var(--dg-text-primary)]">{stats.total}</div> <div className="text-xl font-bold text-[var(--dg-text-primary)]">{stats.total}</div>
<div className="text-[10px] text-[var(--dg-text-muted)]">主机总数</div> <div className="text-[10px] text-[var(--dg-text-muted)]">{t('monitor.hostmonitordashboard.sd94cd2')}</div>
</div> </div>
</CardContent> </CardContent>
</Card> </Card>
@@ -165,7 +167,7 @@ export default function HostMonitorDashboard() {
<div className="p-1.5 rounded-lg bg-emerald-500/10"><Wifi className="h-4 w-4 dg-text-green" /></div> <div className="p-1.5 rounded-lg bg-emerald-500/10"><Wifi className="h-4 w-4 dg-text-green" /></div>
<div> <div>
<div className="text-xl font-bold dg-text-green">{stats.online}</div> <div className="text-xl font-bold dg-text-green">{stats.online}</div>
<div className="text-[10px] text-[var(--dg-text-muted)]">Agent 在线</div> <div className="text-[10px] text-[var(--dg-text-muted)]">{t('monitor.hostmonitordashboard.s42860c')}</div>
</div> </div>
</CardContent> </CardContent>
</Card> </Card>
@@ -174,7 +176,7 @@ export default function HostMonitorDashboard() {
<div className="p-1.5 rounded-lg bg-[var(--dg-bg-active)]/10"><WifiOff className="h-4 w-4 dg-text-secondary" /></div> <div className="p-1.5 rounded-lg bg-[var(--dg-bg-active)]/10"><WifiOff className="h-4 w-4 dg-text-secondary" /></div>
<div> <div>
<div className="text-xl font-bold dg-text-secondary">{stats.offline}</div> <div className="text-xl font-bold dg-text-secondary">{stats.offline}</div>
<div className="text-[10px] text-[var(--dg-text-muted)]">离线</div> <div className="text-[10px] text-[var(--dg-text-muted)]">{t('common.offline')}</div>
</div> </div>
</CardContent> </CardContent>
</Card> </Card>
@@ -190,7 +192,7 @@ export default function HostMonitorDashboard() {
<div className="p-1.5 rounded-lg bg-red-500/10"><Cpu className="h-4 w-4 dg-text-red" /></div> <div className="p-1.5 rounded-lg bg-red-500/10"><Cpu className="h-4 w-4 dg-text-red" /></div>
<div> <div>
<div className={`text-xl font-bold ${cpuColor}`}>{avgCpu.toFixed(1)}<span className="text-sm">%</span></div> <div className={`text-xl font-bold ${cpuColor}`}>{avgCpu.toFixed(1)}<span className="text-sm">%</span></div>
<div className="text-[10px] text-[var(--dg-text-muted)]">平均 CPU</div> <div className="text-[10px] text-[var(--dg-text-muted)]">{t('monitor.hostmonitordashboard.s16dd85')}</div>
</div> </div>
</CardContent> </CardContent>
</Card> </Card>
@@ -199,7 +201,7 @@ export default function HostMonitorDashboard() {
<div className="p-1.5 rounded-lg bg-amber-500/10"><Server className="h-4 w-4 dg-text-yellow" /></div> <div className="p-1.5 rounded-lg bg-amber-500/10"><Server className="h-4 w-4 dg-text-yellow" /></div>
<div> <div>
<div className={`text-xl font-bold ${memColor}`}>{avgMem.toFixed(1)}<span className="text-sm">%</span></div> <div className={`text-xl font-bold ${memColor}`}>{avgMem.toFixed(1)}<span className="text-sm">%</span></div>
<div className="text-[10px] text-[var(--dg-text-muted)]">平均内存</div> <div className="text-[10px] text-[var(--dg-text-muted)]">{t('monitor.hostmonitordashboard.sa09099')}</div>
</div> </div>
</CardContent> </CardContent>
</Card> </Card>
@@ -216,7 +218,7 @@ export default function HostMonitorDashboard() {
<CardTitle className="text-sm flex items-center gap-2 text-[var(--dg-text-primary)]"> <CardTitle className="text-sm flex items-center gap-2 text-[var(--dg-text-primary)]">
<Cpu className="h-4 w-4 dg-text-red" /> <Cpu className="h-4 w-4 dg-text-red" />
CPU 使用率 Top 5 CPU 使用率 Top 5
<Badge variant="outline" className="text-[10px] bg-red-500/10 dg-text-red border-red-500/30">阈值: 60% / 85%</Badge> <Badge variant="outline" className="text-[10px] bg-red-500/10 dg-text-red border-red-500/30">{t('monitor.hostmonitordashboard.sec309b')}</Badge>
</CardTitle> </CardTitle>
</CardHeader> </CardHeader>
<CardContent className="space-y-2"> <CardContent className="space-y-2">
@@ -257,7 +259,7 @@ export default function HostMonitorDashboard() {
<CardTitle className="text-sm flex items-center gap-2 text-[var(--dg-text-primary)]"> <CardTitle className="text-sm flex items-center gap-2 text-[var(--dg-text-primary)]">
<Server className="h-4 w-4 dg-text-yellow" /> <Server className="h-4 w-4 dg-text-yellow" />
内存使用率 Top 5 内存使用率 Top 5
<Badge variant="outline" className="text-[10px] bg-amber-500/10 dg-text-yellow border-amber-500/30">阈值: 60% / 85%</Badge> <Badge variant="outline" className="text-[10px] bg-amber-500/10 dg-text-yellow border-amber-500/30">{t('monitor.hostmonitordashboard.sec309b')}</Badge>
</CardTitle> </CardTitle>
</CardHeader> </CardHeader>
<CardContent className="space-y-2"> <CardContent className="space-y-2">
@@ -300,15 +302,15 @@ export default function HostMonitorDashboard() {
<div className="flex items-center justify-between"> <div className="flex items-center justify-between">
<div className="flex items-center gap-2"> <div className="flex items-center gap-2">
<Activity className="h-5 w-5 dg-text-green" /> <Activity className="h-5 w-5 dg-text-green" />
<CardTitle className="text-base text-[var(--dg-text-primary)]">主机监控列表</CardTitle> <CardTitle className="text-base text-[var(--dg-text-primary)]">{t('monitor.hostmonitordashboard.s6aa711')}</CardTitle>
<Badge variant="outline" className="text-xs bg-emerald-500/10 dg-text-green border-emerald-500/30">实时</Badge> <Badge variant="outline" className="text-xs bg-emerald-500/10 dg-text-green border-emerald-500/30">{t('common.realtime')}</Badge>
</div> </div>
<div className="flex items-center gap-2"> <div className="flex items-center gap-2">
<div className="relative"> <div className="relative">
<Search className="absolute left-2.5 top-1/2 -translate-y-1/2 h-4 w-4 dg-text-muted" /> <Search className="absolute left-2.5 top-1/2 -translate-y-1/2 h-4 w-4 dg-text-muted" />
<Input <Input
className="w-[200px] pl-8 h-8 text-sm bg-[var(--dg-bg-primary)]" className="w-[200px] pl-8 h-8 text-sm bg-[var(--dg-bg-primary)]"
placeholder="搜索主机名/IP..." placeholder=t('monitor.hostmonitordashboard.s3d0fc0')
value={search} value={search}
onChange={(e) => setSearch(e.target.value)} onChange={(e) => setSearch(e.target.value)}
onKeyDown={(e) => e.key === 'Enter' && handleSearch()} onKeyDown={(e) => e.key === 'Enter' && handleSearch()}
@@ -325,13 +327,13 @@ export default function HostMonitorDashboard() {
{loading ? ( {loading ? (
<div className="py-16 text-center text-[var(--dg-text-muted)]"> <div className="py-16 text-center text-[var(--dg-text-muted)]">
<Activity className="h-8 w-8 mx-auto mb-2 animate-spin dg-text-green" /> <Activity className="h-8 w-8 mx-auto mb-2 animate-spin dg-text-green" />
<p className="text-sm">加载中...</p> <p className="text-sm">{t('common.loading')}</p>
</div> </div>
) : sorted.length === 0 ? ( ) : sorted.length === 0 ? (
<div className="py-16 text-center text-[var(--dg-text-muted)]"> <div className="py-16 text-center text-[var(--dg-text-muted)]">
<Server className="h-10 w-10 mx-auto mb-2 dg-text-muted" /> <Server className="h-10 w-10 mx-auto mb-2 dg-text-muted" />
<p className="text-sm">暂无主机数据</p> <p className="text-sm">{t('monitor.hostmonitordashboard.s2678f4')}</p>
<p className="text-xs mt-1">请先添加服务器,或等待 Agent 上报数据</p> <p className="text-xs mt-1">{t('monitor.hostmonitordashboard.s350255')}</p>
</div> </div>
) : ( ) : (
<> <>
@@ -340,14 +342,14 @@ export default function HostMonitorDashboard() {
<thead> <thead>
<tr className="border-b border-[var(--dg-border)]"> <tr className="border-b border-[var(--dg-border)]">
{[ {[
{ key: 'hostname', label: '主机名/ID', w: '' }, { key: 'hostname', label: t('monitor.hostmonitordashboard.s7ba2a1'), w: '' },
{ key: 'agent_version', label: 'Agent 版本', w: 'w-[100px]' }, { key: 'agent_version', label: t('monitor.systemInfo.agentVersion'), w: 'w-[100px]' },
{ key: 'agent_status', label: 'Agent 状态', w: 'w-[90px]' }, { key: 'agent_status', label: t('monitor.hostmonitordashboard.secfbd1'), w: 'w-[90px]' },
{ key: 'cpu_usage', label: 'CPU', w: 'w-[130px]' }, { key: 'cpu_usage', label: 'CPU', w: 'w-[130px]' },
{ key: 'memory_usage', label: '内存', w: 'w-[130px]' }, { key: 'memory_usage', label: t('k8s.pods.memory'), w: 'w-[130px]' },
{ key: 'disk_usage', label: '磁盘', w: 'w-[130px]' }, { key: 'disk_usage', label: t('dashboard.topUsage.disk'), w: 'w-[130px]' },
{ key: 'region', label: '所在区域', w: 'w-[120px]' }, { key: 'region', label: t('monitor.hostmonitordashboard.sc09adb'), w: 'w-[120px]' },
{ key: 'ip', label: 'IP 地址', w: 'w-[140px]' }, { key: 'ip', label: t('agent.agentIp'), w: 'w-[140px]' },
].map(col => ( ].map(col => (
<th <th
key={col.key} key={col.key}
@@ -360,7 +362,7 @@ export default function HostMonitorDashboard() {
</div> </div>
</th> </th>
))} ))}
<th className="text-left px-3 py-2.5 text-xs font-medium text-[var(--dg-text-muted)]">操作</th> <th className="text-left px-3 py-2.5 text-xs font-medium text-[var(--dg-text-muted)]">{t('common.actions')}</th>
</tr> </tr>
</thead> </thead>
<tbody> <tbody>
@@ -423,7 +425,7 @@ export default function HostMonitorDashboard() {
size="sm" size="sm"
className="h-7 text-xs dg-text-blue hover:text-blue-300 hover:bg-blue-500/10" className="h-7 text-xs dg-text-blue hover:text-blue-300 hover:bg-blue-500/10"
onClick={() => navigate(`/monitor-center?host=${encodeURIComponent(h.hostname)}`)} onClick={() => navigate(`/monitor-center?host=${encodeURIComponent(h.hostname)}`)}
title="查看监控图表" title=t('monitor.hostmonitordashboard.s2ee528')
> >
<Monitor className="h-3 w-3 mr-1" /> <Monitor className="h-3 w-3 mr-1" />
监控 监控
@@ -433,7 +435,7 @@ export default function HostMonitorDashboard() {
size="sm" size="sm"
className="h-7 text-xs dg-text-yellow hover:text-amber-300 hover:bg-amber-500/10" className="h-7 text-xs dg-text-yellow hover:text-amber-300 hover:bg-amber-500/10"
onClick={() => navigate(`/alerts?hostname=${encodeURIComponent(h.hostname)}`)} onClick={() => navigate(`/alerts?hostname=${encodeURIComponent(h.hostname)}`)}
title="查看报警规则" title=t('monitor.hostmonitordashboard.s356aa8')
> >
<Bell className="h-3 w-3 mr-1" /> <Bell className="h-3 w-3 mr-1" />
告警 告警
@@ -449,7 +451,7 @@ export default function HostMonitorDashboard() {
{/* 分页 */} {/* 分页 */}
<div className="flex items-center justify-between px-4 py-3 border-t border-[var(--dg-border)]"> <div className="flex items-center justify-between px-4 py-3 border-t border-[var(--dg-border)]">
<div className="flex items-center gap-2 text-xs text-[var(--dg-text-muted)]"> <div className="flex items-center gap-2 text-xs text-[var(--dg-text-muted)]">
<span>每页</span> <span>{t('common.perPage')}</span>
<Select value={String(pageSize)} onValueChange={(v) => { setPageSize(Number(v)); setPage(1); }}> <Select value={String(pageSize)} onValueChange={(v) => { setPageSize(Number(v)); setPage(1); }}>
<SelectTrigger className="h-7 w-[60px] text-xs"> <SelectTrigger className="h-7 w-[60px] text-xs">
<SelectValue /> <SelectValue />
@@ -8,10 +8,12 @@ import { StatStrip } from '@/components/ui/stat-strip';
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs'; import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs';
import { prometheusProxyApi } from '@/api'; import { prometheusProxyApi } from '@/api';
import type { JsonData } from '@/types/common'; import type { JsonData } from '@/types/common';
import { useTranslation } from 'react-i18next';
interface Props { dsUrl?: string; } interface Props { dsUrl?: string; }
const MiniBar = ({ val, label, color }: { val: number; label: string; color?: string }) => { const MiniBar = ({ val, label, color }: { val: number; label: string; color?: string }) => {
const { t } = useTranslation();
const pct = Math.min(val, 100); const pct = Math.min(val, 100);
return ( return (
<div className="flex items-center gap-1.5 min-w-[80px]"> <div className="flex items-center gap-1.5 min-w-[80px]">
@@ -46,6 +48,7 @@ function parsePrune( result: JsonData[]): JsonData[] {
} }
const Box = (p: JsonData) => <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" {...p}><path d="M21 16V8a2 2 0 0 0-1-1.73l-7-4a2 2 0 0 0-2 0l-7 4A2 2 0 0 0 3 8v8a2 2 0 0 0 1 1.73l7 4a2 2 0 0 0 2 0l7-4A2 2 0 0 0 21 16z"/></svg>; const Box = (p: JsonData) => <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" {...p}><path d="M21 16V8a2 2 0 0 0-1-1.73l-7-4a2 2 0 0 0-2 0l-7 4A2 2 0 0 0 3 8v8a2 2 0 0 0 1 1.73l7 4a2 2 0 0 0 2 0l7-4A2 2 0 0 0 21 16z"/></svg>;
const { t } = useTranslation();
const K8sPanel: React.FC<{ d: JsonData}> = ({ d }) => ( const K8sPanel: React.FC<{ d: JsonData}> = ({ d }) => (
<div className="space-y-4"> <div className="space-y-4">
@@ -58,7 +61,7 @@ const K8sPanel: React.FC<{ d: JsonData}> = ({ d }) => (
]} ]}
/> />
<div className="rounded-lg bg-[var(--dg-bg-primary)] border border-[var(--dg-border)] p-3 max-h-60 overflow-y-auto"> <div className="rounded-lg bg-[var(--dg-bg-primary)] border border-[var(--dg-border)] p-3 max-h-60 overflow-y-auto">
<div className="text-xs font-medium mb-2 flex items-center gap-1"><Cpu className="w-3 h-3 dg-text-purple" />节点 CPU / 内存利用率</div> <div className="text-xs font-medium mb-2 flex items-center gap-1"><Cpu className="w-3 h-3 dg-text-purple" />{i18n.t('monitor.prometheusdashboard.se7fb2b')}</div>
{(d.nodeCPU || []).map((n: JsonData, i: number) => { {(d.nodeCPU || []).map((n: JsonData, i: number) => {
const mem = (d.nodeMem || []).find((m: JsonData) => m.node === n.node); const mem = (d.nodeMem || []).find((m: JsonData) => m.node === n.node);
return <div key={i} className="flex items-center gap-3 text-[11px] mb-1.5"><span className="w-28 truncate" title={n.node}>{n.node}</span><MiniBar val={Number(n.value||0)} label={`${Number(n.value||0).toFixed(1)}%`} /><MiniBar val={Number(mem?.value||0)} label={`${Number(mem?.value||0).toFixed(1)}%`} color="bg-blue-500" /></div>; return <div key={i} className="flex items-center gap-3 text-[11px] mb-1.5"><span className="w-28 truncate" title={n.node}>{n.node}</span><MiniBar val={Number(n.value||0)} label={`${Number(n.value||0).toFixed(1)}%`} /><MiniBar val={Number(mem?.value||0)} label={`${Number(mem?.value||0).toFixed(1)}%`} color="bg-blue-500" /></div>;
@@ -70,7 +73,7 @@ const K8sPanel: React.FC<{ d: JsonData}> = ({ d }) => (
const NodePanel: React.FC<{ d: JsonData}> = ({ d }) => ( const NodePanel: React.FC<{ d: JsonData}> = ({ d }) => (
<div className="overflow-x-auto rounded-lg border border-[var(--dg-border)]"> <div className="overflow-x-auto rounded-lg border border-[var(--dg-border)]">
<table className="w-full text-xs"> <table className="w-full text-xs">
<thead className="bg-[var(--dg-bg-tertiary)]"><tr><th className="px-3 py-2 text-left">节点</th><th className="px-3 py-2 text-left">状态</th><th className="px-3 py-2 text-left">CPU</th><th className="px-3 py-2 text-left">内存</th><th className="px-3 py-2 text-left">磁盘</th><th className="px-3 py-2 text-left">流入</th><th className="px-3 py-2 text-left">流出</th></tr></thead> <thead className="bg-[var(--dg-bg-tertiary)]"><tr><th className="px-3 py-2 text-left">{i18n.t('k8s.tab.nodes')}</th><th className="px-3 py-2 text-left">{i18n.t('common.status')}</th><th className="px-3 py-2 text-left">CPU</th><th className="px-3 py-2 text-left">{i18n.t('k8s.pods.memory')}</th><th className="px-3 py-2 text-left">{i18n.t('dashboard.topUsage.disk')}</th><th className="px-3 py-2 text-left">{i18n.t('monitor.prometheusdashboard.s361ffa')}</th><th className="px-3 py-2 text-left">{i18n.t('monitor.prometheusdashboard.s37cc0a')}</th></tr></thead>
<tbody> <tbody>
{(d.nodes || []).map((n: JsonData, i: number) => { {(d.nodes || []).map((n: JsonData, i: number) => {
const inst = n.instance || n.exported_instance || ''; const inst = n.instance || n.exported_instance || '';
@@ -104,11 +107,12 @@ const PodPanel: React.FC<{ d: JsonData}> = ({ d }) => (
]} ]}
/> />
<div className="rounded-lg bg-[var(--dg-bg-primary)] p-3 max-h-40 overflow-y-auto"><div className="text-xs font-medium mb-2">CPU Top 10</div>{(d.cpuTop||[]).map((p: JsonData, i:number)=><div key={i} className="flex items-center gap-2 text-[11px] mb-1"><span className="w-10 text-right text-[var(--dg-text-muted)]">{i+1}</span><span className="w-32 truncate" title={p.pod}>{p.pod}</span><MiniBar val={Number(p.value||0)*100} label={`${Number(p.value||0).toFixed(2)}c`} color="bg-purple-500" /></div>)}</div> <div className="rounded-lg bg-[var(--dg-bg-primary)] p-3 max-h-40 overflow-y-auto"><div className="text-xs font-medium mb-2">CPU Top 10</div>{(d.cpuTop||[]).map((p: JsonData, i:number)=><div key={i} className="flex items-center gap-2 text-[11px] mb-1"><span className="w-10 text-right text-[var(--dg-text-muted)]">{i+1}</span><span className="w-32 truncate" title={p.pod}>{p.pod}</span><MiniBar val={Number(p.value||0)*100} label={`${Number(p.value||0).toFixed(2)}c`} color="bg-purple-500" /></div>)}</div>
<div className="rounded-lg bg-[var(--dg-bg-primary)] p-3 max-h-40 overflow-y-auto"><div className="text-xs font-medium mb-2">内存 Top 10</div>{(d.memTop||[]).map((p: JsonData, i:number)=><div key={i} className="flex items-center gap-2 text-[11px] mb-1"><span className="w-10 text-right text-[var(--dg-text-muted)]">{i+1}</span><span className="w-32 truncate" title={p.pod}>{p.pod}</span><span className="ml-auto">{fmtBytes(Number(p.value||0))}</span></div>)}</div> <div className="rounded-lg bg-[var(--dg-bg-primary)] p-3 max-h-40 overflow-y-auto"><div className="text-xs font-medium mb-2">{i18n.t('monitor.prometheusdashboard.sb0f653')}</div>{(d.memTop||[]).map((p: JsonData, i:number)=><div key={i} className="flex items-center gap-2 text-[11px] mb-1"><span className="w-10 text-right text-[var(--dg-text-muted)]">{i+1}</span><span className="w-32 truncate" title={p.pod}>{p.pod}</span><span className="ml-auto">{fmtBytes(Number(p.value||0))}</span></div>)}</div>
</div> </div>
); );
const JvmPanel: React.FC<{ d: JsonData}> = ({ d }) => { const JvmPanel: React.FC<{ d: JsonData}> = ({ d }) => {
const { t } = useTranslation();
const h = Number(d.heapUsed?.[0]?.value||0); const h = Number(d.heapUsed?.[0]?.value||0);
const uptime = Number(d.uptime?.[0]?.value||0); const uptime = Number(d.uptime?.[0]?.value||0);
return ( return (
@@ -123,6 +127,7 @@ const JvmPanel: React.FC<{ d: JsonData}> = ({ d }) => {
}; };
export const PrometheusDashboard: React.FC<Props> = ({ dsUrl }) => { export const PrometheusDashboard: React.FC<Props> = ({ dsUrl }) => {
const { t } = useTranslation();
const [connected, setConnected] = useState(false); const [connected, setConnected] = useState(false);
const [loading, setLoading] = useState(false); const [loading, setLoading] = useState(false);
const [targets, setTargets] = useState(0); const [targets, setTargets] = useState(0);
@@ -143,7 +148,7 @@ export const PrometheusDashboard: React.FC<Props> = ({ dsUrl }) => {
const data: JsonData = await prometheusProxyApi.connect(u); const data: JsonData = await prometheusProxyApi.connect(u);
setConnected(true); setTargets(data.targets||0); setConnected(true); setTargets(data.targets||0);
loadAll(u); loadAll(u);
} catch (e) { setConnected(false); setError((e as JsonData).message||'连接失败'); } } catch (e) { setConnected(false); setError((e as JsonData).message||t('aiops.llmTestFailed')); }
finally { setLoading(false); } finally { setLoading(false); }
}; };
@@ -169,13 +174,13 @@ export const PrometheusDashboard: React.FC<Props> = ({ dsUrl }) => {
<CardHeader className="py-3 px-4 pb-2"> <CardHeader className="py-3 px-4 pb-2">
<div className="flex items-center gap-2"> <div className="flex items-center gap-2">
<Activity className="h-4 w-4 dg-text-purple" /> <Activity className="h-4 w-4 dg-text-purple" />
<CardTitle className="text-sm font-medium">Prometheus 监控</CardTitle> <CardTitle className="text-sm font-medium">{t('monitor.prometheusdashboard.s006a5f')}</CardTitle>
{connected && <Badge className="text-[10px] bg-purple-500/10 dg-text-purple">{targets} targets</Badge>} {connected && <Badge className="text-[10px] bg-purple-500/10 dg-text-purple">{targets} targets</Badge>}
{connected && <div className="ml-auto"><Button variant="ghost" size="sm" className="h-6 px-2 text-[10px]" onClick={refresh}><RefreshCw className="w-3 h-3 mr-1" />刷新</Button></div>} {connected && <div className="ml-auto"><Button variant="ghost" size="sm" className="h-6 px-2 text-[10px]" onClick={refresh}><RefreshCw className="w-3 h-3 mr-1" />{t('common.refresh')}</Button></div>}
</div> </div>
</CardHeader> </CardHeader>
<CardContent className="px-4 pb-3 pt-0"> <CardContent className="px-4 pb-3 pt-0">
{loading ? (<div className="text-center py-12"><Loader2 className="h-6 w-6 mx-auto mb-2 animate-spin dg-text-purple" /><p className="text-xs text-[var(--dg-text-muted)]">连接中…</p></div>) {loading ? (<div className="text-center py-12"><Loader2 className="h-6 w-6 mx-auto mb-2 animate-spin dg-text-purple" /><p className="text-xs text-[var(--dg-text-muted)]">{t('monitor.prometheusdashboard.s5e8eb2')}</p></div>)
: error ? (<div className="p-3 rounded-lg bg-red-500/10 border border-red-500/20 text-xs dg-text-red"><AlertTriangle className="h-4 w-4 inline mr-1" />{error}</div>) : error ? (<div className="p-3 rounded-lg bg-red-500/10 border border-red-500/20 text-xs dg-text-red"><AlertTriangle className="h-4 w-4 inline mr-1" />{error}</div>)
: ( : (
<Tabs value={tab} onValueChange={setTab}> <Tabs value={tab} onValueChange={setTab}>
@@ -18,6 +18,7 @@ import { Badge } from '@/components/ui/badge';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card'; import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { zabbixProxyApi } from '@/api'; import { zabbixProxyApi } from '@/api';
import type { JsonData } from '@/types/common'; import type { JsonData } from '@/types/common';
import { useTranslation } from 'react-i18next';
interface ZabbixHost { interface ZabbixHost {
hostid: string; hostname: string; name: string; ip: string; available: string; hostid: string; hostname: string; name: string; ip: string; available: string;
@@ -31,6 +32,7 @@ type SortField = 'hostname' | 'cpu_usage' | 'memory_usage' | 'disk_usage' | 'loa
interface Props { dsUrl?: string; dsUsername?: string; dsPassword?: string; } interface Props { dsUrl?: string; dsUsername?: string; dsPassword?: string; }
export const ZabbixDashboard: React.FC<Props> = ({ dsUrl, dsUsername, dsPassword }) => { export const ZabbixDashboard: React.FC<Props> = ({ dsUrl, dsUsername, dsPassword }) => {
const { t } = useTranslation();
const [connected, setConnected] = useState(false); const [connected, setConnected] = useState(false);
const [loading, setLoading] = useState(false); const [loading, setLoading] = useState(false);
const [hosts, setHosts] = useState<ZabbixHost[]>([]); const [hosts, setHosts] = useState<ZabbixHost[]>([]);
@@ -50,7 +52,7 @@ export const ZabbixDashboard: React.FC<Props> = ({ dsUrl, dsUsername, dsPassword
setHosts(data.hosts || []); setHosts(data.hosts || []);
setVersion(data.version || ''); setVersion(data.version || '');
setConnected(true); setConnected(true);
} catch (e) { setConnected(false); setError((e as JsonData).message || '连接失败'); } } catch (e) { setConnected(false); setError((e as JsonData).message || t('aiops.llmTestFailed')); }
finally { setLoading(false); } finally { setLoading(false); }
}; };
@@ -94,24 +96,24 @@ export const ZabbixDashboard: React.FC<Props> = ({ dsUrl, dsUsername, dsPassword
<CardHeader className="py-3 px-4 pb-2"> <CardHeader className="py-3 px-4 pb-2">
<div className="flex items-center gap-2"> <div className="flex items-center gap-2">
<Activity className="h-4 w-4 dg-text-blue" /> <Activity className="h-4 w-4 dg-text-blue" />
<CardTitle className="text-sm font-medium">Zabbix 主机监控</CardTitle> <CardTitle className="text-sm font-medium">{t('monitor.zabbixdashboard.s6f2695')}</CardTitle>
{version && <Badge className="text-[10px] bg-blue-500/10 dg-text-blue">v{version}</Badge>} {version && <Badge className="text-[10px] bg-blue-500/10 dg-text-blue">v{version}</Badge>}
{connected && <span className="text-[10px] text-[var(--dg-text-muted)] ml-2">{hosts.length} 台</span>} {connected && <span className="text-[10px] text-[var(--dg-text-muted)] ml-2">{hosts.length} 台</span>}
{connected && <div className="ml-auto flex gap-1"><Button variant="ghost" size="sm" className="h-6 px-2 text-[10px]" onClick={refresh}><RefreshCw className="w-3 h-3 mr-1" />刷新</Button></div>} {connected && <div className="ml-auto flex gap-1"><Button variant="ghost" size="sm" className="h-6 px-2 text-[10px]" onClick={refresh}><RefreshCw className="w-3 h-3 mr-1" />{t('common.refresh')}</Button></div>}
</div> </div>
</CardHeader> </CardHeader>
<CardContent className="px-4 pb-3 pt-0"> <CardContent className="px-4 pb-3 pt-0">
{loading ? (<div className="text-center py-12"><Loader2 className="h-6 w-6 mx-auto mb-2 animate-spin dg-text-blue" /><p className="text-xs text-[var(--dg-text-muted)]">连接中…</p></div>) {loading ? (<div className="text-center py-12"><Loader2 className="h-6 w-6 mx-auto mb-2 animate-spin dg-text-blue" /><p className="text-xs text-[var(--dg-text-muted)]">{t('monitor.zabbixdashboard.s5e8eb2')}</p></div>)
: error ? (<div className="p-3 rounded-lg bg-red-500/10 border border-red-500/20 text-xs dg-text-red flex items-start gap-2"><AlertTriangle className="h-4 w-4 mt-0.5" /><span>{error}</span></div>) : error ? (<div className="p-3 rounded-lg bg-red-500/10 border border-red-500/20 text-xs dg-text-red flex items-start gap-2"><AlertTriangle className="h-4 w-4 mt-0.5" /><span>{error}</span></div>)
: hosts.length === 0 ? (<div className="text-center py-8 text-[var(--dg-text-muted)]"><Server className="h-8 w-8 mx-auto mb-2 dg-text-muted" /><p className="text-sm">未找到被监控的 Zabbix 主机</p></div>) : hosts.length === 0 ? (<div className="text-center py-8 text-[var(--dg-text-muted)]"><Server className="h-8 w-8 mx-auto mb-2 dg-text-muted" /><p className="text-sm">{t('monitor.zabbixdashboard.sdb131a')}</p></div>)
: ( : (
<div className="overflow-x-auto rounded-lg border border-[var(--dg-border)]"> <div className="overflow-x-auto rounded-lg border border-[var(--dg-border)]">
<table className="w-full text-xs"> <table className="w-full text-xs">
<thead className="bg-[var(--dg-bg-tertiary)] border-b border-[var(--dg-border)]"><tr> <thead className="bg-[var(--dg-bg-tertiary)] border-b border-[var(--dg-border)]"><tr>
{[ {[
{ f: 'hostname' as SortField, l: '主机名' },{ f: 'cpu_usage' as SortField, l: 'CPU' },{ f: 'memory_usage' as SortField, l: '内存' }, { f: 'hostname' as SortField, l: t('server.hostname') },{ f: 'cpu_usage' as SortField, l: 'CPU' },{ f: 'memory_usage' as SortField, l: t('k8s.pods.memory') },
{ f: 'disk_usage' as SortField, l: '磁盘' },{ f: 'load5' as SortField, l: 'Load5' },{ f: 'net_in_bps' as SortField, l: '流入' }, { f: 'disk_usage' as SortField, l: t('dashboard.topUsage.disk') },{ f: 'load5' as SortField, l: 'Load5' },{ f: 'net_in_bps' as SortField, l: t('monitor.zabbixdashboard.s361ffa') },
{ f: 'net_out_bps' as SortField, l: '流出' },{ f: 'problem_count' as SortField, l: '问题' },{ f: 'uptime_days' as SortField, l: '运行' }, { f: 'net_out_bps' as SortField, l: t('monitor.zabbixdashboard.s37cc0a') },{ f: 'problem_count' as SortField, l: t('monitor.zabbixdashboard.s5dc99f') },{ f: 'uptime_days' as SortField, l: t('common.run') },
].map(({ f, l }) => ( ].map(({ f, l }) => (
<th key={f} className="px-3 py-2 text-left font-medium text-[var(--dg-text-secondary)] cursor-pointer hover:text-[var(--dg-text-primary)] select-none whitespace-nowrap" onClick={() => toggleSort(f)}> <th key={f} className="px-3 py-2 text-left font-medium text-[var(--dg-text-secondary)] cursor-pointer hover:text-[var(--dg-text-primary)] select-none whitespace-nowrap" onClick={() => toggleSort(f)}>
<div className="flex items-center gap-1">{l}<SI f={f} /></div></th> <div className="flex items-center gap-1">{l}<SI f={f} /></div></th>
@@ -23,8 +23,10 @@ import PromDsFormDialog from './prometheus-ds/PromDsFormDialog';
import { PageLoading } from '@/components/layout/PageLoading'; import { PageLoading } from '@/components/layout/PageLoading';
import { PageEmpty } from '@/components/layout/PageEmpty'; import { PageEmpty } from '@/components/layout/PageEmpty';
import { ContentPanel } from '@/components/layout/ContentPanel'; import { ContentPanel } from '@/components/layout/ContentPanel';
import { useTranslation } from 'react-i18next';
export default function PrometheusDatasourceManager() { export default function PrometheusDatasourceManager() {
const { t } = useTranslation();
const _confirm = useConfirm(); const _confirm = useConfirm();
const { data: sources = [], isLoading, isError } = usePromDatasources(); const { data: sources = [], isLoading, isError } = usePromDatasources();
const { deleteMutation, setDefaultMutation } = usePromDatasourceMutations(); const { deleteMutation, setDefaultMutation } = usePromDatasourceMutations();
@@ -33,7 +35,7 @@ export default function PrometheusDatasourceManager() {
const [editingDs, setEditingDs] = useState<PromDS | null>(null); const [editingDs, setEditingDs] = useState<PromDS | null>(null);
useEffect(() => { useEffect(() => {
if (isError) toast.error('获取数据源列表失败'); if (isError) toast.error(t('monitor.prometheusdatasourcemanager.s45f817'));
}, [isError]); }, [isError]);
const openCreate = () => { const openCreate = () => {
@@ -48,25 +50,25 @@ export default function PrometheusDatasourceManager() {
const handleDelete = async (ds: PromDS) => { const handleDelete = async (ds: PromDS) => {
const ok = await _confirm({ const ok = await _confirm({
title: '删除数据源', title: t('monitor.deleteDatasource'),
description: `确定删除数据源「${ds.name}」吗?此操作不可撤销。`, description: t('monitor.prometheusdatasourcemanager.s623d90', { ds.name: ds.name }),
variant: 'destructive', variant: 'destructive',
}); });
if (!ok) return; if (!ok) return;
try { try {
await deleteMutation.mutateAsync(ds.id); await deleteMutation.mutateAsync(ds.id);
toast.success('已删除'); toast.success(t('alert.deleted'));
} catch { } catch {
toast.error('删除失败'); toast.error(t('common.deleteFailed'));
} }
}; };
const handleSetDefault = async (ds: PromDS) => { const handleSetDefault = async (ds: PromDS) => {
try { try {
await setDefaultMutation.mutateAsync(ds.id); await setDefaultMutation.mutateAsync(ds.id);
toast.success(`已将「${ds.name}」设为默认数据源`); toast.success(t('monitor.prometheusdatasourcemanager.sa8bcc7', { ds.name: ds.name }));
} catch { } catch {
toast.error('设置失败'); toast.error(t('monitor.prometheusdatasourcemanager.s9f9603'));
} }
}; };
@@ -94,8 +96,8 @@ export default function PrometheusDatasourceManager() {
{sources.length === 0 ? ( {sources.length === 0 ? (
<PageEmpty <PageEmpty
icon={<Database className="h-12 w-12" />} icon={<Database className="h-12 w-12" />}
title="暂无 Prometheus 数据源" title=t('monitor.prometheusdatasourcemanager.s99ed81')
description="添加数据源后可用于指标监控与监控大屏" description=t('monitor.prometheusdatasourcemanager.sd9a356')
action={( action={(
<Button onClick={openCreate} size="sm" className="dg-btn-primary"> <Button onClick={openCreate} size="sm" className="dg-btn-primary">
<Plus className="w-4 h-4 mr-1" />添加数据源 <Plus className="w-4 h-4 mr-1" />添加数据源
@@ -107,11 +109,11 @@ export default function PrometheusDatasourceManager() {
<table className="w-full"> <table className="w-full">
<thead className="border-b border-[var(--border-default)]"> <thead className="border-b border-[var(--border-default)]">
<tr className="text-xs dg-text-secondary"> <tr className="text-xs dg-text-secondary">
<th className="text-left py-3 px-4 font-medium">名称</th> <th className="text-left py-3 px-4 font-medium">{t('common.name')}</th>
<th className="text-left py-3 px-4 font-medium">URL</th> <th className="text-left py-3 px-4 font-medium">URL</th>
<th className="text-left py-3 px-4 font-medium w-20">默认</th> <th className="text-left py-3 px-4 font-medium w-20">{t('approval.status.default')}</th>
<th className="text-left py-3 px-4 font-medium w-16">状态</th> <th className="text-left py-3 px-4 font-medium w-16">{t('common.status')}</th>
<th className="text-right py-3 px-4 font-medium w-36">操作</th> <th className="text-right py-3 px-4 font-medium w-36">{t('common.actions')}</th>
</tr> </tr>
</thead> </thead>
<tbody> <tbody>
@@ -142,16 +144,16 @@ export default function PrometheusDatasourceManager() {
</td> </td>
<td className="py-3 px-4"> <td className="py-3 px-4">
{ds.is_default ? ( {ds.is_default ? (
<span className="dg-badge-yellow"><Star className="w-3 h-3 mr-1 inline" />默认</span> <span className="dg-badge-yellow"><Star className="w-3 h-3 mr-1 inline" />{t('approval.status.default')}</span>
) : ( ) : (
<span className="text-xs dg-text-muted">--</span> <span className="text-xs dg-text-muted">--</span>
)} )}
</td> </td>
<td className="py-3 px-4"> <td className="py-3 px-4">
{ds.status === 1 ? ( {ds.status === 1 ? (
<span className="dg-status-running">启用</span> <span className="dg-status-running">{t('common.enable')}</span>
) : ( ) : (
<span className="dg-badge-muted">禁用</span> <span className="dg-badge-muted">{t('common.disable')}</span>
)} )}
</td> </td>
<td className="py-3 px-4"> <td className="py-3 px-4">
@@ -160,7 +162,7 @@ export default function PrometheusDatasourceManager() {
variant="ghost" size="sm" variant="ghost" size="sm"
className="h-8 px-2" className="h-8 px-2"
onClick={() => handleTestQuick(ds)} onClick={() => handleTestQuick(ds)}
title="测试连接" title=t('aiops.llmTest')
> >
<Plug className="w-3.5 h-3.5" /> <Plug className="w-3.5 h-3.5" />
</Button> </Button>
@@ -169,7 +171,7 @@ export default function PrometheusDatasourceManager() {
variant="ghost" size="sm" variant="ghost" size="sm"
className="h-8 px-2 dg-text-yellow" className="h-8 px-2 dg-text-yellow"
onClick={() => handleSetDefault(ds)} onClick={() => handleSetDefault(ds)}
title="设为默认" title=t('aiops.llmSetDefault')
> >
<Star className="w-3.5 h-3.5" /> <Star className="w-3.5 h-3.5" />
</Button> </Button>
@@ -32,6 +32,7 @@ import { toast } from 'sonner';
import { useConfirm } from '@/components/ui/confirm-dialog'; import { useConfirm } from '@/components/ui/confirm-dialog';
import { zabbixDatasourceApi } from '@/api'; import { zabbixDatasourceApi } from '@/api';
import type { JsonData } from '@/types/common'; import type { JsonData } from '@/types/common';
import { useTranslation } from 'react-i18next';
interface ZabbixDS { interface ZabbixDS {
id: number; id: number;
@@ -59,6 +60,7 @@ const defaultForm = {
}; };
export default function ZabbixDatasourceManager() { export default function ZabbixDatasourceManager() {
const { t } = useTranslation();
const _confirm = useConfirm(); const _confirm = useConfirm();
const [sources, setSources] = useState<ZabbixDS[]>([]); const [sources, setSources] = useState<ZabbixDS[]>([]);
const [loading, setLoading] = useState(true); const [loading, setLoading] = useState(true);
@@ -78,7 +80,7 @@ export default function ZabbixDatasourceManager() {
const res: JsonData = await zabbixDatasourceApi.list(); const res: JsonData = await zabbixDatasourceApi.list();
setSources(res?.data || res || []); setSources(res?.data || res || []);
} catch { } catch {
toast.error('获取数据源列表失败'); toast.error(t('monitor.zabbixdatasourcemanager.s45f817'));
} finally { } finally {
setLoading(false); setLoading(false);
} }
@@ -115,51 +117,51 @@ export default function ZabbixDatasourceManager() {
}; };
const handleSave = async () => { const handleSave = async () => {
if (!form.name.trim()) { toast.error('请输入数据源名称'); return; } if (!form.name.trim()) { toast.error(t('monitor.zabbixdatasourcemanager.s138957')); return; }
if (!form.url.trim()) { toast.error('请输入 Zabbix API URL'); return; } if (!form.url.trim()) { toast.error(t('monitor.zabbixdatasourcemanager.s2ba385')); return; }
if (!form.username.trim()) { toast.error('请输入用户名'); return; } if (!form.username.trim()) { toast.error(t('login.usernameRequired')); return; }
if (!form.password.trim()) { toast.error('请输入密码'); return; } if (!form.password.trim()) { toast.error(t('login.passwordRequired')); return; }
try { try {
if (editingId) { if (editingId) {
await zabbixDatasourceApi.update(editingId, form); await zabbixDatasourceApi.update(editingId, form);
toast.success('数据源已更新'); toast.success(t('monitor.zabbixdatasourcemanager.s8dfdd2'));
} else { } else {
await zabbixDatasourceApi.create(form); await zabbixDatasourceApi.create(form);
toast.success('数据源已创建'); toast.success(t('monitor.zabbixdatasourcemanager.sa6def0'));
} }
setDialogOpen(false); setDialogOpen(false);
fetchList(); fetchList();
} catch (err) { } catch (err) {
toast.error(err?.message || '操作失败'); toast.error(err?.message || t('common.operationFailed'));
} }
}; };
const handleDelete = async (ds: ZabbixDS) => { const handleDelete = async (ds: ZabbixDS) => {
const ok = await _confirm({ const ok = await _confirm({
title: '删除数据源', title: t('monitor.deleteDatasource'),
description: `确定删除「${ds.name}」?`, description: t('monitor.zabbixdatasourcemanager.sa2b79a', { ds.name: ds.name }),
variant: 'destructive', variant: 'destructive',
}); });
if (!ok) return; if (!ok) return;
try { try {
await zabbixDatasourceApi.delete(ds.id); await zabbixDatasourceApi.delete(ds.id);
toast.success('已删除'); toast.success(t('alert.deleted'));
fetchList(); fetchList();
} catch { toast.error('删除失败'); } } catch { toast.error(t('common.deleteFailed')); }
}; };
const handleSetDefault = async (ds: ZabbixDS) => { const handleSetDefault = async (ds: ZabbixDS) => {
try { try {
await zabbixDatasourceApi.setDefault(ds.id); await zabbixDatasourceApi.setDefault(ds.id);
toast.success(`已将「${ds.name}」设为默认`); toast.success(t('monitor.zabbixdatasourcemanager.sf0f959', { ds.name: ds.name }));
fetchList(); fetchList();
} catch { toast.error('设置失败'); } } catch { toast.error(t('monitor.zabbixdatasourcemanager.s9f9603')); }
}; };
const handleTest = async () => { const handleTest = async () => {
if (!form.url.trim() || !form.username.trim()) { if (!form.url.trim() || !form.username.trim()) {
toast.error('请填写 URL 和用户名'); toast.error(t('monitor.zabbixdatasourcemanager.s1d3562'));
return; return;
} }
setTesting(true); setTesting(true);
@@ -173,7 +175,7 @@ export default function ZabbixDatasourceManager() {
const data = res?.data || res; const data = res?.data || res;
setTestResult(data); setTestResult(data);
} catch (err) { } catch (err) {
setTestResult({ success: false, message: err?.message || '测试失败' }); setTestResult({ success: false, message: err?.message || t('monitor.zabbixdatasourcemanager.s9710d9') });
} finally { } finally {
setTesting(false); setTesting(false);
} }
@@ -199,7 +201,7 @@ export default function ZabbixDatasourceManager() {
/> />
Zabbix 数据源 Zabbix 数据源
</h2> </h2>
<p className="text-xs text-[var(--dg-text-muted)]">配置 Zabbix API 连接,获取主机监控数据</p> <p className="text-xs text-[var(--dg-text-muted)]">{t('monitor.zabbixdatasourcemanager.s79e929')}</p>
</div> </div>
<Button onClick={openCreate} size="sm"> <Button onClick={openCreate} size="sm">
<Plus className="w-4 h-4 mr-1" />添加 <Plus className="w-4 h-4 mr-1" />添加
@@ -210,7 +212,7 @@ export default function ZabbixDatasourceManager() {
<Card className="bg-[var(--dg-bg-secondary)] border-[var(--dg-border)]"> <Card className="bg-[var(--dg-bg-secondary)] border-[var(--dg-border)]">
<CardContent className="py-12 text-center text-[var(--dg-text-muted)]"> <CardContent className="py-12 text-center text-[var(--dg-text-muted)]">
<Database className="w-12 h-12 mx-auto mb-3 opacity-30" /> <Database className="w-12 h-12 mx-auto mb-3 opacity-30" />
<p className="text-sm">暂无 Zabbix 数据源</p> <p className="text-sm">{t('monitor.zabbixdatasourcemanager.sc9c9bd')}</p>
<Button size="sm" className="mt-4" onClick={openCreate}> <Button size="sm" className="mt-4" onClick={openCreate}>
<Plus className="w-4 h-4 mr-1" />添加数据源 <Plus className="w-4 h-4 mr-1" />添加数据源
</Button> </Button>
@@ -226,15 +228,15 @@ export default function ZabbixDatasourceManager() {
<div className="flex items-center gap-2 mb-1"> <div className="flex items-center gap-2 mb-1">
<div className={`w-2 h-2 rounded-full ${ds.status === 1 ? 'bg-emerald-400' : 'bg-[var(--dg-bg-active)]'}`} /> <div className={`w-2 h-2 rounded-full ${ds.status === 1 ? 'bg-emerald-400' : 'bg-[var(--dg-bg-active)]'}`} />
<span className="font-medium text-[var(--dg-text-primary)]">{ds.name}</span> <span className="font-medium text-[var(--dg-text-primary)]">{ds.name}</span>
{ds.is_default && <Badge className="bg-amber-500/20 dg-text-yellow text-[10px]"><Star className="w-3 h-3 mr-0.5" />默认</Badge>} {ds.is_default && <Badge className="bg-amber-500/20 dg-text-yellow text-[10px]"><Star className="w-3 h-3 mr-0.5" />{t('approval.status.default')}</Badge>}
{ds.status === 1 {ds.status === 1
? <Badge className="bg-emerald-500/20 dg-text-green text-[10px]">启用</Badge> ? <Badge className="bg-emerald-500/20 dg-text-green text-[10px]">{t('common.enable')}</Badge>
: <Badge className="bg-[var(--dg-bg-active)]/20 dg-text-secondary text-[10px]">禁用</Badge>} : <Badge className="bg-[var(--dg-bg-active)]/20 dg-text-secondary text-[10px]">{t('common.disable')}</Badge>}
</div> </div>
<div className="text-xs text-[var(--dg-text-muted)] space-x-3"> <div className="text-xs text-[var(--dg-text-muted)] space-x-3">
<code className="text-orange-300">{ds.url}</code> <code className="text-orange-300">{ds.url}</code>
<span>用户: {ds.username}</span> <span>用户: {ds.username}</span>
{ds.direct_db && <Badge variant="outline" className="text-[10px]">直连DB</Badge>} {ds.direct_db && <Badge variant="outline" className="text-[10px]">{t('monitor.zabbixdatasourcemanager.s85260a')}</Badge>}
</div> </div>
</div> </div>
<div className="flex items-center gap-1"> <div className="flex items-center gap-1">
@@ -263,7 +265,7 @@ export default function ZabbixDatasourceManager() {
<DialogHeader> <DialogHeader>
<DialogTitle className="text-[var(--dg-text-primary)] flex items-center gap-2"> <DialogTitle className="text-[var(--dg-text-primary)] flex items-center gap-2">
<Database className="h-5 w-5 dg-text-orange" /> <Database className="h-5 w-5 dg-text-orange" />
{editingId ? '编辑 Zabbix 数据源' : '新建 Zabbix 数据源'} {editingId ? t('monitor.zabbixdatasourcemanager.sc1c87e') : t('monitor.zabbixdatasourcemanager.sa77d38')}
</DialogTitle> </DialogTitle>
<DialogDescription> <DialogDescription>
配置 Zabbix API 连接,用于主机监控与告警数据获取 配置 Zabbix API 连接,用于主机监控与告警数据获取
@@ -274,14 +276,14 @@ export default function ZabbixDatasourceManager() {
{/* Name + Default */} {/* Name + Default */}
<div className="grid grid-cols-2 gap-3"> <div className="grid grid-cols-2 gap-3">
<div> <div>
<Label className="text-xs text-[var(--dg-text-secondary)]">名称 *</Label> <Label className="text-xs text-[var(--dg-text-secondary)]">{t('deploy.form.nameStar')}</Label>
<Input className="mt-1 h-9 text-sm bg-[var(--dg-bg-primary)]" placeholder="如:生产 Zabbix" <Input className="mt-1 h-9 text-sm bg-[var(--dg-bg-primary)]" placeholder=t('monitor.zabbixdatasourcemanager.s9f1e6a')
value={form.name} onChange={e => updateForm('name', e.target.value)} /> value={form.name} onChange={e => updateForm('name', e.target.value)} />
</div> </div>
<div className="flex items-end pb-1"> <div className="flex items-end pb-1">
<div className="flex items-center gap-2"> <div className="flex items-center gap-2">
<Switch checked={form.is_default} onCheckedChange={v => updateForm('is_default', v)} /> <Switch checked={form.is_default} onCheckedChange={v => updateForm('is_default', v)} />
<Label className="text-xs cursor-pointer">设为默认</Label> <Label className="text-xs cursor-pointer">{t('aiops.llmSetDefault')}</Label>
</div> </div>
</div> </div>
</div> </div>
@@ -305,15 +307,15 @@ export default function ZabbixDatasourceManager() {
onClick={() => setShowAuth(!showAuth)}> onClick={() => setShowAuth(!showAuth)}>
<div className="flex items-center gap-2"> <div className="flex items-center gap-2">
<Shield className="w-4 h-4" /> <Shield className="w-4 h-4" />
<span>Zabbix API 认证</span> <span>{t('monitor.zabbixdatasourcemanager.sb47858')}</span>
</div> </div>
{showAuth ? <ChevronUp className="w-4 h-4" /> : <ChevronDown className="w-4 h-4" />} {showAuth ? <ChevronUp className="w-4 h-4" /> : <ChevronDown className="w-4 h-4" />}
</button> </button>
{showAuth && ( {showAuth && (
<div className="px-3 pb-3 space-y-3"> <div className="px-3 pb-3 space-y-3">
<Input className="h-9 text-sm bg-[var(--dg-bg-primary)]" placeholder="用户名 *" <Input className="h-9 text-sm bg-[var(--dg-bg-primary)]" placeholder=t('monitor.zabbixdatasourcemanager.s04c3dd')
value={form.username} onChange={e => updateForm('username', e.target.value)} /> value={form.username} onChange={e => updateForm('username', e.target.value)} />
<Input className="h-9 text-sm bg-[var(--dg-bg-primary)]" type="password" placeholder="密码 *" <Input className="h-9 text-sm bg-[var(--dg-bg-primary)]" type="password" placeholder=t('monitor.zabbixdatasourcemanager.s3140c0')
value={form.password} onChange={e => updateForm('password', e.target.value)} /> value={form.password} onChange={e => updateForm('password', e.target.value)} />
</div> </div>
)} )}
@@ -325,7 +327,7 @@ export default function ZabbixDatasourceManager() {
onClick={() => setShowTrends(!showTrends)}> onClick={() => setShowTrends(!showTrends)}>
<div className="flex items-center gap-2"> <div className="flex items-center gap-2">
<Clock className="w-4 h-4" /> <Clock className="w-4 h-4" />
<span>Trends 设置</span> <span>{t('monitor.zabbixdatasourcemanager.s05ef18')}</span>
</div> </div>
{showTrends ? <ChevronUp className="w-4 h-4" /> : <ChevronDown className="w-4 h-4" />} {showTrends ? <ChevronUp className="w-4 h-4" /> : <ChevronDown className="w-4 h-4" />}
</button> </button>
@@ -333,24 +335,24 @@ export default function ZabbixDatasourceManager() {
<div className="px-3 pb-3 space-y-3"> <div className="px-3 pb-3 space-y-3">
<div className="grid grid-cols-2 gap-3"> <div className="grid grid-cols-2 gap-3">
<div> <div>
<Label className="text-xs text-[var(--dg-text-secondary)]">After (天)</Label> <Label className="text-xs text-[var(--dg-text-secondary)]">{t('monitor.zabbixdatasourcemanager.sebfa4e')}</Label>
<Input className="mt-1 h-9 text-sm bg-[var(--dg-bg-primary)]" type="number" min={0} <Input className="mt-1 h-9 text-sm bg-[var(--dg-bg-primary)]" type="number" min={0}
value={form.trends_after} onChange={e => updateForm('trends_after', parseInt(e.target.value) || 0)} /> value={form.trends_after} onChange={e => updateForm('trends_after', parseInt(e.target.value) || 0)} />
</div> </div>
<div> <div>
<Label className="text-xs text-[var(--dg-text-secondary)]">Range (秒)</Label> <Label className="text-xs text-[var(--dg-text-secondary)]">{t('monitor.zabbixdatasourcemanager.s7fe44f')}</Label>
<Input className="mt-1 h-9 text-sm bg-[var(--dg-bg-primary)]" type="number" min={0} <Input className="mt-1 h-9 text-sm bg-[var(--dg-bg-primary)]" type="number" min={0}
value={form.trends_range} onChange={e => updateForm('trends_range', parseInt(e.target.value) || 0)} /> value={form.trends_range} onChange={e => updateForm('trends_range', parseInt(e.target.value) || 0)} />
</div> </div>
</div> </div>
<div className="grid grid-cols-2 gap-3"> <div className="grid grid-cols-2 gap-3">
<div> <div>
<Label className="text-xs text-[var(--dg-text-secondary)]">Cache TTL (秒)</Label> <Label className="text-xs text-[var(--dg-text-secondary)]">{t('monitor.zabbixdatasourcemanager.sbf9a86')}</Label>
<Input className="mt-1 h-9 text-sm bg-[var(--dg-bg-primary)]" type="number" min={0} <Input className="mt-1 h-9 text-sm bg-[var(--dg-bg-primary)]" type="number" min={0}
value={form.trends_cache_ttl} onChange={e => updateForm('trends_cache_ttl', parseInt(e.target.value) || 3600)} /> value={form.trends_cache_ttl} onChange={e => updateForm('trends_cache_ttl', parseInt(e.target.value) || 3600)} />
</div> </div>
<div> <div>
<Label className="text-xs text-[var(--dg-text-secondary)]">Timeout (秒)</Label> <Label className="text-xs text-[var(--dg-text-secondary)]">{t('monitor.zabbixdatasourcemanager.s21f982')}</Label>
<Input className="mt-1 h-9 text-sm bg-[var(--dg-bg-primary)]" type="number" min={1} <Input className="mt-1 h-9 text-sm bg-[var(--dg-bg-primary)]" type="number" min={1}
value={form.trends_timeout} onChange={e => updateForm('trends_timeout', parseInt(e.target.value) || 30)} /> value={form.trends_timeout} onChange={e => updateForm('trends_timeout', parseInt(e.target.value) || 30)} />
</div> </div>
@@ -365,7 +367,7 @@ export default function ZabbixDatasourceManager() {
onClick={() => setShowOther(!showOther)}> onClick={() => setShowOther(!showOther)}>
<div className="flex items-center gap-2"> <div className="flex items-center gap-2">
<Settings className="w-4 h-4" /> <Settings className="w-4 h-4" />
<span>其他设置</span> <span>{t('monitor.zabbixdatasourcemanager.sdda36e')}</span>
</div> </div>
{showOther ? <ChevronUp className="w-4 h-4" /> : <ChevronDown className="w-4 h-4" />} {showOther ? <ChevronUp className="w-4 h-4" /> : <ChevronDown className="w-4 h-4" />}
</button> </button>
@@ -376,11 +378,11 @@ export default function ZabbixDatasourceManager() {
<Switch checked={form.direct_db} onCheckedChange={v => updateForm('direct_db', v)} /> <Switch checked={form.direct_db} onCheckedChange={v => updateForm('direct_db', v)} />
</div> </div>
<div className="flex items-center justify-between"> <div className="flex items-center justify-between">
<Label className="text-xs">只读用户禁用确认</Label> <Label className="text-xs">{t('monitor.zabbixdatasourcemanager.s413ec7')}</Label>
<Switch checked={form.disable_acknowledges} onCheckedChange={v => updateForm('disable_acknowledges', v)} /> <Switch checked={form.disable_acknowledges} onCheckedChange={v => updateForm('disable_acknowledges', v)} />
</div> </div>
<div className="flex items-center justify-between"> <div className="flex items-center justify-between">
<Label className="text-xs">禁用数据对齐</Label> <Label className="text-xs">{t('monitor.zabbixdatasourcemanager.s6d4d6f')}</Label>
<Switch checked={form.disable_data_alignment} onCheckedChange={v => updateForm('disable_data_alignment', v)} /> <Switch checked={form.disable_data_alignment} onCheckedChange={v => updateForm('disable_data_alignment', v)} />
</div> </div>
</div> </div>
@@ -404,8 +406,8 @@ export default function ZabbixDatasourceManager() {
测试连接 测试连接
</Button> </Button>
<div className="flex-1" /> <div className="flex-1" />
<Button variant="ghost" size="sm" onClick={() => setDialogOpen(false)}>取消</Button> <Button variant="ghost" size="sm" onClick={() => setDialogOpen(false)}>{t('common.cancel')}</Button>
<Button size="sm" onClick={handleSave}>保存</Button> <Button size="sm" onClick={handleSave}>{t('common.save')}</Button>
</DialogFooter> </DialogFooter>
</DialogContent> </DialogContent>
</Dialog> </Dialog>
@@ -36,6 +36,7 @@ import { usePromDatasourceMutations } from '@/hooks/api';
import type { PromDS, HeaderEntry, PromDsForm } from './types'; import type { PromDS, HeaderEntry, PromDsForm } from './types';
import { defaultForm } from './types'; import { defaultForm } from './types';
import { dsToForm, parseHeaders, buildPayload, testPromConnection, type TestConnectionResult } from './helpers'; import { dsToForm, parseHeaders, buildPayload, testPromConnection, type TestConnectionResult } from './helpers';
import { useTranslation } from 'react-i18next';
interface PromDsFormDialogProps { interface PromDsFormDialogProps {
open: boolean; open: boolean;
@@ -50,6 +51,7 @@ export default function PromDsFormDialog({
editingDs, editingDs,
sources, sources,
}: PromDsFormDialogProps) { }: PromDsFormDialogProps) {
const { t } = useTranslation();
const { createMutation, updateMutation } = usePromDatasourceMutations(); const { createMutation, updateMutation } = usePromDatasourceMutations();
const editingId = editingDs?.id ?? null; const editingId = editingDs?.id ?? null;
@@ -100,28 +102,28 @@ export default function PromDsFormDialog({
}; };
const handleSave = async () => { const handleSave = async () => {
if (!form.name.trim()) { toast.error('请输入数据源名称'); return; } if (!form.name.trim()) { toast.error(t('monitor.promdsformdialog.s138957')); return; }
if (!form.url.trim()) { toast.error('请输入 Prometheus URL'); return; } if (!form.url.trim()) { toast.error(t('monitor.promdsformdialog.sdc869f')); return; }
const payload = buildPayload(form, headers); const payload = buildPayload(form, headers);
try { try {
if (editingId) { if (editingId) {
await updateMutation.mutateAsync({ id: editingId, data: payload }); await updateMutation.mutateAsync({ id: editingId, data: payload });
toast.success('数据源更新成功'); toast.success(t('monitor.promdsformdialog.sc0c477'));
} else { } else {
await createMutation.mutateAsync(payload); await createMutation.mutateAsync(payload);
toast.success('数据源创建成功'); toast.success(t('monitor.promdsformdialog.s8b45c1'));
} }
onOpenChange(false); onOpenChange(false);
} catch (err: unknown) { } catch (err: unknown) {
const message = err instanceof Error ? err.message : '操作失败'; const message = err instanceof Error ? err.message : t('common.operationFailed');
toast.error(message); toast.error(message);
} }
}; };
const handleTestConnection = async () => { const handleTestConnection = async () => {
if (!form.url.trim()) { toast.error('请先输入 URL'); return; } if (!form.url.trim()) { toast.error(t('monitor.promdsformdialog.sc289ae')); return; }
setTesting(true); setTesting(true);
setTestResult(null); setTestResult(null);
try { try {
@@ -134,7 +136,7 @@ export default function PromDsFormDialog({
}); });
setTestResult(data); setTestResult(data);
} catch (err: unknown) { } catch (err: unknown) {
const message = err instanceof Error ? err.message : '测试失败'; const message = err instanceof Error ? err.message : t('monitor.promdsformdialog.s9710d9');
setTestResult({ success: false, message }); setTestResult({ success: false, message });
} finally { } finally {
setTesting(false); setTesting(false);
@@ -149,7 +151,7 @@ export default function PromDsFormDialog({
<DialogHeader> <DialogHeader>
<DialogTitle className="flex items-center gap-2 text-lg"> <DialogTitle className="flex items-center gap-2 text-lg">
<Database className="w-5 h-5 dg-text-orange" /> <Database className="w-5 h-5 dg-text-orange" />
{editingId ? '编辑数据源' : '添加数据源'} {editingId ? t('monitor.editDatasource') : t('monitor.addDatasource')}
</DialogTitle> </DialogTitle>
<DialogDescription> <DialogDescription>
Prometheus 数据源配置 · 参考 Grafana 数据源管理 Prometheus 数据源配置 · 参考 Grafana 数据源管理
@@ -163,7 +165,7 @@ export default function PromDsFormDialog({
<Label htmlFor="ds-name" className="text-sm">Name <span className="dg-text-red">*</span></Label> <Label htmlFor="ds-name" className="text-sm">Name <span className="dg-text-red">*</span></Label>
<Input <Input
id="ds-name" id="ds-name"
placeholder="Prometheus 数据源名称" placeholder=t('monitor.promdsformdialog.s9a9542')
value={form.name} value={form.name}
onChange={e => updateForm('name', e.target.value)} onChange={e => updateForm('name', e.target.value)}
className="bg-[var(--dg-bg-tertiary)] border-[var(--dg-border)]" className="bg-[var(--dg-bg-tertiary)] border-[var(--dg-border)]"
@@ -238,14 +240,14 @@ export default function PromDsFormDialog({
{form.basic_auth && ( {form.basic_auth && (
<div className="grid grid-cols-2 gap-3 ml-9"> <div className="grid grid-cols-2 gap-3 ml-9">
<Input <Input
placeholder="用户名" placeholder=t('login.username')
value={form.basic_auth_user} value={form.basic_auth_user}
onChange={e => updateForm('basic_auth_user', e.target.value)} onChange={e => updateForm('basic_auth_user', e.target.value)}
className="bg-[var(--dg-bg-tertiary)] border-[var(--dg-border)] text-sm" className="bg-[var(--dg-bg-tertiary)] border-[var(--dg-border)] text-sm"
/> />
<Input <Input
type="password" type="password"
placeholder="密码" placeholder=t('login.password')
value={form.basic_auth_pass} value={form.basic_auth_pass}
onChange={e => updateForm('basic_auth_pass', e.target.value)} onChange={e => updateForm('basic_auth_pass', e.target.value)}
className="bg-[var(--dg-bg-tertiary)] border-[var(--dg-border)] text-sm" className="bg-[var(--dg-bg-tertiary)] border-[var(--dg-border)] text-sm"
@@ -284,7 +286,7 @@ export default function PromDsFormDialog({
</div> </div>
{form.with_ca_cert && ( {form.with_ca_cert && (
<textarea <textarea
placeholder="PEM 格式的 CA 证书内容..." placeholder=t('monitor.promdsformdialog.sf66241')
value={form.ca_cert} value={form.ca_cert}
onChange={e => updateForm('ca_cert', e.target.value)} onChange={e => updateForm('ca_cert', e.target.value)}
rows={4} rows={4}
@@ -322,7 +324,7 @@ export default function PromDsFormDialog({
</Button> </Button>
</div> </div>
{headers.length === 0 ? ( {headers.length === 0 ? (
<p className="text-xs text-[var(--dg-text-secondary)] italic">暂无自定义 Header</p> <p className="text-xs text-[var(--dg-text-secondary)] italic">{t('monitor.promdsformdialog.s3c75b9')}</p>
) : ( ) : (
<div className="space-y-2"> <div className="space-y-2">
{headers.map((h, idx) => ( {headers.map((h, idx) => (
@@ -382,7 +384,7 @@ export default function PromDsFormDialog({
<SelectValue placeholder="Choose" /> <SelectValue placeholder="Choose" />
</SelectTrigger> </SelectTrigger>
<SelectContent> <SelectContent>
<SelectItem value="__none">无</SelectItem> <SelectItem value="__none">{t('common.none')}</SelectItem>
{sources.filter(s => s.id !== editingId).map(s => ( {sources.filter(s => s.id !== editingId).map(s => (
<SelectItem key={s.id} value={String(s.id)}>{s.name}</SelectItem> <SelectItem key={s.id} value={String(s.id)}>{s.name}</SelectItem>
))} ))}
@@ -407,7 +409,7 @@ export default function PromDsFormDialog({
onChange={e => updateForm('scrape_interval', Number(e.target.value))} onChange={e => updateForm('scrape_interval', Number(e.target.value))}
className="w-20 bg-[var(--dg-bg-tertiary)] border-[var(--dg-border)] text-sm text-center" className="w-20 bg-[var(--dg-bg-tertiary)] border-[var(--dg-border)] text-sm text-center"
/> />
<span className="text-xs text-[var(--dg-text-secondary)]">秒</span> <span className="text-xs text-[var(--dg-text-secondary)]">{t('common.second')}</span>
</div> </div>
</div> </div>
<div className="space-y-2"> <div className="space-y-2">
@@ -422,7 +424,7 @@ export default function PromDsFormDialog({
onChange={e => updateForm('query_timeout', Number(e.target.value))} onChange={e => updateForm('query_timeout', Number(e.target.value))}
className="w-20 bg-[var(--dg-bg-tertiary)] border-[var(--dg-border)] text-sm text-center" className="w-20 bg-[var(--dg-bg-tertiary)] border-[var(--dg-border)] text-sm text-center"
/> />
<span className="text-xs text-[var(--dg-text-secondary)]">秒</span> <span className="text-xs text-[var(--dg-text-secondary)]">{t('common.second')}</span>
</div> </div>
</div> </div>
</div> </div>
@@ -468,7 +470,7 @@ export default function PromDsFormDialog({
<div className="space-y-2"> <div className="space-y-2">
<Label className="text-sm text-[var(--dg-text-secondary)]">Custom query parameters</Label> <Label className="text-sm text-[var(--dg-text-secondary)]">Custom query parameters</Label>
<Input <Input
placeholder='例: {"timeout": "30s"}' placeholder=t('monitor.promdsformdialog.s5617a6')
value={form.custom_query_params} value={form.custom_query_params}
onChange={e => updateForm('custom_query_params', e.target.value)} onChange={e => updateForm('custom_query_params', e.target.value)}
className="bg-[var(--dg-bg-tertiary)] border-[var(--dg-border)] text-sm font-mono" className="bg-[var(--dg-bg-tertiary)] border-[var(--dg-border)] text-sm font-mono"
@@ -518,7 +520,7 @@ export default function PromDsFormDialog({
取消 取消
</Button> </Button>
<Button onClick={handleSave} disabled={saving}> <Button onClick={handleSave} disabled={saving}>
{editingId ? '更新' : '保存'} {editingId ? t('common.update') : t('common.save')}
</Button> </Button>
</DialogFooter> </DialogFooter>
</DialogContent> </DialogContent>
Loaded 100 of 166 files, more files were not shown because too many files have changed in this diff. Show more