feat: opsx-loki 全面升级 — 前端重构/用户与LDAP/部署向导/日志查询
基于 WEB-UI-Development-Guide 标准的整体升级,并更名 LokiDeploy → opsx-loki。 前端(Gin+React+shadcn/ui): - 按 02/07 章重构:页面域化拆分(无超 400 行文件)、PageContainer/ListQuery、 反馈分级(成功静默/失败 toast/危险确认)、401 单飞刷新+队列重放 - 暗色模式(next-themes)+ 语义 Token(--primary 品牌色/success/warning/info) - 部署向导(状态推导四步:环境→存储→Loki→采集,内嵌表单闭环) - 日志查询页:LogQL 标签构建器/拖拽直方图/日志上下文/Live Tail/查询历史 - 按用户+标签策略的查询授权(服务端强制合并策略) 后端(Go+Gin+JSON DB): - 简单用户管理(仅 admin,无 RBAC)+ TokenVersion 会话吊销 + 登录 IP 限流 - LDAP 接入:配置(AES 加密存储/hasPassword 脱敏)/测试连接/批量导入/登录 - 存储配置测试连接(SigV4 零依赖)+ 桶不存在自动创建 - Loki 三模式部署修复:SSH 密钥认证、3.x 配置模板、ruler 对象存储嵌套块、 凭证解密、孤儿 deploying 状态恢复、Grafana 部署(可选默认关)+面板导入 - DaemonSet 采集纯 YAML(去 helm 依赖)+ DNS 自愈回退 ClusterIP + 集群名标签 - 日志查询代理:cluster-svc 经 kube-apiserver proxy/url 直连 + cursor 翻页 - 统一 log 命名空间;部署就绪探活;Grafana 访问地址自动记录 修复:run.sh 增量编译检测、Sanitized 脱敏补全、LokiDeployment Update 白名单、 健康检查 CreatedAt 零值等 10+ 存量 bug。 数据兼容:DB 沿用旧 lokideploy.json(新名优先);localStorage 一次性迁移; HKDF 加密前缀保留(已加密凭证不受影响)。
This commit is contained in:
1 parent
327e282356
commit
f9c6c1d826
204 files changed
+14107
-9103
No files matched your search
@@ -0,0 +1,97 @@
|
||||
import { memo } from 'react'
|
||||
import { Monitor, RefreshCw, Trash2, Eye, Terminal } from 'lucide-react'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { Card, CardContent } from '@/components/ui/card'
|
||||
import { StatusBadge } from '@/components/StatusBadge'
|
||||
import { InfoRow } from '@/components/InfoRow'
|
||||
import type { Host } from '@/types'
|
||||
|
||||
interface HostCardProps {
|
||||
host: Host
|
||||
validating: number | null
|
||||
onViewInfo: (h: Host) => void
|
||||
onOpenTerminal: (h: Host) => void
|
||||
onValidate: (id: number) => void
|
||||
onDelete: (h: Host) => void
|
||||
}
|
||||
|
||||
/** 主机卡片 — 列表项展示与操作入口(删除传整个对象,供确认弹窗展示名称) */
|
||||
export const HostCard = memo(function HostCard({
|
||||
host,
|
||||
validating,
|
||||
onViewInfo,
|
||||
onOpenTerminal,
|
||||
onValidate,
|
||||
onDelete,
|
||||
}: HostCardProps) {
|
||||
return (
|
||||
<Card className="border-border hover:shadow-md transition-shadow">
|
||||
<CardContent className="p-5">
|
||||
<div className="flex items-start justify-between mb-3">
|
||||
<div className="flex items-center gap-2 min-w-0">
|
||||
<Monitor className="w-5 h-5 text-purple-500 flex-shrink-0" />
|
||||
<h3 className="font-semibold text-foreground truncate">
|
||||
{host.name}
|
||||
</h3>
|
||||
</div>
|
||||
<StatusBadge status={host.status} />
|
||||
</div>
|
||||
|
||||
<div className="space-y-1.5 text-xs text-muted-foreground mb-4">
|
||||
<InfoRow label="IP 地址" value={`${host.hostIP}:${host.port}`} />
|
||||
<InfoRow label="用户名" value={host.user} />
|
||||
<InfoRow
|
||||
label="认证方式"
|
||||
value={host.authType === 'key' ? 'SSH 密钥' : '密码'}
|
||||
/>
|
||||
<InfoRow
|
||||
label="系统"
|
||||
value={`${host.os || '未知'} (${host.arch || '未知'})`}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="flex gap-2 pt-3 border-t border-border">
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
className="flex-1 text-xs"
|
||||
onClick={() => onViewInfo(host)}
|
||||
>
|
||||
<Eye className="w-3 h-3 mr-1" />
|
||||
详情
|
||||
</Button>
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
className="flex-1 text-xs"
|
||||
onClick={() => onOpenTerminal(host)}
|
||||
>
|
||||
<Terminal className="w-3 h-3 mr-1" />
|
||||
终端
|
||||
</Button>
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
aria-label={`验证主机 ${host.name}`}
|
||||
className="text-xs"
|
||||
onClick={() => onValidate(host.id)}
|
||||
disabled={validating === host.id}
|
||||
>
|
||||
<RefreshCw
|
||||
className={`w-3 h-3 ${validating === host.id ? 'animate-spin' : ''}`}
|
||||
/>
|
||||
</Button>
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
aria-label={`删除主机 ${host.name}`}
|
||||
className="text-destructive hover:text-destructive hover:bg-destructive/10"
|
||||
onClick={() => onDelete(host)}
|
||||
>
|
||||
<Trash2 className="w-3 h-3" />
|
||||
</Button>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
)
|
||||
})
|
||||
@@ -0,0 +1,149 @@
|
||||
import { memo, useEffect, useState } from 'react'
|
||||
import { Monitor } from 'lucide-react'
|
||||
import {
|
||||
Dialog,
|
||||
DialogContent,
|
||||
DialogHeader,
|
||||
DialogTitle,
|
||||
} from '@/components/ui/dialog'
|
||||
import { hostApi } from '@/api'
|
||||
import { LoadingSpinner } from '@/components/LoadingSpinner'
|
||||
import { ErrorState } from '@/components/ErrorState'
|
||||
import type { Host, HostInfo } from '@/types'
|
||||
|
||||
// 使用率颜色阈值
|
||||
const usageColor = (v: number) =>
|
||||
v >= 90 ? 'bg-destructive' : v >= 70 ? 'bg-warning' : 'bg-success'
|
||||
|
||||
interface HostDetailDialogProps {
|
||||
host: Host | null
|
||||
onClose: () => void
|
||||
}
|
||||
|
||||
/** 主机详情弹窗 — 自负责拉取主机信息(打开即加载,失败渲染 ErrorState 可重开重试) */
|
||||
export const HostDetailDialog = memo(function HostDetailDialog({
|
||||
host,
|
||||
onClose,
|
||||
}: HostDetailDialogProps) {
|
||||
const [info, setInfo] = useState<HostInfo | null>(null)
|
||||
const [error, setError] = useState<string | null>(null)
|
||||
|
||||
useEffect(() => {
|
||||
if (!host) return
|
||||
let cancelled = false
|
||||
hostApi
|
||||
.getInfo(host.id)
|
||||
.then((data) => {
|
||||
if (!cancelled) setInfo(data)
|
||||
})
|
||||
.catch((err) => {
|
||||
if (!cancelled) setError(err instanceof Error ? err.message : '加载主机详情失败')
|
||||
})
|
||||
return () => {
|
||||
cancelled = true
|
||||
}
|
||||
}, [host])
|
||||
|
||||
return (
|
||||
<Dialog open={host !== null} onOpenChange={(open) => !open && onClose()}>
|
||||
<DialogContent className="max-w-2xl max-h-[90vh] overflow-y-auto">
|
||||
<DialogHeader>
|
||||
<DialogTitle className="flex items-center gap-2">
|
||||
<Monitor className="w-5 h-5 text-purple-500" />
|
||||
{host?.name}
|
||||
</DialogTitle>
|
||||
</DialogHeader>
|
||||
|
||||
{error ? (
|
||||
<ErrorState message={error} />
|
||||
) : info ? (
|
||||
<HostDetail info={info} />
|
||||
) : (
|
||||
<LoadingSpinner className="h-32" />
|
||||
)}
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
)
|
||||
})
|
||||
|
||||
/** 主机详情内容:资源使用率 + 基本信息 */
|
||||
const HostDetail = memo(function HostDetail({ info }: { info: HostInfo }) {
|
||||
return (
|
||||
<div className="space-y-5">
|
||||
{/* 资源使用率 */}
|
||||
<div>
|
||||
<h4 className="text-sm font-semibold mb-3">资源使用率</h4>
|
||||
<div className="space-y-3">
|
||||
<UsageBar label="CPU" value={info.cpuUsage} />
|
||||
<UsageBar
|
||||
label="内存"
|
||||
value={info.memUsage}
|
||||
detail={`${info.memUsed} / ${info.memTotal}`}
|
||||
/>
|
||||
<UsageBar
|
||||
label="磁盘"
|
||||
value={info.diskUsage}
|
||||
detail={`${info.diskUsed} / ${info.diskTotal}`}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* 基本信息 */}
|
||||
<div>
|
||||
<h4 className="text-sm font-semibold mb-3">基本信息</h4>
|
||||
<div className="grid grid-cols-2 gap-3">
|
||||
<InfoCard label="主机名" value={info.hostname || '未知'} />
|
||||
<InfoCard label="系统" value={`${info.os || '未知'} ${info.version}`} />
|
||||
<InfoCard label="架构" value={info.arch || '未知'} />
|
||||
<InfoCard label="内核" value={info.kernel || '未知'} />
|
||||
<InfoCard label="CPU 核数" value={info.cpu || '未知'} />
|
||||
<InfoCard label="运行时长" value={info.uptime || '未知'} />
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
})
|
||||
|
||||
// 使用率进度条
|
||||
const UsageBar = memo(function UsageBar({
|
||||
label,
|
||||
value,
|
||||
detail,
|
||||
}: {
|
||||
label: string
|
||||
value: number
|
||||
detail?: string
|
||||
}) {
|
||||
return (
|
||||
<div>
|
||||
<div className="flex justify-between text-xs mb-1">
|
||||
<span className="text-muted-foreground">{label}</span>
|
||||
<span className="font-medium">
|
||||
{value.toFixed(1)}% {detail && `(${detail})`}
|
||||
</span>
|
||||
</div>
|
||||
<div className="h-2 bg-slate-200 dark:bg-slate-700 rounded-full overflow-hidden">
|
||||
<div
|
||||
className={`h-full ${usageColor(value)} rounded-full transition-all`}
|
||||
style={{ width: `${Math.min(value, 100)}%` }}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
})
|
||||
|
||||
// 信息卡片
|
||||
const InfoCard = memo(function InfoCard({
|
||||
label,
|
||||
value,
|
||||
}: {
|
||||
label: string
|
||||
value: string
|
||||
}) {
|
||||
return (
|
||||
<div className="p-2.5 bg-muted rounded-lg">
|
||||
<p className="text-xs text-muted-foreground">{label}</p>
|
||||
<p className="text-sm font-medium truncate">{value}</p>
|
||||
</div>
|
||||
)
|
||||
})
|
||||
@@ -0,0 +1,304 @@
|
||||
import { memo, useEffect, useState } from 'react'
|
||||
import { useForm } from 'react-hook-form'
|
||||
import { zodResolver } from '@hookform/resolvers/zod'
|
||||
import { z } from 'zod'
|
||||
import { Key, Lock } from 'lucide-react'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { Input } from '@/components/ui/input'
|
||||
import { Textarea } from '@/components/ui/textarea'
|
||||
import {
|
||||
Dialog,
|
||||
DialogContent,
|
||||
DialogHeader,
|
||||
DialogTitle,
|
||||
} from '@/components/ui/dialog'
|
||||
import {
|
||||
Form,
|
||||
FormControl,
|
||||
FormField,
|
||||
FormItem,
|
||||
FormLabel,
|
||||
FormMessage,
|
||||
} from '@/components/ui/form'
|
||||
import { hostApi } from '@/api'
|
||||
import { PasswordInput } from '@/components/PasswordInput'
|
||||
import { toast } from 'sonner'
|
||||
|
||||
// 表单 schema:zod 为唯一校验源,消息中文且具体
|
||||
// (port 在表单内为字符串、提交时转数字,避免 z.coerce 输入/输出类型分叉导致 RHF 泛型不兼容)
|
||||
const hostFormSchema = z
|
||||
.object({
|
||||
name: z.string().min(1, '请输入主机名称'),
|
||||
hostIP: z.string().min(1, '请输入主机 IP'),
|
||||
port: z
|
||||
.string()
|
||||
.min(1, '请输入端口')
|
||||
.regex(/^\d+$/, '端口必须为数字')
|
||||
.refine((v) => Number(v) >= 1 && Number(v) <= 65535, '端口必须在 1-65535 之间'),
|
||||
user: z.string().min(1, '请输入用户名'),
|
||||
authType: z.enum(['password', 'key']),
|
||||
password: z.string().optional(),
|
||||
privateKey: z.string().optional(),
|
||||
keyPhrase: z.string().optional(),
|
||||
labels: z.string().optional(),
|
||||
})
|
||||
.superRefine((data, ctx) => {
|
||||
if (data.authType === 'password' && !data.password?.trim()) {
|
||||
ctx.addIssue({
|
||||
code: 'custom',
|
||||
path: ['password'],
|
||||
message: '请填写 SSH 登录密码',
|
||||
})
|
||||
}
|
||||
if (data.authType === 'key' && !data.privateKey?.trim()) {
|
||||
ctx.addIssue({
|
||||
code: 'custom',
|
||||
path: ['privateKey'],
|
||||
message: '请粘贴 SSH 私钥内容',
|
||||
})
|
||||
}
|
||||
})
|
||||
|
||||
type HostFormValues = z.infer<typeof hostFormSchema>
|
||||
|
||||
const DEFAULT_VALUES: HostFormValues = {
|
||||
name: '',
|
||||
hostIP: '',
|
||||
port: '22',
|
||||
user: 'root',
|
||||
authType: 'password',
|
||||
password: '',
|
||||
privateKey: '',
|
||||
keyPhrase: '',
|
||||
labels: '',
|
||||
}
|
||||
|
||||
interface HostFormDialogProps {
|
||||
open: boolean
|
||||
onOpenChange: (open: boolean) => void
|
||||
/** 创建成功回调(父级刷新列表并关闭弹窗) */
|
||||
onCreated: () => void
|
||||
}
|
||||
|
||||
/** 添加 SSH 主机弹窗 — react-hook-form + zod,自包含表单逻辑,页面只传开关与回调 */
|
||||
export const HostFormDialog = memo(function HostFormDialog({
|
||||
open,
|
||||
onOpenChange,
|
||||
onCreated,
|
||||
}: HostFormDialogProps) {
|
||||
const [submitting, setSubmitting] = useState(false)
|
||||
|
||||
const form = useForm<HostFormValues>({
|
||||
resolver: zodResolver(hostFormSchema),
|
||||
defaultValues: DEFAULT_VALUES,
|
||||
})
|
||||
const authType = form.watch('authType')
|
||||
|
||||
// 打开时重置(默认值),关闭/重开时机明确
|
||||
useEffect(() => {
|
||||
if (open) {
|
||||
form.reset(DEFAULT_VALUES)
|
||||
}
|
||||
}, [open, form])
|
||||
|
||||
const onSubmit = form.handleSubmit(async (values) => {
|
||||
setSubmitting(true)
|
||||
try {
|
||||
await hostApi.create({
|
||||
name: values.name,
|
||||
hostIP: values.hostIP,
|
||||
port: Number(values.port),
|
||||
user: values.user,
|
||||
authType: values.authType,
|
||||
password: values.authType === 'password' ? values.password : undefined,
|
||||
privateKey: values.authType === 'key' ? values.privateKey : undefined,
|
||||
keyPhrase: values.authType === 'key' ? values.keyPhrase : undefined,
|
||||
labels: values.labels,
|
||||
})
|
||||
onOpenChange(false)
|
||||
onCreated()
|
||||
} catch (err) {
|
||||
toast.error(err instanceof Error ? err.message : '添加主机失败')
|
||||
} finally {
|
||||
setSubmitting(false)
|
||||
}
|
||||
})
|
||||
|
||||
return (
|
||||
<Dialog open={open} onOpenChange={onOpenChange}>
|
||||
<DialogContent className="max-w-2xl max-h-[90vh] overflow-y-auto">
|
||||
<DialogHeader>
|
||||
<DialogTitle>添加 SSH 主机</DialogTitle>
|
||||
</DialogHeader>
|
||||
<Form {...form}>
|
||||
<form onSubmit={onSubmit} className="space-y-4">
|
||||
<div className="grid grid-cols-2 gap-4">
|
||||
<FormField
|
||||
control={form.control}
|
||||
name="name"
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>名称 *</FormLabel>
|
||||
<FormControl>
|
||||
<Input placeholder="loki-server-1" {...field} />
|
||||
</FormControl>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
<FormField
|
||||
control={form.control}
|
||||
name="hostIP"
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>主机 IP *</FormLabel>
|
||||
<FormControl>
|
||||
<Input placeholder="192.168.1.100" {...field} />
|
||||
</FormControl>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
</div>
|
||||
<div className="grid grid-cols-2 gap-4">
|
||||
<FormField
|
||||
control={form.control}
|
||||
name="port"
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>端口</FormLabel>
|
||||
<FormControl>
|
||||
<Input type="number" placeholder="22" {...field} />
|
||||
</FormControl>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
<FormField
|
||||
control={form.control}
|
||||
name="user"
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>用户名 *</FormLabel>
|
||||
<FormControl>
|
||||
<Input placeholder="root" {...field} />
|
||||
</FormControl>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<FormField
|
||||
control={form.control}
|
||||
name="authType"
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>认证方式</FormLabel>
|
||||
<FormControl>
|
||||
<div className="flex gap-4">
|
||||
<label className="flex items-center gap-2 cursor-pointer">
|
||||
<input
|
||||
type="radio"
|
||||
name="authType"
|
||||
value="password"
|
||||
checked={field.value === 'password'}
|
||||
onChange={() => field.onChange('password')}
|
||||
/>
|
||||
<Lock className="w-4 h-4" />
|
||||
<span className="text-sm">密码</span>
|
||||
</label>
|
||||
<label className="flex items-center gap-2 cursor-pointer">
|
||||
<input
|
||||
type="radio"
|
||||
name="authType"
|
||||
value="key"
|
||||
checked={field.value === 'key'}
|
||||
onChange={() => field.onChange('key')}
|
||||
/>
|
||||
<Key className="w-4 h-4" />
|
||||
<span className="text-sm">SSH 密钥</span>
|
||||
</label>
|
||||
</div>
|
||||
</FormControl>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
|
||||
{authType === 'password' ? (
|
||||
<FormField
|
||||
control={form.control}
|
||||
name="password"
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>密码 *</FormLabel>
|
||||
<FormControl>
|
||||
<PasswordInput placeholder="SSH 登录密码" {...field} />
|
||||
</FormControl>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
) : (
|
||||
<>
|
||||
<FormField
|
||||
control={form.control}
|
||||
name="privateKey"
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>私钥 *</FormLabel>
|
||||
<FormControl>
|
||||
<Textarea
|
||||
placeholder="-----BEGIN OPENSSH PRIVATE KEY-----"
|
||||
className="min-h-[120px] font-mono text-xs"
|
||||
{...field}
|
||||
/>
|
||||
</FormControl>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
<FormField
|
||||
control={form.control}
|
||||
name="keyPhrase"
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>密钥口令(可选)</FormLabel>
|
||||
<FormControl>
|
||||
<PasswordInput placeholder="无口令则留空" {...field} />
|
||||
</FormControl>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
</>
|
||||
)}
|
||||
|
||||
<FormField
|
||||
control={form.control}
|
||||
name="labels"
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>标签(JSON)</FormLabel>
|
||||
<FormControl>
|
||||
<Input placeholder='["loki", "logging"]' {...field} />
|
||||
</FormControl>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
|
||||
<Button
|
||||
type="submit"
|
||||
className="w-full bg-primary hover:bg-primary/90"
|
||||
disabled={submitting}
|
||||
>
|
||||
{submitting ? '添加中...' : '添加主机'}
|
||||
</Button>
|
||||
</form>
|
||||
</Form>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
)
|
||||
})
|
||||
@@ -0,0 +1,86 @@
|
||||
import { memo, useEffect, useState } from 'react'
|
||||
import { Terminal } from 'lucide-react'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { Input } from '@/components/ui/input'
|
||||
import {
|
||||
Dialog,
|
||||
DialogContent,
|
||||
DialogHeader,
|
||||
DialogTitle,
|
||||
} from '@/components/ui/dialog'
|
||||
import { hostApi } from '@/api'
|
||||
import type { Host } from '@/types'
|
||||
|
||||
interface TerminalDialogProps {
|
||||
host: Host | null
|
||||
onClose: () => void
|
||||
}
|
||||
|
||||
/** 命令执行终端弹窗 — 打开即初始化欢迎输出,命令执行与输出渲染自包含 */
|
||||
export const TerminalDialog = memo(function TerminalDialog({
|
||||
host,
|
||||
onClose,
|
||||
}: TerminalDialogProps) {
|
||||
const [command, setCommand] = useState('')
|
||||
const [output, setOutput] = useState('')
|
||||
const [executing, setExecuting] = useState(false)
|
||||
|
||||
// 切换主机/重新打开时重置终端
|
||||
useEffect(() => {
|
||||
if (host) {
|
||||
setCommand('')
|
||||
setOutput(`已连接到 ${host.name} (${host.hostIP})\n输入命令后按"执行"...\n`)
|
||||
}
|
||||
}, [host])
|
||||
|
||||
const executeCommand = async () => {
|
||||
if (!host || !command.trim() || executing) return
|
||||
setExecuting(true)
|
||||
setOutput((prev) => prev + `\n$ ${command}\n`)
|
||||
try {
|
||||
const res = await hostApi.execute(host.id, command)
|
||||
setOutput((prev) => prev + (res.stdout || '') + (res.stderr || '') + '\n')
|
||||
} catch (err) {
|
||||
const message = err instanceof Error ? err.message : '命令执行失败'
|
||||
setOutput((prev) => prev + `错误:${message}\n`)
|
||||
} finally {
|
||||
setExecuting(false)
|
||||
setCommand('')
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<Dialog open={host !== null} onOpenChange={(open) => !open && onClose()}>
|
||||
<DialogContent className="max-w-4xl">
|
||||
<DialogHeader>
|
||||
<DialogTitle className="flex items-center gap-2">
|
||||
<Terminal className="w-5 h-5 text-primary" />
|
||||
终端 - {host?.name}
|
||||
</DialogTitle>
|
||||
</DialogHeader>
|
||||
<div className="space-y-4">
|
||||
<div className="bg-card dark:bg-card text-green-400 font-mono text-xs p-4 rounded-lg h-80 overflow-auto whitespace-pre-wrap">
|
||||
{output}
|
||||
</div>
|
||||
<div className="flex gap-2">
|
||||
<Input
|
||||
value={command}
|
||||
onChange={(e) => setCommand(e.target.value)}
|
||||
onKeyDown={(e) => e.key === 'Enter' && executeCommand()}
|
||||
placeholder="输入命令..."
|
||||
className="flex-1 font-mono text-sm"
|
||||
disabled={executing}
|
||||
/>
|
||||
<Button
|
||||
onClick={executeCommand}
|
||||
disabled={executing || !command.trim()}
|
||||
className="bg-primary hover:bg-primary/90"
|
||||
>
|
||||
{executing ? '执行中...' : '执行'}
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
)
|
||||
})
|
||||
@@ -0,0 +1,171 @@
|
||||
import { memo, useCallback, useEffect, useRef, useState } from 'react'
|
||||
import { Monitor, Plus } from 'lucide-react'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { hostApi, deploymentApi, collectorApi } from '@/api'
|
||||
import { PageContainer } from '@/components/PageContainer'
|
||||
import { LoadingSpinner } from '@/components/LoadingSpinner'
|
||||
import { EmptyState } from '@/components/EmptyState'
|
||||
import { ErrorState } from '@/components/ErrorState'
|
||||
import { PaginationBar } from '@/components/PaginationBar'
|
||||
import { ConfirmDialog } from '@/components/ConfirmDialog'
|
||||
import { toast } from 'sonner'
|
||||
import { useListQuery } from '@/hooks/useListQuery'
|
||||
import type { Host } from '@/types'
|
||||
import { HostCard } from './components/HostCard'
|
||||
import { HostFormDialog } from './components/HostFormDialog'
|
||||
import { HostDetailDialog } from './components/HostDetailDialog'
|
||||
import { TerminalDialog } from './components/TerminalDialog'
|
||||
|
||||
/**
|
||||
* 主机管理页 — 只做编排:数据走 useListQuery(取消+版本号),
|
||||
* 卡片/表单/详情/终端/删除确认均为域内子组件。成功操作静默(列表刷新即反馈)。
|
||||
*/
|
||||
const HostsPage = memo(function HostsPage() {
|
||||
const query = useListQuery<Host>((params, signal) =>
|
||||
hostApi.list(params, { signal })
|
||||
)
|
||||
|
||||
const [formOpen, setFormOpen] = useState(false)
|
||||
const [detailHost, setDetailHost] = useState<Host | null>(null)
|
||||
const [terminalHost, setTerminalHost] = useState<Host | null>(null)
|
||||
const [deleteTarget, setDeleteTarget] = useState<Host | null>(null)
|
||||
const [deleting, setDeleting] = useState(false)
|
||||
const [validating, setValidating] = useState<number | null>(null)
|
||||
|
||||
// 验证后延时刷新列表的定时器(卸载清理)
|
||||
const timeoutsRef = useRef<ReturnType<typeof setTimeout>[]>([])
|
||||
useEffect(() => {
|
||||
const timers = timeoutsRef.current
|
||||
return () => {
|
||||
timers.forEach((id) => clearTimeout(id))
|
||||
}
|
||||
}, [])
|
||||
|
||||
const [refCount, setRefCount] = useState<{ dep: number; col: number }>({ dep: 0, col: 0 })
|
||||
useEffect(() => {
|
||||
if (!deleteTarget) return
|
||||
Promise.all([
|
||||
deploymentApi.list({ page: 1, pageSize: 100 }),
|
||||
collectorApi.list({ page: 1, pageSize: 100 }),
|
||||
]).then(([d, c]) => {
|
||||
setRefCount({
|
||||
dep: d.list.filter((x) => x.hostID === deleteTarget.id).length,
|
||||
col: c.list.filter((x) => x.hostID === deleteTarget.id).length,
|
||||
})
|
||||
}).catch(() => setRefCount({ dep: 0, col: 0 }))
|
||||
}, [deleteTarget])
|
||||
|
||||
const handleDelete = useCallback(async () => {
|
||||
const id = deleteTarget?.id
|
||||
if (!id) return
|
||||
setDeleting(true)
|
||||
try {
|
||||
await hostApi.remove(id)
|
||||
setDeleteTarget(null)
|
||||
query.refresh()
|
||||
} catch (err) {
|
||||
toast.error(err instanceof Error ? err.message : '删除主机失败')
|
||||
} finally {
|
||||
setDeleting(false)
|
||||
}
|
||||
}, [deleteTarget, query])
|
||||
|
||||
const handleValidate = useCallback(
|
||||
async (id: number) => {
|
||||
setValidating(id)
|
||||
try {
|
||||
await hostApi.validate(id)
|
||||
timeoutsRef.current.push(setTimeout(() => query.refresh(), 3000))
|
||||
} catch (err) {
|
||||
toast.error(err instanceof Error ? err.message : '验证失败')
|
||||
} finally {
|
||||
timeoutsRef.current.push(setTimeout(() => setValidating(null), 3000))
|
||||
}
|
||||
},
|
||||
[query]
|
||||
)
|
||||
|
||||
return (
|
||||
<PageContainer
|
||||
title="主机管理"
|
||||
description="管理用于二进制方式部署 Loki 的 SSH 主机"
|
||||
action={
|
||||
<Button
|
||||
className="bg-primary hover:bg-primary/90"
|
||||
onClick={() => setFormOpen(true)}
|
||||
>
|
||||
<Plus className="w-4 h-4 mr-1" />
|
||||
添加主机
|
||||
</Button>
|
||||
}
|
||||
>
|
||||
{query.loading ? (
|
||||
<LoadingSpinner className="h-64" />
|
||||
) : query.error ? (
|
||||
<ErrorState message={query.error} onRetry={query.refresh} />
|
||||
) : query.list.length === 0 ? (
|
||||
<EmptyState
|
||||
icon={Monitor}
|
||||
title="暂无主机"
|
||||
description="添加第一台 SSH 主机开始使用"
|
||||
/>
|
||||
) : (
|
||||
<>
|
||||
<div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
|
||||
{query.list.map((host) => (
|
||||
<HostCard
|
||||
key={host.id}
|
||||
host={host}
|
||||
validating={validating}
|
||||
onViewInfo={setDetailHost}
|
||||
onOpenTerminal={setTerminalHost}
|
||||
onValidate={handleValidate}
|
||||
onDelete={setDeleteTarget}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
<PaginationBar
|
||||
page={query.page}
|
||||
pageSize={query.pageSize}
|
||||
total={query.total}
|
||||
onPageChange={query.setPage}
|
||||
/>
|
||||
</>
|
||||
)}
|
||||
|
||||
<HostFormDialog
|
||||
open={formOpen}
|
||||
onOpenChange={setFormOpen}
|
||||
onCreated={query.reload}
|
||||
/>
|
||||
|
||||
<HostDetailDialog
|
||||
key={detailHost?.id ?? 'none'}
|
||||
host={detailHost}
|
||||
onClose={() => setDetailHost(null)}
|
||||
/>
|
||||
|
||||
<TerminalDialog
|
||||
host={terminalHost}
|
||||
onClose={() => setTerminalHost(null)}
|
||||
/>
|
||||
|
||||
<ConfirmDialog
|
||||
open={deleteTarget !== null}
|
||||
onOpenChange={(open) => {
|
||||
if (!open) setDeleteTarget(null)
|
||||
}}
|
||||
name={deleteTarget?.name}
|
||||
loading={deleting}
|
||||
description={
|
||||
refCount.dep + refCount.col > 0
|
||||
? `确定要删除「${deleteTarget?.name}」吗?警告:仍有 ${refCount.dep} 个部署、${refCount.col} 个采集策略引用该主机,删除后它们将无法工作。`
|
||||
: undefined
|
||||
}
|
||||
onConfirm={handleDelete}
|
||||
/>
|
||||
</PageContainer>
|
||||
)
|
||||
})
|
||||
|
||||
export default HostsPage
|
||||
Reference in new issue
Block a user