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:
logan committed 2026-10-24 13:20:12 +08:00
1 parent 327e282356
commit f9c6c1d826
204 files changed
+14107 -9103

No files matched your search

@@ -0,0 +1,101 @@
import { memo } from 'react'
import { Server, RefreshCw, Trash2, Eye } 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 { Cluster } from '@/types'
interface ClusterCardProps {
cluster: Cluster
validating: number | null
onViewInfo: (c: Cluster) => void
onValidate: (id: number) => void
onDelete: (c: Cluster) => void
}
/** 集群卡片 — 列表项展示与操作入口 */
export const ClusterCard = memo(function ClusterCard({
cluster,
validating,
onViewInfo,
onValidate,
onDelete,
}: ClusterCardProps) {
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">
<Server className="w-5 h-5 text-info flex-shrink-0" />
<h3 className="font-semibold text-foreground truncate">
{cluster.name}
</h3>
</div>
<StatusBadge status={cluster.status} />
</div>
<p className="text-sm text-muted-foreground mb-3 line-clamp-2">
{cluster.description || '无描述'}
</p>
<div className="space-y-1.5 text-xs text-muted-foreground mb-4">
<InfoRow
label="接入方式"
value={cluster.configType === 'token' ? 'Token' : 'Kubeconfig'}
/>
{cluster.apiServer && (
<InfoRow
label="API Server"
value={cluster.apiServer}
valueClass="truncate max-w-[150px]"
/>
)}
<InfoRow label="版本" value={cluster.version || '未知'} />
<InfoRow label="节点数" value={String(cluster.nodesCount || 0)} />
<InfoRow
label="最后连接"
value={
cluster.lastConnected
? new Date(cluster.lastConnected).toLocaleString()
: '从未'
}
/>
</div>
<div className="flex gap-2 pt-3 border-t border-border">
<Button
variant="outline"
size="sm"
className="flex-1 text-xs"
onClick={() => onViewInfo(cluster)}
>
<Eye className="w-3 h-3 mr-1" />
详情
</Button>
<Button
variant="outline"
size="sm"
className="flex-1 text-xs"
onClick={() => onValidate(cluster.id)}
disabled={validating === cluster.id}
>
<RefreshCw
className={`w-3 h-3 mr-1 ${validating === cluster.id ? 'animate-spin' : ''}`}
/>
验证
</Button>
<Button
variant="outline"
size="sm"
aria-label={`删除集群 ${cluster.name}`}
className="text-destructive hover:text-destructive hover:bg-destructive/10"
onClick={() => onDelete(cluster)}
>
<Trash2 className="w-3 h-3" />
</Button>
</div>
</CardContent>
</Card>
)
})
@@ -0,0 +1,137 @@
import { memo, useEffect, useState } from 'react'
import { Server } from 'lucide-react'
import {
Dialog,
DialogContent,
DialogHeader,
DialogTitle,
} from '@/components/ui/dialog'
import { clusterApi } from '@/api'
import { LoadingSpinner } from '@/components/LoadingSpinner'
import { ErrorState } from '@/components/ErrorState'
import type { Cluster, ClusterInfo } from '@/types'
interface ClusterDetailDialogProps {
cluster: Cluster | null
onClose: () => void
}
/** 集群详情弹窗 — 自负责拉取集群信息(打开即加载,卸载取消语义由加载态覆盖) */
export const ClusterDetailDialog = memo(function ClusterDetailDialog({
cluster,
onClose,
}: ClusterDetailDialogProps) {
const [info, setInfo] = useState<ClusterInfo | null>(null)
const [error, setError] = useState<string | null>(null)
useEffect(() => {
if (!cluster) return
let cancelled = false
clusterApi
.getInfo(cluster.id)
.then((data) => {
if (!cancelled) setInfo(data)
})
.catch((err) => {
if (!cancelled) setError(err instanceof Error ? err.message : '加载集群详情失败')
})
return () => {
cancelled = true
}
}, [cluster])
return (
<Dialog open={cluster !== null} onOpenChange={(open) => !open && onClose()}>
<DialogContent className="max-w-3xl max-h-[90vh] overflow-y-auto">
<DialogHeader>
<DialogTitle className="flex items-center gap-2">
<Server className="w-5 h-5 text-info" />
{cluster?.name}
</DialogTitle>
</DialogHeader>
{error ? (
<ErrorState message={error} />
) : info ? (
<ClusterDetail info={info} />
) : (
<LoadingSpinner className="h-32" />
)}
</DialogContent>
</Dialog>
)
})
/** 集群详情内容:版本/上下文/节点/命名空间 */
const ClusterDetail = memo(function ClusterDetail({ info }: { info: ClusterInfo }) {
return (
<div className="space-y-6">
<div className="grid grid-cols-2 gap-4">
<div className="p-3 bg-muted rounded-lg">
<p className="text-xs text-muted-foreground">版本</p>
<p className="text-sm font-medium">{info.version || '未知'}</p>
</div>
<div className="p-3 bg-muted rounded-lg">
<p className="text-xs text-muted-foreground">当前上下文</p>
<p className="text-sm font-medium">{info.currentContext || '默认'}</p>
</div>
</div>
<div>
<h4 className="text-sm font-semibold mb-2">节点({info.nodes.length})</h4>
<div className="space-y-2">
{info.nodes.map((node) => (
<div
key={node.name}
className="p-3 border border-border rounded-lg"
>
<div className="flex items-center justify-between">
<span className="font-medium text-sm">{node.name}</span>
<span
className={`px-2 py-0.5 rounded-full text-xs ${
node.status === 'Ready'
? 'bg-success/10 text-primary'
: 'bg-destructive/10 text-destructive'
}`}
>
{node.status === 'Ready' ? '就绪' : '未就绪'}
</span>
</div>
<div className="grid grid-cols-3 gap-2 mt-2 text-xs text-muted-foreground">
<span>IP:{node.internalIP}</span>
<span>系统:{node.os}/{node.arch}</span>
<span>版本:{node.version}</span>
</div>
{node.roles.length > 0 && (
<div className="flex gap-1 mt-2">
{node.roles.map((role) => (
<span
key={role}
className="px-1.5 py-0.5 bg-info/10 text-info rounded text-xs"
>
{role}
</span>
))}
</div>
)}
</div>
))}
</div>
</div>
<div>
<h4 className="text-sm font-semibold mb-2">命名空间</h4>
<div className="flex flex-wrap gap-1">
{info.namespaces.map((ns) => (
<span
key={ns}
className="px-2 py-0.5 bg-muted rounded text-xs"
>
{ns}
</span>
))}
</div>
</div>
</div>
)
})
@@ -0,0 +1,263 @@
import { memo, useEffect, useState } from 'react'
import { useForm } from 'react-hook-form'
import { zodResolver } from '@hookform/resolvers/zod'
import { z } from 'zod'
import { Key, FileKey } from 'lucide-react'
import { Button } from '@/components/ui/button'
import { Input } from '@/components/ui/input'
import { Textarea } from '@/components/ui/textarea'
import { Tabs, TabsList, TabsTrigger, TabsContent } from '@/components/ui/tabs'
import {
Dialog,
DialogContent,
DialogHeader,
DialogTitle,
} from '@/components/ui/dialog'
import {
Form,
FormControl,
FormField,
FormItem,
FormLabel,
FormMessage,
} from '@/components/ui/form'
import { clusterApi } from '@/api'
import { toast } from 'sonner'
// 从 kubeconfig 文本自动提取 server 地址
const parseApiServer = (kubeconfig: string): string => {
const m = kubeconfig.match(/^\s*server:\s*(\S+)/m)
return m ? m[1] : ''
}
// 表单 schema:zod 为唯一校验源,消息中文且具体
const clusterFormSchema = z
.object({
name: z.string().min(1, '请输入集群名称'),
description: z.string().optional(),
configType: z.enum(['kubeconfig', 'token']),
kubeconfig: z.string().optional(),
apiServer: z.string().optional(),
token: z.string().optional(),
context: z.string().optional(),
})
.superRefine((data, ctx) => {
if (data.configType === 'kubeconfig' && !data.kubeconfig?.trim()) {
ctx.addIssue({ code: 'custom', path: ['kubeconfig'], message: '请填写 kubeconfig 内容' })
}
if (data.configType === 'token') {
if (!data.apiServer?.trim()) {
ctx.addIssue({ code: 'custom', path: ['apiServer'], message: '请填写 API Server 地址' })
}
if (!data.token?.trim()) {
ctx.addIssue({ code: 'custom', path: ['token'], message: '请填写 Token' })
}
}
})
type ClusterFormValues = z.infer<typeof clusterFormSchema>
const DEFAULT_VALUES: ClusterFormValues = {
name: '',
description: '',
configType: 'kubeconfig',
kubeconfig: '',
apiServer: '',
token: '',
context: '',
}
interface ClusterFormDialogProps {
open: boolean
onOpenChange: (open: boolean) => void
/** 创建成功回调(父级刷新列表并关闭弹窗) */
onCreated: () => void
}
/** 添加集群弹窗 — react-hook-form + zod,自包含表单逻辑,页面只传开关与回调 */
export const ClusterFormDialog = memo(function ClusterFormDialog({
open,
onOpenChange,
onCreated,
}: ClusterFormDialogProps) {
const [submitting, setSubmitting] = useState(false)
const form = useForm<ClusterFormValues>({
resolver: zodResolver(clusterFormSchema),
defaultValues: DEFAULT_VALUES,
})
const configType = form.watch('configType')
const kubeconfig = form.watch('kubeconfig')
// 打开时重置(编辑回填/关闭重置时机明确)
useEffect(() => {
if (open) {
form.reset(DEFAULT_VALUES)
}
}, [open, form])
const onSubmit = form.handleSubmit(async (values) => {
setSubmitting(true)
try {
await clusterApi.create({
name: values.name,
description: values.description,
configType: values.configType,
apiServer: values.configType === 'token' ? values.apiServer : undefined,
kubeconfig: values.configType === 'kubeconfig' ? values.kubeconfig : undefined,
token: values.configType === 'token' ? values.token : undefined,
context: values.context,
})
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>添加 Kubernetes 集群</DialogTitle>
</DialogHeader>
<Form {...form}>
<form onSubmit={onSubmit} className="space-y-4">
<FormField
control={form.control}
name="name"
render={({ field }) => (
<FormItem>
<FormLabel>集群名称 *</FormLabel>
<FormControl>
<Input placeholder="production-cluster" {...field} />
</FormControl>
<FormMessage />
</FormItem>
)}
/>
<FormField
control={form.control}
name="description"
render={({ field }) => (
<FormItem>
<FormLabel>描述</FormLabel>
<FormControl>
<Input placeholder="生产环境日志集群" {...field} />
</FormControl>
<FormMessage />
</FormItem>
)}
/>
<FormItem>
<FormLabel>接入方式</FormLabel>
<FormControl>
<Tabs
value={configType}
onValueChange={(v) =>
form.setValue('configType', v as ClusterFormValues['configType'])
}
>
<TabsList>
<TabsTrigger value="kubeconfig">
<FileKey className="w-3.5 h-3.5 mr-1" /> Kubeconfig
</TabsTrigger>
<TabsTrigger value="token">
<Key className="w-3.5 h-3.5 mr-1" /> Token
</TabsTrigger>
</TabsList>
<TabsContent value="kubeconfig" className="space-y-2 pt-2">
<FormField
control={form.control}
name="kubeconfig"
render={({ field }) => (
<FormItem>
<FormLabel>Kubeconfig 内容 *</FormLabel>
<FormControl>
<Textarea
placeholder="粘贴 kubeconfig YAML(自动识别 API Server)..."
className="min-h-[200px] font-mono text-xs"
{...field}
/>
</FormControl>
<FormMessage />
</FormItem>
)}
/>
{kubeconfig && parseApiServer(kubeconfig) && (
<p className="text-xs text-primary">
已识别 API Server:{parseApiServer(kubeconfig)}
</p>
)}
</TabsContent>
<TabsContent value="token" className="space-y-2 pt-2">
<FormField
control={form.control}
name="apiServer"
render={({ field }) => (
<FormItem>
<FormLabel>API Server *</FormLabel>
<FormControl>
<Input placeholder="https://10.0.0.1:6443" {...field} />
</FormControl>
<FormMessage />
</FormItem>
)}
/>
<FormField
control={form.control}
name="token"
render={({ field }) => (
<FormItem>
<FormLabel>Token *</FormLabel>
<FormControl>
<Textarea
placeholder="粘贴 Service Account Token..."
className="min-h-[120px] font-mono text-xs"
{...field}
/>
</FormControl>
<FormMessage />
<p className="text-xs text-muted-foreground">
采用 insecure 模式,便于内网/自签证书集群接入
</p>
</FormItem>
)}
/>
</TabsContent>
</Tabs>
</FormControl>
</FormItem>
{configType === 'kubeconfig' && (
<FormField
control={form.control}
name="context"
render={({ field }) => (
<FormItem>
<FormLabel>上下文(可选)</FormLabel>
<FormControl>
<Input placeholder="留空则使用默认上下文" {...field} />
</FormControl>
<FormMessage />
</FormItem>
)}
/>
)}
<Button
type="submit"
className="w-full bg-primary hover:bg-primary/90"
disabled={submitting}
>
{submitting ? '添加中...' : '添加集群'}
</Button>
</form>
</Form>
</DialogContent>
</Dialog>
)
})
+164
View File
@@ -0,0 +1,164 @@
import { memo, useCallback, useEffect, useRef, useState } from 'react'
import { Server, Plus } from 'lucide-react'
import { Button } from '@/components/ui/button'
import { clusterApi, 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 { Cluster } from '@/types'
import { ClusterCard } from './components/ClusterCard'
import { ClusterFormDialog } from './components/ClusterFormDialog'
import { ClusterDetailDialog } from './components/ClusterDetailDialog'
/**
* 集群管理页 — 只做编排:数据走 useListQuery(取消+版本号),
* 卡片/表单/详情/删除确认均为域内子组件。成功操作静默(列表刷新即反馈)。
*/
const ClustersPage = memo(function ClustersPage() {
const query = useListQuery<Cluster>((params, signal) =>
clusterApi.list(params, { signal })
)
const [formOpen, setFormOpen] = useState(false)
const [detailCluster, setDetailCluster] = useState<Cluster | null>(null)
const [deleteTarget, setDeleteTarget] = useState<Cluster | 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.clusterID === deleteTarget.id).length,
col: c.list.filter((x) => x.clusterID === 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 clusterApi.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 clusterApi.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 部署的 Kubernetes 集群"
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={Server}
title="暂无集群"
description="添加第一个 Kubernetes 集群开始使用"
/>
) : (
<>
<div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
{query.list.map((cluster) => (
<ClusterCard
key={cluster.id}
cluster={cluster}
validating={validating}
onViewInfo={setDetailCluster}
onValidate={handleValidate}
onDelete={setDeleteTarget}
/>
))}
</div>
<PaginationBar
page={query.page}
pageSize={query.pageSize}
total={query.total}
onPageChange={query.setPage}
/>
</>
)}
<ClusterFormDialog
open={formOpen}
onOpenChange={setFormOpen}
onCreated={query.reload}
/>
<ClusterDetailDialog
key={detailCluster?.id ?? 'none'}
cluster={detailCluster}
onClose={() => setDetailCluster(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 ClustersPage