feat: 完善堡垒机与 Agent 智能运维能力

- 支持 Windows Agent 构建、安装脚本和统一上报协议

- 增强 RDP 剪贴板、虚拟盘和文件传输能力

- 新增 AIOps 上下文工具、告警 RCA trace 落库和回放接口

- 重构 docs 模块文档并补充终端、堡垒机、监控、AI Agent 设计
This commit is contained in:
Logan.Li committed 2026-07-05 23:49:36 +08:00
1 parent a9513c2056
commit e0d652d211
169 files changed
+12192 -9116

No files matched your search

@@ -16,7 +16,7 @@ import {
} from '@/components/ui/dialog';
import { Plus, Trash2, Loader2 } from 'lucide-react';
import { alertApi } from '@/api';
import { CHANNEL_TYPES, getChannelTypeLabel } from './alertShared';
import { getChannelTypes, getChannelTypeLabel } from './alertShared';
import type { AlertChannel } from '@/types';
import i18n from '@/i18n';
@@ -225,7 +225,7 @@ export function AlertChannelDialog({
onChange={(e) => setChannelForm({ ...channelForm, type: 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"
>
{CHANNEL_TYPES.map(({ key, label }) => (
{getChannelTypes().map(({ key, label }) => (
<option key={key} value={key}>{label}</option>
))}
</select>
@@ -235,7 +235,7 @@ export function AlertChannelDialog({
<Textarea
value={channelForm.config}
onChange={(e) => setChannelForm({ ...channelForm, config: e.target.value })}
placeholder={CHANNEL_TYPES.find((t) => t.key === channelForm.type)?.placeholder || ''}
placeholder={getChannelTypes().find((t) => t.key === channelForm.type)?.placeholder || ''}
rows={5}
className="dg-input font-mono text-xs resize-none"
/>
+26 -18
View File
@@ -1,4 +1,5 @@
import { Mail, Phone, MessageSquare, Bell } from 'lucide-react';
import i18n from '@/i18n';
import type { AlertChannel, AlertRuleRecord } from '@/types';
// 将 notify_channels (可能是数组/JSON字符串/逗号分隔) 解析为数组
@@ -20,40 +21,47 @@ export function parseChannels( notifyChannels: unknown): string[] {
// 已知的渠道类型(用于旧数据兼容 — 旧规则存储类型字符串而非渠道 ID)
export const KNOWN_CHANNEL_TYPES = ['email', 'sms', 'dingtalk', 'wechat', 'webhook'];
// 根据渠道类型获取图标组件名(用字符串映射,组件内用 getChannelIcon 返回实际组件)
export const CHANNEL_TYPE_LABELS: Record<string, string> = {
dingtalk: '钉钉',
wechat: '企业微信',
email: '邮件',
sms: '短信',
webhook: 'Webhook',
// 渠道类型标签 key(运行时通过 i18n.t 解析,适配语言切换) // Logan.Li
export const CHANNEL_TYPE_LABEL_KEYS: Record<string, string> = {
dingtalk: 'monitor.channel.dingtalk',
wechat: 'monitor.channel.wechat',
email: 'monitor.channel.email',
sms: 'monitor.channel.sms',
webhook: 'monitor.channel.webhook',
};
// 兼容旧调用:返回当前语言的标签
export function getChannelTypeLabelKey(type: string): string {
return CHANNEL_TYPE_LABEL_KEYS[type] ? i18n.t(CHANNEL_TYPE_LABEL_KEYS[type]) : type;
}
// 解析单个 notify_channels 引用值 — 返回 {id?, type, name, isLegacy}
// 新格式存渠道 ID (string),旧格式存类型字符串 (email/dingtalk 等)
export function resolveChannelRef(value: string, channels: AlertChannel[]): { type: string; name: string; isLegacy: boolean } | null {
if (!value) return null;
// 尝试按 ID 匹配已配置渠道
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('common.unnamed'), isLegacy: false };
// 兼容旧格式:值本身是类型字符串
if (KNOWN_CHANNEL_TYPES.includes(value)) {
return { type: value, name: CHANNEL_TYPE_LABELS[value] || value, isLegacy: true };
return { type: value, name: getChannelTypeLabelKey(value), isLegacy: true };
}
return null;
}
// 渠道类型选项(供下拉选择)
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: 'wechat', label: '企业微信', 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: 'sms', label: '短信', placeholder: '{\n "phones": "13800138000",\n "sign": "AIOps"\n}' },
{ key: 'webhook', label: 'Webhook', placeholder: '{\n "url": "https://example.com/alert"\n}' },
];
// 渠道类型选项(供下拉选择,label 走 i18n) // Logan.Li
export function getChannelTypes(): { key: string; label: string; placeholder: string }[] {
return [
{ key: 'dingtalk', label: i18n.t('monitor.channel.dingtalk'), placeholder: '{\n "webhook": "https://oapi.dingtalk.com/robot/send?access_token=***",\n "secret": "SECxxx"\n}' },
{ key: 'wechat', label: i18n.t('monitor.channel.wechat'), placeholder: '{\n "webhook": "https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=***"\n}' },
{ key: 'email', label: i18n.t('monitor.channel.email'), placeholder: '{\n "to": "ops@ezops.io",\n "subject": "Alert Notification"\n}' },
{ key: 'sms', label: i18n.t('monitor.channel.sms'), placeholder: '{\n "phones": "13800138000",\n "sign": "AIOps"\n}' },
{ key: 'webhook', label: 'Webhook', placeholder: '{\n "url": "https://example.com/alert"\n}' },
];
}
export function getChannelTypeLabel(type: string) {
return CHANNEL_TYPES.find((t) => t.key === type)?.label || type;
return getChannelTypes().find((t) => t.key === type)?.label || type;
}
// 根据渠道类型返回对应图标组件
@@ -47,11 +47,12 @@ import { cn } from '@/lib/utils';
import { PageShell } from '@/components/layout/PageShell';
import { PageLoading } from '@/components/layout/PageLoading';
import { PageEmpty } from '@/components/layout/PageEmpty';
import i18n from '@/i18n';
// ═══════════ Tab 配置 ═══════════
type TabId = 'agent' | 'zabbix' | 'prometheus';
const getTabs = (t: (key: string) => string): { id: TabId; label: string; icon: React.ReactNode }[] => [
{ id: 'agent', label: t('monitor.dashboard.tab.agent'), icon: <Server className="w-3.5 h-3.5" /> },
{ id: 'agent', label: i18n.t('monitor.dashboard.tab.agent'), icon: <Server className="w-3.5 h-3.5" /> },
{ id: 'zabbix', label: 'Zabbix', icon: <Activity className="w-3.5 h-3.5" /> },
{ id: 'prometheus', label: 'Prometheus', icon: <Activity className="w-3.5 h-3.5" /> },
];
@@ -86,16 +87,16 @@ const AgentTab: React.FC = () => {
// 批量卸载
const [batchUninstalling, setBatchUninstalling] = useState(false);
const handleBatchUninstall = async () => {
const ok = await _confirm({ title: t('monitor.dashboard.confirm.uninstallTitle'), description: t('monitor.dashboard.confirm.uninstallDesc', { count: selIds.length }), confirmText: t('monitor.dashboard.confirm.uninstall'), variant: 'destructive' });
const ok = await _confirm({ title: i18n.t('monitor.dashboard.confirm.uninstallTitle'), description: i18n.t('monitor.dashboard.confirm.uninstallDesc', { count: selIds.length }), confirmText: i18n.t('monitor.dashboard.confirm.uninstall'), variant: 'destructive' });
if (!ok) return;
setBatchUninstalling(true);
setOperating(new Set(selIds));
try {
await agentApi.batchUninstall(selIds);
toast.success(t('monitor.dashboard.agent.toast.batchUninstall', { count: selIds.length }));
toast.success(i18n.t('monitor.dashboard.agent.toast.batchUninstall', { count: selIds.length }));
setSelected(new Set());
setTimeout(() => { fetch(); setOperating(new Set()); }, 30000);
} catch { toast.error(t('monitor.dashboard.agent.toast.submitFailed')); setOperating(new Set()); }
} catch { toast.error(i18n.t('monitor.dashboard.agent.toast.submitFailed')); setOperating(new Set()); }
finally { setBatchUninstalling(false); }
};
const totalPages = Math.max(1, Math.ceil(hosts.length / pageSize));
@@ -115,7 +116,7 @@ const AgentTab: React.FC = () => {
return next;
});
} catch (e: any) {
toast.error(t('monitor.dashboard.agent.toast.refreshFailed', { msg: (e?.message || t('monitor.dashboard.agent.toast.unknownError')) }));
toast.error(i18n.t('monitor.dashboard.agent.toast.refreshFailed', { msg: (e?.message || i18n.t('monitor.dashboard.agent.toast.unknownError')) }));
} finally {
setLoading(false);
setRefreshing(false);
@@ -158,17 +159,17 @@ const AgentTab: React.FC = () => {
// 执行批量部署
const handleBatchSubmit = async () => {
if (!batchAck) { toast.error(t('monitor.dashboard.agent.toast.ackRequired')); return; }
if (!batchAck) { toast.error(i18n.t('monitor.dashboard.agent.toast.ackRequired')); return; }
setBatchSubmitting(true);
const token = useUserStore.getState().token;
const ids = selectedHosts.map(h => h.server_id);
setOperating(new Set(ids));
try {
if (batchMode === 'install') {
if (!token) { toast.error(t('monitor.dashboard.agent.toast.notLogin')); return; }
if (!token) { toast.error(i18n.t('monitor.dashboard.agent.toast.notLogin')); return; }
// 安装:只安装无 Agent 的
const installIds = needInstall.map(h => h.server_id);
if (installIds.length === 0) { toast.warning(t('monitor.dashboard.agent.toast.allInstalled')); return; }
if (installIds.length === 0) { toast.warning(i18n.t('monitor.dashboard.agent.toast.allInstalled')); return; }
// 为未保存凭据的主机构造临时凭据 map;后端遇到空字段不会覆盖已有凭据 // Logan.Li
const credentials: Record<number, { username?: string; password?: string; ssh_key?: string; auth_type?: string }> = {};
const needCreds = batchCreds.username && (batchCreds.authType === 'key' ? batchCreds.sshKey : batchCreds.password);
@@ -183,63 +184,63 @@ const AgentTab: React.FC = () => {
}
}
const res = await serverApi.batchInstallAgent(installIds, token, Object.keys(credentials).length ? credentials : undefined);
toast.success(t('monitor.dashboard.agent.toast.batchInstall', { count: res?.total ?? installIds.length }));
toast.success(i18n.t('monitor.dashboard.agent.toast.batchInstall', { count: res?.total ?? installIds.length }));
setSelected(new Set());
setTimeout(() => { fetch(); setOperating(new Set()); }, 30000);
} else {
// 升级:只升级在线的
const upgradeIds = needUpgrade.map(h => h.server_id);
if (upgradeIds.length === 0) { toast.warning(t('monitor.dashboard.agent.toast.noOnline')); return; }
if (upgradeIds.length === 0) { toast.warning(i18n.t('monitor.dashboard.agent.toast.noOnline')); return; }
const res = await agentApi.batchUpgrade(upgradeIds);
toast.success(res?.message || t('monitor.dashboard.agent.toast.batchUpgrade', { count: upgradeIds.length }));
toast.success(res?.message || i18n.t('monitor.dashboard.agent.toast.batchUpgrade', { count: upgradeIds.length }));
setSelected(new Set());
setTimeout(() => { fetch(); setOperating(new Set()); }, 30000);
}
setBatchOpen(false);
} catch { toast.error(t('monitor.dashboard.agent.toast.submitFailed')); setOperating(new Set()); }
} catch { toast.error(i18n.t('monitor.dashboard.agent.toast.submitFailed')); setOperating(new Set()); }
finally { setBatchSubmitting(false); }
};
if (loading) return <PageLoading label={t('monitor.dashboard.agent.loadingHosts')} />;
if (loading) return <PageLoading label={i18n.t('monitor.dashboard.agent.loadingHosts')} />;
if (!hosts.length) return (
<PageEmpty
icon={<Server className="h-8 w-8" />}
title={t('monitor.dashboard.agent.emptyTitle')}
description={t('monitor.dashboard.agent.emptyDesc')}
title={i18n.t('monitor.dashboard.agent.emptyTitle')}
description={i18n.t('monitor.dashboard.agent.emptyDesc')}
/>
);
return (
<div>
{/* 工具栏 */}
<div className="flex items-center gap-2 mb-3 flex-wrap">
{selAny && <span className="text-xs text-[var(--dg-text-secondary)]">{t('monitor.dashboard.agent.selected', { count: selected.size })}</span>}
{selAny && <span className="text-xs text-[var(--dg-text-secondary)]">{i18n.t('monitor.dashboard.agent.selected', { count: selected.size })}</span>}
<div className="flex-1" />
<Button size="sm" variant="outline" className="h-7 text-xs gap-1" onClick={() => {
const picked = selAny ? hosts.find(h => selected.has(String(h.server_id))) : null;
setWizardServer(picked ? { id: picked.server_id, hostname: picked.hostname, ip: picked.ip, has_auth: picked.has_auth } : null);
setWizardServer(picked ? { id: picked.server_id, hostname: picked.hostname, ip: picked.ip, has_auth: picked.has_auth, os: picked.os } : null);
setWizardOpen(true);
}}>
<Rocket className="w-3 h-3" />{t('monitor.dashboard.agent.installAgent')}
<Rocket className="w-3 h-3" />{i18n.t('monitor.dashboard.agent.installAgent')}
</Button>
{selAny && (
<>
<Button size="sm" variant="outline" className="h-7 text-xs gap-1 dg-btn-secondary dg-text-blue" onClick={openBatchDialog}>
<PackageOpen className="w-3 h-3" />{t('monitor.dashboard.agent.batchDeploy')} ({selected.size})
<PackageOpen className="w-3 h-3" />{i18n.t('monitor.dashboard.agent.batchDeploy')} ({selected.size})
</Button>
<Button size="sm" variant="outline" className="h-7 text-xs gap-1 border-red-500/30 dg-text-red hover:bg-red-500/10" onClick={handleBatchUninstall} disabled={batchUninstalling}>
<Trash2 className="w-3 h-3" />{t('monitor.dashboard.agent.batchUninstall')} ({selected.size})
<Trash2 className="w-3 h-3" />{i18n.t('monitor.dashboard.agent.batchUninstall')} ({selected.size})
</Button>
</>
)}
<Button size="sm" variant="ghost" className="h-7 text-xs gap-1" onClick={fetch} disabled={refreshing}>
<RefreshCw className={cn('w-3 h-3', refreshing && 'animate-spin')} />{t('monitor.dashboard.refresh')}
<RefreshCw className={cn('w-3 h-3', refreshing && 'animate-spin')} />{i18n.t('monitor.dashboard.refresh')}
</Button>
</div>
<AgentWizard open={wizardOpen} onOpenChange={setWizardOpen} server={wizardServer}
onStart={(id) => { setOperating(prev => new Set(prev).add(id)); }}
onInstalled={() => { toast.success(t('monitor.dashboard.agent.toast.installed')); setWizardOpen(false); fetch(); }}
onFailed={(id) => { toast.error(t('monitor.dashboard.agent.toast.installFailed')); setOperating(prev => { const next = new Set(prev); next.delete(id); return next; }); }} />
onInstalled={() => { toast.success(i18n.t('monitor.dashboard.agent.toast.installed')); setWizardOpen(false); fetch(); }}
onFailed={(id) => { toast.error(i18n.t('monitor.dashboard.agent.toast.installFailed')); setOperating(prev => { const next = new Set(prev); next.delete(id); return next; }); }} />
{/* ────────── 批量部署 Agent 对话框 ────────── */}
<Dialog open={batchOpen} onOpenChange={(v) => { if (!v) { setBatchOpen(false); setBatchAck(false); setBatchCreds({ username: 'root', password: '', sshKey: '', authType: 'password' }); } }}>
@@ -247,10 +248,10 @@ const AgentTab: React.FC = () => {
<DialogHeader>
<DialogTitle className="flex items-center gap-2 text-base">
<PackageOpen className="w-5 h-5 dg-text-blue" />
{t('monitor.dashboard.batch.title')}
{i18n.t('monitor.dashboard.batch.title')}
</DialogTitle>
<DialogDescription className="dg-text-secondary text-xs">
{t('monitor.dashboard.batch.summary', { selected: selectedHosts.length, install: needInstall.length, upgrade: needUpgrade.length })}
{i18n.t('monitor.dashboard.batch.summary', { selected: selectedHosts.length, install: needInstall.length, upgrade: needUpgrade.length })}
</DialogDescription>
</DialogHeader>
@@ -266,7 +267,7 @@ const AgentTab: React.FC = () => {
batchMode === m ? 'dg-btn-primary text-white shadow-sm' : 'dg-text-secondary hover:text-[var(--dg-text-primary)]'
}`}
>
{m === 'install' ? t('monitor.dashboard.batch.install', { count: needInstall.length }) : t('monitor.dashboard.batch.upgrade', { count: needUpgrade.length })}
{m === 'install' ? i18n.t('monitor.dashboard.batch.install', { count: needInstall.length }) : i18n.t('monitor.dashboard.batch.upgrade', { count: needUpgrade.length })}
</button>
))}
</div>
@@ -276,11 +277,11 @@ const AgentTab: React.FC = () => {
<table className="w-full text-xs">
<thead className="bg-[var(--dg-bg-tertiary)]">
<tr>
<th className="px-3 py-2 text-left font-medium dg-text-secondary">{t('monitor.dashboard.col.hostname')}</th>
<th className="px-3 py-2 text-left font-medium dg-text-secondary">{i18n.t('monitor.dashboard.col.hostname')}</th>
<th className="px-3 py-2 text-left font-medium dg-text-secondary">IP</th>
<th className="px-3 py-2 text-left font-medium dg-text-secondary">{t('monitor.dashboard.col.status')}</th>
<th className="px-3 py-2 text-left font-medium dg-text-secondary">{t('monitor.dashboard.col.version')}</th>
<th className="px-3 py-2 text-left font-medium dg-text-secondary">{t('monitor.dashboard.col.action')}</th>
<th className="px-3 py-2 text-left font-medium dg-text-secondary">{i18n.t('monitor.dashboard.col.status')}</th>
<th className="px-3 py-2 text-left font-medium dg-text-secondary">{i18n.t('monitor.dashboard.col.version')}</th>
<th className="px-3 py-2 text-left font-medium dg-text-secondary">{i18n.t('monitor.dashboard.col.action')}</th>
</tr>
</thead>
<tbody>
@@ -290,15 +291,15 @@ const AgentTab: React.FC = () => {
<td className="px-3 py-2 font-mono dg-text-secondary">{h.ip}</td>
<td className="px-3 py-2">
{h.agent_status === 'online'
? <Badge className="text-[10px] bg-emerald-500/20 dg-text-green">{t('monitor.dashboard.status.online')}</Badge>
? <Badge className="text-[10px] bg-emerald-500/20 dg-text-green">{i18n.t('monitor.dashboard.status.online')}</Badge>
: <Badge className="text-[10px] bg-[var(--dg-bg-active)]/20 dg-text-secondary">
{h.agent_status === 'not_installed' ? t('monitor.dashboard.status.notInstalled') : h.agent_status || t('monitor.dashboard.status.offline')}
{h.agent_status === 'not_installed' ? i18n.t('monitor.dashboard.status.notInstalled') : h.agent_status || i18n.t('monitor.dashboard.status.offline')}
</Badge>}
</td>
<td className="px-3 py-2 font-mono dg-text-secondary">{h.agent_version || '—'}</td>
<td className="px-3 py-2">
<span className="dg-text-blue text-[11px]">
{batchMode === 'install' ? t('monitor.dashboard.batch.willInstall') : t('monitor.dashboard.batch.willUpgrade')}
{batchMode === 'install' ? i18n.t('monitor.dashboard.batch.willInstall') : i18n.t('monitor.dashboard.batch.willUpgrade')}
</span>
</td>
</tr>
@@ -312,34 +313,34 @@ const AgentTab: React.FC = () => {
<div className="rounded-md border border-[var(--dg-border)] bg-[var(--dg-bg-tertiary)]/50 p-3 space-y-3">
<div className="flex items-center gap-2">
<Info className="w-4 h-4 dg-text-blue shrink-0" />
<span className="text-xs text-[var(--dg-text-secondary)]">{t('monitor.dashboard.creds.hint')}</span>
<span className="text-xs text-[var(--dg-text-secondary)]">{i18n.t('monitor.dashboard.creds.hint')}</span>
</div>
<div className="grid grid-cols-2 gap-3">
<div>
<Label className="text-[11px] dg-text-secondary mb-1 block">{t('monitor.dashboard.creds.authType')}</Label>
<Label className="text-[11px] dg-text-secondary mb-1 block">{i18n.t('monitor.dashboard.creds.authType')}</Label>
<Select value={batchCreds.authType} onValueChange={(v: 'password' | 'key') => setBatchCreds(c => ({ ...c, authType: v }))}>
<SelectTrigger className="h-8 text-xs dg-input text-[var(--dg-text-primary)]">
<SelectValue />
</SelectTrigger>
<SelectContent className="dg-input text-[var(--dg-text-primary)]">
<SelectItem value="password">{t('monitor.dashboard.creds.password')}</SelectItem>
<SelectItem value="key">{t('monitor.dashboard.creds.sshKey')}</SelectItem>
<SelectItem value="password">{i18n.t('monitor.dashboard.creds.password')}</SelectItem>
<SelectItem value="key">{i18n.t('monitor.dashboard.creds.sshKey')}</SelectItem>
</SelectContent>
</Select>
</div>
<div>
<Label className="text-[11px] dg-text-secondary mb-1 block">{t('monitor.dashboard.creds.username')}</Label>
<Label className="text-[11px] dg-text-secondary mb-1 block">{i18n.t('monitor.dashboard.creds.username')}</Label>
<Input value={batchCreds.username} onChange={e => setBatchCreds(c => ({ ...c, username: e.target.value }))} placeholder="root" className="h-8 text-xs dg-input text-[var(--dg-text-primary)]" />
</div>
</div>
{batchCreds.authType === 'password' ? (
<div>
<Label className="text-[11px] dg-text-secondary mb-1 block">{t('monitor.dashboard.creds.password')}</Label>
<Input type="password" value={batchCreds.password} onChange={e => setBatchCreds(c => ({ ...c, password: e.target.value }))} placeholder={t('monitor.dashboard.creds.passwordPlaceholder')} className="h-8 text-xs dg-input text-[var(--dg-text-primary)]" />
<Label className="text-[11px] dg-text-secondary mb-1 block">{i18n.t('monitor.dashboard.creds.password')}</Label>
<Input type="password" value={batchCreds.password} onChange={e => setBatchCreds(c => ({ ...c, password: e.target.value }))} placeholder={i18n.t('monitor.dashboard.creds.passwordPlaceholder')} className="h-8 text-xs dg-input text-[var(--dg-text-primary)]" />
</div>
) : (
<div>
<Label className="text-[11px] dg-text-secondary mb-1 block">{t('monitor.dashboard.creds.sshKey')}</Label>
<Label className="text-[11px] dg-text-secondary mb-1 block">{i18n.t('monitor.dashboard.creds.sshKey')}</Label>
<textarea value={batchCreds.sshKey} onChange={e => setBatchCreds(c => ({ ...c, sshKey: e.target.value }))} placeholder="-----BEGIN OPENSSH PRIVATE KEY-----" className="w-full h-24 rounded-md border border-[var(--dg-border)] bg-[var(--dg-bg-secondary)] text-[var(--dg-text-primary)] text-xs p-2 resize-none focus:outline-none focus:ring-1 focus:ring-[var(--dg-blue)]" />
</div>
)}
@@ -352,30 +353,30 @@ const AgentTab: React.FC = () => {
<Info className="w-4 h-4 dg-text-yellow mt-0.5 shrink-0" />
<div>
<p className="text-xs font-medium text-amber-300 mb-1">
{(batchMode === 'install' ? t('monitor.dashboard.warn.thisInstall') : t('monitor.dashboard.warn.thisUpgrade')) + t('monitor.dashboard.warn.intro')}
{(batchMode === 'install' ? i18n.t('monitor.dashboard.warn.thisInstall') : i18n.t('monitor.dashboard.warn.thisUpgrade')) + i18n.t('monitor.dashboard.warn.intro')}
</p>
<p className="text-[11px] dg-text-yellow/80 leading-relaxed">
{batchMode === 'upgrade' ? t('monitor.dashboard.warn.upgradeNotice') : t('monitor.dashboard.warn.installNotice')}
{batchMode === 'upgrade' ? i18n.t('monitor.dashboard.warn.upgradeNotice') : i18n.t('monitor.dashboard.warn.installNotice')}
</p>
<ul className="mt-1 space-y-0.5 text-[11px] dg-text-secondary list-disc list-inside">
{batchMode === 'upgrade' && (
<>
<li>{t('monitor.dashboard.warn.u1')}</li>
<li>{t('monitor.dashboard.warn.u2')}</li>
<li>{t('monitor.dashboard.warn.u3')}</li>
<li>{t('monitor.dashboard.warn.u4')}</li>
<li>{i18n.t('monitor.dashboard.warn.u1')}</li>
<li>{i18n.t('monitor.dashboard.warn.u2')}</li>
<li>{i18n.t('monitor.dashboard.warn.u3')}</li>
<li>{i18n.t('monitor.dashboard.warn.u4')}</li>
</>
)}
{batchMode === 'install' && (
<>
<li>{t('monitor.dashboard.warn.i1')}</li>
<li>{t('monitor.dashboard.warn.i2')}</li>
<li>{t('monitor.dashboard.warn.i3')}</li>
<li>{t('monitor.dashboard.warn.i4')}</li>
<li>{i18n.t('monitor.dashboard.warn.i1')}</li>
<li>{i18n.t('monitor.dashboard.warn.i2')}</li>
<li>{i18n.t('monitor.dashboard.warn.i3')}</li>
<li>{i18n.t('monitor.dashboard.warn.i4')}</li>
</>
)}
<li>{t('monitor.dashboard.warn.c1')}</li>
<li>{t('monitor.dashboard.warn.c2')}</li>
<li>{i18n.t('monitor.dashboard.warn.c1')}</li>
<li>{i18n.t('monitor.dashboard.warn.c2')}</li>
</ul>
</div>
</div>
@@ -384,13 +385,13 @@ const AgentTab: React.FC = () => {
{/* 我已知悉 勾选 */}
<div className="flex items-center gap-2">
<Checkbox id="batch-ack" checked={batchAck} onCheckedChange={(c) => setBatchAck(!!c)} />
<label htmlFor="batch-ack" className="text-xs text-[var(--dg-text-secondary)] cursor-pointer select-none">{t('monitor.dashboard.batch.ack')}</label>
<label htmlFor="batch-ack" className="text-xs text-[var(--dg-text-secondary)] cursor-pointer select-none">{i18n.t('monitor.dashboard.batch.ack')}</label>
</div>
</div>
<DialogFooter className="gap-2">
<Button variant="outline" className="border-[var(--dg-border)] text-[var(--dg-text-secondary)] h-8 text-xs" onClick={() => { setBatchOpen(false); setBatchAck(false); }}>
{t('monitor.dashboard.batch.cancel')}
{i18n.t('monitor.dashboard.batch.cancel')}
</Button>
<Button
className="dg-btn-primary h-8 text-xs gap-1"
@@ -398,7 +399,7 @@ const AgentTab: React.FC = () => {
onClick={handleBatchSubmit}
>
{batchSubmitting && <Loader2 className="w-3 h-3 animate-spin" />}
{batchMode === 'install' ? t('monitor.dashboard.batch.confirmInstall') : t('monitor.dashboard.batch.confirmUpgrade')}
{batchMode === 'install' ? i18n.t('monitor.dashboard.batch.confirmInstall') : i18n.t('monitor.dashboard.batch.confirmUpgrade')}
</Button>
</DialogFooter>
</DialogContent>
@@ -412,10 +413,10 @@ const AgentTab: React.FC = () => {
</th>
{['hostname','agent_version','agent_status','cpu_usage','mem_usage','disk_usage','region','ip'].map(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={() => toggle(f as SortField)}>
<div className="flex items-center gap-1">{{hostname:t('monitor.dashboard.col.hostname'),agent_version:t('monitor.dashboard.col.agentVersion'),agent_status:t('monitor.dashboard.col.status'),cpu_usage:t('monitor.dashboard.col.cpu'),mem_usage:t('monitor.dashboard.col.memory'),disk_usage:t('monitor.dashboard.col.disk'),region:t('monitor.dashboard.col.region'),ip:'IP'}[f]}<SI f={f as SortField} /></div>
<div className="flex items-center gap-1">{{hostname:i18n.t('monitor.dashboard.col.hostname'),agent_version:i18n.t('monitor.dashboard.col.agentVersion'),agent_status:i18n.t('monitor.dashboard.col.status'),cpu_usage:i18n.t('monitor.dashboard.col.cpu'),mem_usage:i18n.t('monitor.dashboard.col.memory'),disk_usage:i18n.t('monitor.dashboard.col.disk'),region:i18n.t('monitor.dashboard.col.region'),ip:'IP'}[f]}<SI f={f as SortField} /></div>
</th>
))}
<th className="px-3 py-2 text-left font-medium text-[var(--dg-text-secondary)] whitespace-nowrap">{t('monitor.dashboard.col.action')}</th></tr></thead>
<th className="px-3 py-2 text-left font-medium text-[var(--dg-text-secondary)] whitespace-nowrap">{i18n.t('monitor.dashboard.col.action')}</th></tr></thead>
<tbody>
{paged.map((h, i) => (
<tr key={h.hostname + i} className="border-b border-[var(--dg-border)] last:border-0 hover:bg-[var(--dg-bg-tertiary)]/50">
@@ -435,13 +436,13 @@ const AgentTab: React.FC = () => {
{operating.has(h.server_id) ? (
<span className="inline-flex items-center gap-1 dg-text-blue">
<Loader2 className="w-3 h-3 animate-spin" />
<span className="text-[10px]">{t('monitor.dashboard.agent.deploying')}</span>
<span className="text-[10px]">{i18n.t('monitor.dashboard.agent.deploying')}</span>
</span>
) : (
h.agent_version || '—'
)}
</td>
<td className="px-3 py-2.5">{h.agent_status==='online'?<Badge className="text-[10px] bg-emerald-500/20 dg-text-green"><Wifi className="w-3 h-3 mr-1"/>{t('monitor.dashboard.status.online')}</Badge>:h.agent_status==='not_installed'?<Badge className="text-[10px] bg-amber-500/20 dg-text-yellow">{t('monitor.dashboard.status.notInstalled')}</Badge>:<Badge className="text-[10px] bg-[var(--dg-bg-active)]/10 dg-text-secondary"><WifiOff className="w-3 h-3 mr-1"/>{t('monitor.dashboard.status.offline')}</Badge>}</td>
<td className="px-3 py-2.5">{h.agent_status==='online'?<Badge className="text-[10px] bg-emerald-500/20 dg-text-green"><Wifi className="w-3 h-3 mr-1"/>{i18n.t('monitor.dashboard.status.online')}</Badge>:h.agent_status==='not_installed'?<Badge className="text-[10px] bg-amber-500/20 dg-text-yellow">{i18n.t('monitor.dashboard.status.notInstalled')}</Badge>:<Badge className="text-[10px] bg-[var(--dg-bg-active)]/10 dg-text-secondary"><WifiOff className="w-3 h-3 mr-1"/>{i18n.t('monitor.dashboard.status.offline')}</Badge>}</td>
<td className="px-3 py-2.5">{bar(Number(h.cpu_usage||0), `${Number(h.cpu_usage||0).toFixed(1)}%`)}</td>
<td className="px-3 py-2.5">{bar(Number(h.mem_usage||0), `${Number(h.mem_usage||0).toFixed(1)}%`)}</td>
<td className="px-3 py-2.5">{bar(Number(h.disk_usage||0), `${Number(h.disk_usage||0).toFixed(1)}%`)}</td>
@@ -450,7 +451,7 @@ const AgentTab: React.FC = () => {
<td className="px-3 py-2.5">
<Button variant="ghost" size="sm" className="h-7 text-xs dg-text-blue hover:bg-[var(--dg-bg-hover)] px-2"
onClick={() => navigate(`/host-monitor?host=${encodeURIComponent(h.hostname)}`)}>
<BarChart3 className="w-3.5 h-3.5 mr-1" />{t('monitor.dashboard.agent.chart')}
<BarChart3 className="w-3.5 h-3.5 mr-1" />{i18n.t('monitor.dashboard.agent.chart')}
</Button>
</td>
</tr>
@@ -460,17 +461,17 @@ const AgentTab: React.FC = () => {
{hosts.length > pageSize && (
<div className="flex items-center justify-between px-3 py-2 bg-[var(--dg-bg-tertiary)] border-t border-[var(--dg-border)] text-xs">
<div className="flex items-center gap-2 text-[var(--dg-text-muted)]">
<span>{t('monitor.dashboard.pagination.total', { count: hosts.length })}</span>
<span>{i18n.t('monitor.dashboard.pagination.total', { count: hosts.length })}</span>
<select className="bg-[var(--dg-bg-primary)] border border-[var(--dg-border)] rounded px-2 py-0.5 text-xs" value={pageSize} onChange={e => { setPageSize(Number(e.target.value)); setPage(1); }}>
<option value={10}>{`10/${t('monitor.dashboard.pagination.perPage')}`}</option>
<option value={20}>{`20/${t('monitor.dashboard.pagination.perPage')}`}</option>
<option value={30}>{`30/${t('monitor.dashboard.pagination.perPage')}`}</option>
<option value={10}>{`10/${i18n.t('monitor.dashboard.pagination.perPage')}`}</option>
<option value={20}>{`20/${i18n.t('monitor.dashboard.pagination.perPage')}`}</option>
<option value={30}>{`30/${i18n.t('monitor.dashboard.pagination.perPage')}`}</option>
</select>
</div>
<div className="flex items-center gap-1">
<button className="px-2 py-0.5 rounded hover:bg-[var(--dg-bg-primary)] disabled:opacity-30" disabled={page <= 1} onClick={() => setPage(p => p - 1)}>{t('monitor.dashboard.pagination.prev')}</button>
<button className="px-2 py-0.5 rounded hover:bg-[var(--dg-bg-primary)] disabled:opacity-30" disabled={page <= 1} onClick={() => setPage(p => p - 1)}>{i18n.t('monitor.dashboard.pagination.prev')}</button>
<span className="px-2 text-[var(--dg-text-primary)]">{page} / {totalPages}</span>
<button className="px-2 py-0.5 rounded hover:bg-[var(--dg-bg-primary)] disabled:opacity-30" disabled={page >= totalPages} onClick={() => setPage(p => p + 1)}>{t('monitor.dashboard.pagination.next')}</button>
<button className="px-2 py-0.5 rounded hover:bg-[var(--dg-bg-primary)] disabled:opacity-30" disabled={page >= totalPages} onClick={() => setPage(p => p + 1)}>{i18n.t('monitor.dashboard.pagination.next')}</button>
</div>
</div>
)}
@@ -507,20 +508,20 @@ const DatasourceToolbar: React.FC<{
<div className="flex items-center gap-2 mb-3 flex-wrap">
<Select value={activeId} onValueChange={onChange}>
<SelectTrigger className="w-[280px] h-8 text-xs dg-input">
<SelectValue placeholder={t('monitor.datasourceToolbar.selectDatasource')} />
<SelectValue placeholder={i18n.t('monitor.datasourceToolbar.selectDatasource')} />
</SelectTrigger>
<SelectContent className="dg-input">
{sources.map(ds => (
<SelectItem key={String(ds.id)} value={String(ds.id)}>
{ds.name || ds.url}{ds.is_default ? t('monitor.datasourceToolbar.defaultSuffix') : ''}
{ds.name || ds.url}{ds.is_default ? i18n.t('monitor.datasourceToolbar.defaultSuffix') : ''}
</SelectItem>
))}
</SelectContent>
</Select>
<Button variant="outline" size="sm" className="h-8 text-xs gap-1" onClick={onRefresh} disabled={refreshing}>
<RefreshCw className={cn('w-3 h-3', refreshing && 'animate-spin')} />{t('monitor.datasourceToolbar.refreshDatasource')}
<RefreshCw className={cn('w-3 h-3', refreshing && 'animate-spin')} />{i18n.t('monitor.datasourceToolbar.refreshDatasource')}
</Button>
<span className="text-[11px] text-[var(--dg-text-muted)]">{t('monitor.datasourceToolbar.datasourceSummary', { count: sources.length })}</span>
<span className="text-[11px] text-[var(--dg-text-muted)]">{i18n.t('monitor.datasourceToolbar.datasourceSummary', { count: sources.length })}</span>
</div>
);
@@ -539,12 +540,12 @@ const ZabbixTab: React.FC = () => {
finally { setLoading(false); }
};
useEffect(() => { fetchSources(); }, []);
if (loading) return <PageLoading label={t('monitor.dashboard.zabbix.loading')} />;
if (loading) return <PageLoading label={i18n.t('monitor.dashboard.zabbix.loading')} />;
if (!ds) return (
<PageEmpty
icon={<Database className="h-8 w-8" />}
title={t('monitor.dashboard.zabbix.emptyTitle')}
action={<a href="/datasources" className="text-xs dg-text-blue hover:underline inline-flex items-center gap-1">{t('monitor.dashboard.zabbix.goConfig')} <ExternalLink className="w-3 h-3" /></a>}
title={i18n.t('monitor.dashboard.zabbix.emptyTitle')}
action={<a href="/datasources" className="text-xs dg-text-blue hover:underline inline-flex items-center gap-1">{i18n.t('monitor.dashboard.zabbix.goConfig')} <ExternalLink className="w-3 h-3" /></a>}
/>
);
return (
@@ -570,12 +571,12 @@ const PrometheusTab: React.FC = () => {
finally { setLoading(false); }
};
useEffect(() => { fetchSources(); }, []);
if (loading) return <PageLoading label={t('monitor.dashboard.prometheus.loading')} />;
if (loading) return <PageLoading label={i18n.t('monitor.dashboard.prometheus.loading')} />;
if (!ds) return (
<PageEmpty
icon={<Database className="h-8 w-8" />}
title={t('monitor.dashboard.prometheus.emptyTitle')}
action={<a href="/datasources" className="text-xs dg-text-blue hover:underline inline-flex items-center gap-1">{t('monitor.dashboard.zabbix.goConfig')} <ExternalLink className="w-3 h-3" /></a>}
title={i18n.t('monitor.dashboard.prometheus.emptyTitle')}
action={<a href="/datasources" className="text-xs dg-text-blue hover:underline inline-flex items-center gap-1">{i18n.t('monitor.dashboard.zabbix.goConfig')} <ExternalLink className="w-3 h-3" /></a>}
/>
);
return (
@@ -598,8 +599,8 @@ const GrafanaDashboard: React.FC = () => {
return (
<PageShell
variant="workspace"
title={t('monitor.dashboard.title')}
subtitle={t('monitor.dashboard.subtitle')}
title={i18n.t('monitor.dashboard.title')}
subtitle={i18n.t('monitor.dashboard.subtitle')}
icon={<Monitor className="h-5 w-5" />}
tabs={pageTabs}
activeTab={tab}
@@ -10,6 +10,7 @@ import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@
import { prometheusProxyApi } from '@/api';
import { useTranslation } from 'react-i18next';
import type { JsonData } from '@/types/common';
import i18n from '@/i18n';
interface Props { dsUrl?: string; }
@@ -65,7 +66,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 fmtCores = (v: number, t: (k: string) => string) => v >= 1 ? `${v.toFixed(2)} ${t('monitor.prometheusPanel.cores')}` : `${(v * 1000).toFixed(0)} m`;
const fmtCores = (v: number) => v >= 1 ? `${v.toFixed(2)} ${i18n.t('monitor.prometheusPanel.cores')}` : `${(v * 1000).toFixed(0)} m`;
const K8sPanel: React.FC<{ d: JsonData}> = ({ d }) => {
const { t } = useTranslation();
@@ -80,7 +81,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="text-xs font-medium mb-2 flex items-center gap-1"><Cpu className="w-3 h-3 dg-text-purple" />{t('monitor.prometheusPanel.nodeCpuMemUtil')}</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.prometheusPanel.nodeCpuMemUtil')}</div>
{(d.nodeCPU || []).map((n: JsonData, i: number) => {
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>;
@@ -136,8 +137,8 @@ const NodePanel: React.FC<{ d: JsonData}> = ({ d }) => {
<table className="w-full text-xs">
<thead className="bg-[var(--dg-bg-tertiary)]"><tr>
{[
{ f: 'name' as NodeSortField, l: t('monitor.prometheusPanel.node') }, { f: 'cpu' as NodeSortField, l: t('monitor.prometheusPanel.cpu') },
{ f: 'mem' as NodeSortField, l: t('monitor.prometheusPanel.memory') }, { f: 'disk' as NodeSortField, l: t('monitor.prometheusPanel.disk') }, { f: 'rx' as NodeSortField, l: t('monitor.prometheusPanel.inbound') }, { f: 'tx' as NodeSortField, l: t('monitor.prometheusPanel.outbound') },
{ f: 'name' as NodeSortField, l: i18n.t('monitor.prometheusPanel.node') }, { f: 'cpu' as NodeSortField, l: i18n.t('monitor.prometheusPanel.cpu') },
{ f: 'mem' as NodeSortField, l: i18n.t('monitor.prometheusPanel.memory') }, { f: 'disk' as NodeSortField, l: i18n.t('monitor.prometheusPanel.disk') }, { f: 'rx' as NodeSortField, l: i18n.t('monitor.prometheusPanel.inbound') }, { f: 'tx' as NodeSortField, l: i18n.t('monitor.prometheusPanel.outbound') },
].map(({ f, l }) => (
<th key={f} className="px-3 py-2 text-left cursor-pointer select-none" onClick={() => toggleSort(f)}><div className="flex items-center gap-1">{l}<SI f={f} /></div></th>
))}
@@ -158,15 +159,15 @@ const NodePanel: React.FC<{ d: JsonData}> = ({ d }) => {
{sorted.length > pageSize && (
<div className="flex items-center justify-between px-3 py-2 bg-[var(--dg-bg-tertiary)] border-t border-[var(--dg-border)] text-xs">
<div className="flex items-center gap-2 text-[var(--dg-text-muted)]">
<span>{t('monitor.prometheusPanel.totalNodes', { count: sorted.length })}</span>
<span>{i18n.t('monitor.prometheusPanel.totalNodes', { count: sorted.length })}</span>
<select className="bg-[var(--dg-bg-primary)] border border-[var(--dg-border)] rounded px-2 py-0.5 text-xs" value={pageSize} onChange={e => { setPageSize(Number(e.target.value)); setPage(1); }}>
<option value={10}>10/{t('monitor.prometheusPanel.perPage')}</option><option value={20}>20/{t('monitor.prometheusPanel.perPage')}</option><option value={50}>50/{t('monitor.prometheusPanel.perPage')}</option>
<option value={10}>10/{i18n.t('monitor.prometheusPanel.perPage')}</option><option value={20}>20/{i18n.t('monitor.prometheusPanel.perPage')}</option><option value={50}>50/{i18n.t('monitor.prometheusPanel.perPage')}</option>
</select>
</div>
<div className="flex items-center gap-1">
<button className="px-2 py-0.5 rounded hover:bg-[var(--dg-bg-primary)] disabled:opacity-30" disabled={safePage <= 1} onClick={() => setPage(Math.max(1, safePage - 1))}>{t('monitor.prometheusPanel.prevPage')}</button>
<button className="px-2 py-0.5 rounded hover:bg-[var(--dg-bg-primary)] disabled:opacity-30" disabled={safePage <= 1} onClick={() => setPage(Math.max(1, safePage - 1))}>{i18n.t('monitor.prometheusPanel.prevPage')}</button>
<span className="px-2 text-[var(--dg-text-primary)]">{safePage} / {totalPages}</span>
<button className="px-2 py-0.5 rounded hover:bg-[var(--dg-bg-primary)] disabled:opacity-30" disabled={safePage >= totalPages} onClick={() => setPage(Math.min(totalPages, safePage + 1))}>{t('monitor.prometheusPanel.nextPage')}</button>
<button className="px-2 py-0.5 rounded hover:bg-[var(--dg-bg-primary)] disabled:opacity-30" disabled={safePage >= totalPages} onClick={() => setPage(Math.min(totalPages, safePage + 1))}>{i18n.t('monitor.prometheusPanel.nextPage')}</button>
</div>
</div>
)}
@@ -189,7 +190,7 @@ const SimpleRank: React.FC<{
<CardContent className="p-3 pt-0">
<div className="space-y-2 max-h-[320px] overflow-y-auto pr-1">
{rows.length === 0 ? (
<div className="py-8 text-center text-xs text-[var(--dg-text-muted)]">{t('monitor.prometheusPanel.noData')}</div>
<div className="py-8 text-center text-xs text-[var(--dg-text-muted)]">{i18n.t('monitor.prometheusPanel.noData')}</div>
) : rows.slice(0, 10).map((p: JsonData, i: number) => {
const value = Number(p.value || 0);
return (
@@ -232,7 +233,7 @@ const PodNetworkRank: React.FC<{ rx: JsonData[]; tx: JsonData[] }> = ({ rx, tx }
return (
<Card className="bg-[var(--dg-bg-primary)] border-[var(--dg-border)]">
<CardHeader className="py-2 px-3">
<CardTitle className="text-xs font-medium">{t('monitor.prometheusPanel.podTrafficTop10')}</CardTitle>
<CardTitle className="text-xs font-medium">{i18n.t('monitor.prometheusPanel.podTrafficTop10')}</CardTitle>
</CardHeader>
<CardContent className="p-0">
<div className="overflow-x-auto">
@@ -240,14 +241,14 @@ const PodNetworkRank: React.FC<{ rx: JsonData[]; tx: JsonData[] }> = ({ rx, tx }
<thead className="bg-[var(--dg-bg-tertiary)] border-y border-[var(--dg-border)]">
<tr>
<th className="px-3 py-2 text-left font-medium text-[var(--dg-text-secondary)]">Pod</th>
<th className="px-3 py-2 text-right font-medium text-[var(--dg-text-secondary)]">{t('monitor.prometheusPanel.inbound')}</th>
<th className="px-3 py-2 text-right font-medium text-[var(--dg-text-secondary)]">{t('monitor.prometheusPanel.outbound')}</th>
<th className="px-3 py-2 text-right font-medium text-[var(--dg-text-secondary)]">{t('monitor.prometheusPanel.totalTraffic')}</th>
<th className="px-3 py-2 text-right font-medium text-[var(--dg-text-secondary)]">{i18n.t('monitor.prometheusPanel.inbound')}</th>
<th className="px-3 py-2 text-right font-medium text-[var(--dg-text-secondary)]">{i18n.t('monitor.prometheusPanel.outbound')}</th>
<th className="px-3 py-2 text-right font-medium text-[var(--dg-text-secondary)]">{i18n.t('monitor.prometheusPanel.totalTraffic')}</th>
</tr>
</thead>
<tbody>
{rows.length === 0 ? (
<tr><td colSpan={4} className="px-3 py-8 text-center text-[var(--dg-text-muted)]">{t('monitor.prometheusPanel.noData')}</td></tr>
<tr><td colSpan={4} className="px-3 py-8 text-center text-[var(--dg-text-muted)]">{i18n.t('monitor.prometheusPanel.noData')}</td></tr>
) : rows.map((p, i) => (
<tr key={p.name} className="border-b border-[var(--dg-border)] last:border-0 hover:bg-[var(--dg-bg-tertiary)]/50">
<td className="px-3 py-2">
@@ -277,8 +278,8 @@ const PodPanel: React.FC<{ d: JsonData}> = ({ d }) => (
/>
<PodNetworkRank rx={d.netRxTop || []} tx={d.netTxTop || []} />
<div className="grid grid-cols-1 xl:grid-cols-2 gap-4">
<SimpleRank title="Pod CPU Top 10" rows={d.cpuTop || []} valueText={(v) => fmtCores(v, t)} color="bg-purple-500" />
<SimpleRank title={t('monitor.prometheusPanel.podMemTop10')} rows={d.memTop || []} valueText={fmtBytes} color="bg-blue-500" />
<SimpleRank title="Pod CPU Top 10" rows={d.cpuTop || []} valueText={(v) => fmtCores(v)} color="bg-purple-500" />
<SimpleRank title={i18n.t('monitor.prometheusPanel.podMemTop10')} rows={d.memTop || []} valueText={fmtBytes} color="bg-blue-500" />
</div>
</div>
);
@@ -371,7 +372,7 @@ const JvmPanel: React.FC<{ dsUrl?: string; fallback: JsonData }> = ({ dsUrl, fal
<div className="flex items-center gap-2 flex-wrap">
<Select value={application} onValueChange={setApplication}>
<SelectTrigger className="w-[260px] h-8 text-xs dg-input">
<SelectValue placeholder={t('monitor.prometheusPanel.selectApplication')} />
<SelectValue placeholder={i18n.t('monitor.prometheusPanel.selectApplication')} />
</SelectTrigger>
<SelectContent className="dg-input">
{applications.map(app => <SelectItem key={app} value={app}>{app}</SelectItem>)}
@@ -379,13 +380,13 @@ const JvmPanel: React.FC<{ dsUrl?: string; fallback: JsonData }> = ({ dsUrl, fal
</Select>
<Select value={instance} onValueChange={setInstance}>
<SelectTrigger className="w-[280px] h-8 text-xs dg-input">
<SelectValue placeholder={t('monitor.prometheusPanel.selectInstance')} />
<SelectValue placeholder={i18n.t('monitor.prometheusPanel.selectInstance')} />
</SelectTrigger>
<SelectContent className="dg-input">
{instances.map(ins => <SelectItem key={ins} value={ins}>{ins}</SelectItem>)}
</SelectContent>
</Select>
{loading && <span className="text-[11px] text-[var(--dg-text-muted)] inline-flex items-center gap-1"><Loader2 className="w-3 h-3 animate-spin" />{t('monitor.prometheusPanel.loadingJvmMetrics')}</span>}
{loading && <span className="text-[11px] text-[var(--dg-text-muted)] inline-flex items-center gap-1"><Loader2 className="w-3 h-3 animate-spin" />{i18n.t('monitor.prometheusPanel.loadingJvmMetrics')}</span>}
</div>
<div className="grid grid-cols-2 md:grid-cols-3 xl:grid-cols-6 gap-3">
<Card className="bg-[var(--dg-bg-primary)]"><CardContent className="p-3 text-center"><div className="text-lg font-bold">{uptime>86400?`${(uptime/86400).toFixed(1)}d`:`${(uptime/3600).toFixed(1)}h`}</div><div className="text-[10px] text-[var(--dg-text-muted)]">Uptime</div></CardContent></Card>
@@ -420,7 +421,7 @@ export const PrometheusDashboard: React.FC<Props> = ({ dsUrl }) => {
const data: JsonData = await prometheusProxyApi.connect(u);
setConnected(true); setTargets(data.targets||0);
loadAll(u);
} catch (e) { setConnected(false); setError((e as JsonData).message||t('monitor.prometheusPanel.connectionFailed')); }
} catch (e) { setConnected(false); setError((e as JsonData).message||i18n.t('monitor.prometheusPanel.connectionFailed')); }
finally { setLoading(false); }
};
@@ -448,13 +449,13 @@ export const PrometheusDashboard: React.FC<Props> = ({ dsUrl }) => {
<CardHeader className="py-3 px-4 pb-2">
<div className="flex items-center gap-2">
<Activity className="h-4 w-4 dg-text-purple" />
<CardTitle className="text-sm font-medium">{t('monitor.prometheusPanel.prometheusMonitor')}</CardTitle>
<CardTitle className="text-sm font-medium">{i18n.t('monitor.prometheusPanel.prometheusMonitor')}</CardTitle>
{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" />{t('monitor.prometheusPanel.refresh')}</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" />{i18n.t('monitor.prometheusPanel.refresh')}</Button></div>}
</div>
</CardHeader>
<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)]">{t('monitor.prometheusPanel.connecting')}</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)]">{i18n.t('monitor.prometheusPanel.connecting')}</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>)
: (
<Tabs value={tab} onValueChange={setTab}>
@@ -1,5 +1,6 @@
// LogHistogram.tsx — Log Volume 时间分布面积图 // Logan.Li
import { useMemo } from 'react';
import { useTranslation } from 'react-i18next';
import { AreaChart, Area, XAxis, YAxis, CartesianGrid, Tooltip, ResponsiveContainer } from 'recharts';
import type { LogEngine } from './types-v3';
@@ -31,6 +32,7 @@ function formatBytes(bytes: number): string {
}
export function LogHistogram({ data, engine, onBarClick, loading, totalBytes, lineLimitReached, coverage }: LogHistogramProps) {
const { t } = useTranslation();
const colors = ENGINE_COLORS[engine];
const chartData = useMemo(() => {
@@ -111,7 +113,7 @@ export function LogHistogram({ data, engine, onBarClick, loading, totalBytes, li
fontSize: '11px',
color: 'var(--dg-text-primary)',
}}
formatter={(value: number) => [`${value} 条`, 'logs']}
formatter={(value: number) => [`${value} ${t('logCenter.entries')}`, 'logs']}
labelFormatter={(label: string) => {
const item = chartData.find(d => d.label === label);
return item ? item.timestamp : label;
@@ -1,5 +1,6 @@
// QuickQueryHelper.tsx — 快捷查询语法助手 // Logan.Li
import { useState } from 'react';
import { useTranslation } from 'react-i18next';
import { ChevronDown, ChevronUp, Zap } from 'lucide-react';
import type { LogEngine } from './types-v3';
import { QUICK_TEMPLATES } from './types-v3';
@@ -16,6 +17,7 @@ const ENGINE_NAMES: Record<LogEngine, string> = {
};
export function QuickQueryHelper({ engine, onSelect }: Props) {
const { t } = useTranslation();
const [open, setOpen] = useState(false);
const templates = QUICK_TEMPLATES[engine];
@@ -27,7 +29,7 @@ export function QuickQueryHelper({ engine, onSelect }: Props) {
style={{ color: 'var(--dg-blue)', background: open ? 'var(--dg-bg-tertiary)' : 'transparent' }}
>
<Zap className="h-3 w-3" />
快捷查询
{t('logCenter.quickQuery')}
{open ? <ChevronUp className="h-3 w-3" /> : <ChevronDown className="h-3 w-3" />}
</button>
@@ -37,7 +39,7 @@ export function QuickQueryHelper({ engine, onSelect }: Props) {
style={{ background: 'var(--dg-bg-secondary)', borderColor: 'var(--dg-border)' }}
>
<p className="text-[10px] mb-2" style={{ color: 'var(--dg-text-muted)' }}>
{ENGINE_NAMES[engine]} 常用查询模板,点击快速填充
{t('logCenter.quickQueryHint', { engine: ENGINE_NAMES[engine] })}
</p>
<div className="grid grid-cols-2 gap-1.5">
{templates.map((t, i) => (
@@ -1,5 +1,6 @@
// SaveQueryDialog.tsx — 另存为查询 / 另存为告警 // Logan.Li
import { useState } from 'react';
import { useTranslation } from 'react-i18next';
import { X, Save, BellRing, Loader2 } from 'lucide-react';
import { alertApi } from '@/api';
import { useToast } from '@/hooks/use-toast';
@@ -19,6 +20,7 @@ interface SaveQueryProps {
}
export function SaveQueryDialog({ open, onClose, engine, query, timeRange, datasourceId, datasourceName, onSave }: SaveQueryProps) {
const { t } = useTranslation();
const [name, setName] = useState('');
const [saving, setSaving] = useState(false);
const [saved, setSaved] = useState(false);
@@ -47,24 +49,24 @@ export function SaveQueryDialog({ open, onClose, engine, query, timeRange, datas
<div className="fixed inset-0 z-50" style={{ background: 'rgba(0,0,0,0.5)' }} onClick={onClose} />
<div className="fixed left-1/2 top-1/2 -translate-x-1/2 -translate-y-1/2 z-50 w-full max-w-md rounded-lg border shadow-xl overflow-hidden" style={{ background: 'var(--dg-bg-secondary)', borderColor: 'var(--dg-border)' }}>
<div className="flex items-center justify-between px-4 py-3 border-b" style={{ borderColor: 'var(--dg-border)' }}>
<div className="flex items-center gap-2"><Save className="h-4 w-4" style={{ color: 'var(--dg-blue)' }} /><span className="text-sm font-medium" style={{ color: 'var(--dg-text-primary)' }}>另存为查询</span></div>
<div className="flex items-center gap-2"><Save className="h-4 w-4" style={{ color: 'var(--dg-blue)' }} /><span className="text-sm font-medium" style={{ color: 'var(--dg-text-primary)' }}>{t('logCenter.saveQuery')}</span></div>
<button onClick={onClose} className="h-7 w-7 flex items-center justify-center" style={{ color: 'var(--dg-text-muted)' }}><X className="h-4 w-4" /></button>
</div>
<div className="p-4 space-y-3">
<div>
<label className="text-[10px] block mb-1" style={{ color: 'var(--dg-text-muted)' }}>查询名称 *</label>
<input value={name} onChange={e => setName(e.target.value)} placeholder="输入查询名称" className="w-full h-9 px-3 text-xs rounded" style={{ background: 'var(--dg-bg-tertiary)', border: '1px solid var(--dg-border)', color: 'var(--dg-text-primary)' }} />
<label className="text-[10px] block mb-1" style={{ color: 'var(--dg-text-muted)' }}>{t('logCenter.queryName')} *</label>
<input value={name} onChange={e => setName(e.target.value)} placeholder={t('logCenter.queryNamePlaceholder')} className="w-full h-9 px-3 text-xs rounded" style={{ background: 'var(--dg-bg-tertiary)', border: '1px solid var(--dg-border)', color: 'var(--dg-text-primary)' }} />
</div>
<div className="p-2 rounded text-[11px]" style={{ background: 'var(--dg-bg-tertiary)', color: 'var(--dg-text-secondary)' }}>
<span style={{ color: ENGINE_META[engine].color }}>{ENGINE_META[engine].name}</span> · {datasourceName || '默认'}<br />
<span style={{ color: ENGINE_META[engine].color }}>{ENGINE_META[engine].name}</span> · {datasourceName || t('common.default')}<br />
<span className="font-mono">{query}</span><br />
<span style={{ color: 'var(--dg-text-muted)' }}>{timeRange.label} · {timeRange.start} ~ {timeRange.end}</span>
</div>
</div>
<div className="flex items-center justify-end gap-2 px-4 py-3 border-t" style={{ borderColor: 'var(--dg-border)' }}>
<button onClick={onClose} className="h-8 px-3 rounded text-xs" style={{ color: 'var(--dg-text-secondary)', border: '1px solid var(--dg-border)', background: 'var(--dg-bg-tertiary)' }}>取消</button>
<button onClick={onClose} className="h-8 px-3 rounded text-xs" style={{ color: 'var(--dg-text-secondary)', border: '1px solid var(--dg-border)', background: 'var(--dg-bg-tertiary)' }}>{t('common.cancel')}</button>
<button onClick={handleSave} disabled={saving || !name.trim() || saved} className="h-8 px-4 rounded text-xs font-medium text-white flex items-center gap-1" style={{ background: 'var(--dg-blue)' }}>
{saving && <Loader2 className="h-3.5 w-3.5 animate-spin" />}{saved ? '已保存' : '保存'}
{saving && <Loader2 className="h-3.5 w-3.5 animate-spin" />}{saved ? t('common.saved') : t('common.save')}
</button>
</div>
</div>
@@ -84,6 +86,7 @@ interface SaveAlertProps {
}
export function SaveAlertDialog({ open, onClose, engine, query, datasourceId, datasourceName, onSave }: SaveAlertProps) {
const { t } = useTranslation();
const { toast } = useToast();
const [name, setName] = useState('');
const [severity, setSeverity] = useState('warning');
@@ -101,7 +104,7 @@ export function SaveAlertDialog({ open, onClose, engine, query, datasourceId, da
try {
await alertApi.createRule({
name: name.trim(),
description: `从查询页创建: ${datasourceName || '默认数据源'}`,
description: t('logCenter.createFromQuery', { name: datasourceName || t('logCenter.defaultDatasource') }),
type: 'log',
source: engine === 'sls' ? 'loki' : engine,
expression: query.trim(),
@@ -111,11 +114,11 @@ export function SaveAlertDialog({ open, onClose, engine, query, datasourceId, da
notify_channels: [],
});
setSaved(true);
toast({ title: '告警规则已创建' });
toast({ title: t('logCenter.alertRuleCreated') });
onSave?.();
setTimeout(() => { setSaved(false); onClose(); }, 800);
} catch (e: unknown) {
toast({ title: '创建失败', description: getErrorMessage(e), variant: 'destructive' });
toast({ title: t('common.createFailed'), description: getErrorMessage(e), variant: 'destructive' });
} finally {
setSaving(false);
}
@@ -126,35 +129,35 @@ export function SaveAlertDialog({ open, onClose, engine, query, datasourceId, da
<div className="fixed inset-0 z-50" style={{ background: 'rgba(0,0,0,0.5)' }} onClick={onClose} />
<div className="fixed left-1/2 top-1/2 -translate-x-1/2 -translate-y-1/2 z-50 w-full max-w-md rounded-lg border shadow-xl overflow-hidden" style={{ background: 'var(--dg-bg-secondary)', borderColor: 'var(--dg-border)' }}>
<div className="flex items-center justify-between px-4 py-3 border-b" style={{ borderColor: 'var(--dg-border)' }}>
<div className="flex items-center gap-2"><BellRing className="h-4 w-4" style={{ color: '#f59e0b' }} /><span className="text-sm font-medium" style={{ color: 'var(--dg-text-primary)' }}>另存为告警</span></div>
<div className="flex items-center gap-2"><BellRing className="h-4 w-4" style={{ color: '#f59e0b' }} /><span className="text-sm font-medium" style={{ color: 'var(--dg-text-primary)' }}>{t('logCenter.saveAsAlert')}</span></div>
<button onClick={onClose} className="h-7 w-7 flex items-center justify-center" style={{ color: 'var(--dg-text-muted)' }}><X className="h-4 w-4" /></button>
</div>
<div className="p-4 space-y-3">
<div>
<label className="text-[10px] block mb-1" style={{ color: 'var(--dg-text-muted)' }}>告警名称 *</label>
<input value={name} onChange={e => setName(e.target.value)} placeholder="输入告警规则名称" className="w-full h-9 px-3 text-xs rounded" style={{ background: 'var(--dg-bg-tertiary)', border: '1px solid var(--dg-border)', color: 'var(--dg-text-primary)' }} />
<label className="text-[10px] block mb-1" style={{ color: 'var(--dg-text-muted)' }}>{t('logCenter.alertName')} *</label>
<input value={name} onChange={e => setName(e.target.value)} placeholder={t('logCenter.alertNamePlaceholder')} className="w-full h-9 px-3 text-xs rounded" style={{ background: 'var(--dg-bg-tertiary)', border: '1px solid var(--dg-border)', color: 'var(--dg-text-primary)' }} />
</div>
<div className="grid grid-cols-2 gap-3">
<div>
<label className="text-[10px] block mb-1" style={{ color: 'var(--dg-text-muted)' }}>级别</label>
<label className="text-[10px] block mb-1" style={{ color: 'var(--dg-text-muted)' }}>{t('common.severity')}</label>
<select value={severity} onChange={e => setSeverity(e.target.value)} className="w-full h-9 px-2 text-xs rounded" style={{ background: 'var(--dg-bg-tertiary)', border: '1px solid var(--dg-border)', color: 'var(--dg-text-primary)' }}>
<option value="info">提示</option><option value="warning">警告</option><option value="critical">严重</option>
<option value="info">{t('common.info')}</option><option value="warning">{t('common.warning')}</option><option value="critical">{t('common.critical')}</option>
</select>
</div>
<div>
<label className="text-[10px] block mb-1" style={{ color: 'var(--dg-text-muted)' }}>触发条件</label>
<label className="text-[10px] block mb-1" style={{ color: 'var(--dg-text-muted)' }}>{t('logCenter.triggerCondition')}</label>
<input value={condition} onChange={e => setCondition(e.target.value)} className="w-full h-9 px-2 text-xs rounded" style={{ background: 'var(--dg-bg-tertiary)', border: '1px solid var(--dg-border)', color: 'var(--dg-text-primary)' }} />
</div>
</div>
<div className="p-2 rounded text-[11px]" style={{ background: 'var(--dg-bg-tertiary)', color: 'var(--dg-text-secondary)' }}>
<span style={{ color: meta.color }}>{meta.name}</span> · {datasourceName || '默认'}<br />
<span style={{ color: meta.color }}>{meta.name}</span> · {datasourceName || t('common.default')}<br />
<span className="font-mono">{query}</span>
</div>
</div>
<div className="flex items-center justify-end gap-2 px-4 py-3 border-t" style={{ borderColor: 'var(--dg-border)' }}>
<button onClick={onClose} className="h-8 px-3 rounded text-xs" style={{ color: 'var(--dg-text-secondary)', border: '1px solid var(--dg-border)', background: 'var(--dg-bg-tertiary)' }}>取消</button>
<button onClick={onClose} className="h-8 px-3 rounded text-xs" style={{ color: 'var(--dg-text-secondary)', border: '1px solid var(--dg-border)', background: 'var(--dg-bg-tertiary)' }}>{t('common.cancel')}</button>
<button onClick={handleSave} disabled={saving || !name.trim() || saved} className="h-8 px-4 rounded text-xs font-medium text-white flex items-center gap-1" style={{ background: '#f59e0b' }}>
{saving && <Loader2 className="h-3.5 w-3.5 animate-spin" />}{saved ? '已创建' : '创建告警'}
{saving && <Loader2 className="h-3.5 w-3.5 animate-spin" />}{saved ? t('common.created') : t('logCenter.createAlert')}
</button>
</div>
</div>
@@ -431,8 +431,8 @@ export function UnifiedQueryPanel({ engine, onRuleCreated }: Props) {
const formatEntryLine = useCallback((e: LogEntry) => buildLogCopyText(e), []);
const handleExportLogs = useCallback(() => {
const t = sortedEntries.map(formatEntryLine).join('\n');
const b = new Blob([t], { type: 'text/plain;charset=utf-8' });
const text = sortedEntries.map(formatEntryLine).join('\n');
const b = new Blob([text], { type: 'text/plain;charset=utf-8' });
const u = URL.createObjectURL(b);
const a = document.createElement('a');
a.href = u;