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,91 @@
import { memo } from 'react'
import { HardDrive, Star, Trash2 } from 'lucide-react'
import { Button } from '@/components/ui/button'
import { Card, CardContent } from '@/components/ui/card'
import { InfoRow } from '@/components/InfoRow'
import type { StorageConfig } from '@/types'
import { STORAGE_TYPE_ICONS, STORAGE_TYPE_ICON_CLASS, STORAGE_TYPE_COLORS } from '../constants'
interface StorageCardProps {
storage: StorageConfig
onSetDefault: (id: number) => void
onDelete: (s: StorageConfig) => void
}
/** 存储配置卡片 — 列表项展示与操作入口(删除传整个对象,供确认弹窗展示名称) */
export const StorageCard = memo(function StorageCard({
storage,
onSetDefault,
onDelete,
}: StorageCardProps) {
return (
<Card
className={`border-border hover:shadow-md transition-shadow ${
storage.isDefault ? 'ring-1 ring-primary' : ''
}`}
>
<CardContent className="p-5">
<div className="flex items-start justify-between mb-3">
<div className="flex items-center gap-2 min-w-0">
{(() => {
const Icon = STORAGE_TYPE_ICONS[storage.storageType] || HardDrive
const cls =
STORAGE_TYPE_ICON_CLASS[storage.storageType] || 'text-muted-foreground'
return <Icon className={`w-5 h-5 ${cls}`} />
})()}
<h3 className="font-semibold text-foreground truncate">
{storage.name}
</h3>
</div>
<div className="flex items-center gap-1 flex-shrink-0">
{storage.isDefault && (
<span className="px-1.5 py-0.5 rounded-full bg-success/10 text-primary text-xs font-medium flex items-center gap-0.5">
<Star className="w-3 h-3" />
默认
</span>
)}
<span
className={`px-2 py-0.5 rounded-full text-xs font-medium uppercase ${
STORAGE_TYPE_COLORS[storage.storageType] || 'bg-muted text-slate-600'
}`}
>
{storage.storageType}
</span>
</div>
</div>
<div className="space-y-1.5 text-xs text-muted-foreground mb-4">
<InfoRow label="访问地址" value={storage.endpoint || '默认'} valueClass="truncate max-w-[150px]" />
<InfoRow label="Bucket" value={storage.bucket} valueClass="truncate max-w-[150px]" />
{(storage.storageType === 's3' || storage.storageType === 'oss') && (
<InfoRow label="区域" value={storage.region || '无'} valueClass="truncate max-w-[150px]" />
)}
<InfoRow label="路径前缀" value={storage.pathPrefix || '无'} valueClass="truncate max-w-[150px]" />
<InfoRow label="不加密" value={storage.insecure ? '是' : '否'} />
</div>
<div className="flex gap-2 pt-3 border-t border-border">
<Button
variant="outline"
size="sm"
className="flex-1 text-xs"
onClick={() => onSetDefault(storage.id)}
disabled={storage.isDefault}
>
<Star className="w-3 h-3 mr-1" />
{storage.isDefault ? '默认' : '设为默认'}
</Button>
<Button
variant="outline"
size="sm"
aria-label={`删除存储配置 ${storage.name}`}
className="text-destructive hover:text-destructive hover:bg-destructive/10"
onClick={() => onDelete(storage)}
>
<Trash2 className="w-3 h-3" />
</Button>
</div>
</CardContent>
</Card>
)
})
@@ -0,0 +1,369 @@
import { memo, useEffect, useState } from 'react'
import { useForm } from 'react-hook-form'
import { zodResolver } from '@hookform/resolvers/zod'
import { z } from 'zod'
import { HardDrive, PlugZap } from 'lucide-react'
import { Button } from '@/components/ui/button'
import { Input } from '@/components/ui/input'
import { Label } from '@/components/ui/label'
import { Switch } from '@/components/ui/switch'
import {
Dialog,
DialogContent,
DialogHeader,
DialogTitle,
} from '@/components/ui/dialog'
import {
Form,
FormControl,
FormField,
FormItem,
FormLabel,
FormMessage,
} from '@/components/ui/form'
import { storageApi, type StorageTestResult } from '@/api'
import { PasswordInput } from '@/components/PasswordInput'
import { toast } from 'sonner'
import { STORAGE_TYPE_ICONS, STORAGE_TYPE_ICON_CLASS, STORAGE_TYPES } from '../constants'
// 表单 schema:zod 为唯一校验源,消息中文且具体
const storageFormSchema = z.object({
name: z.string().min(1, '请输入存储配置名称'),
storageType: z.enum(['s3', 'oss', 'minio', 'rustfs']),
endpoint: z.string().optional(),
bucket: z.string().min(1, '请填写 Bucket 名称'),
region: z.string().optional(),
accessKey: z.string().optional(),
secretKey: z.string().optional(),
pathPrefix: z.string().optional(),
insecure: z.boolean(),
isDefault: z.boolean(),
})
type StorageFormValues = z.infer<typeof storageFormSchema>
const DEFAULT_VALUES: StorageFormValues = {
name: '',
storageType: 'minio',
endpoint: '',
bucket: '',
region: '',
accessKey: '',
secretKey: '',
pathPrefix: 'loki',
insecure: false,
isDefault: false,
}
interface StorageFormDialogProps {
open: boolean
onOpenChange: (open: boolean) => void
/** 创建成功回调(父级刷新列表并关闭弹窗) */
onCreated: () => void
}
/** 添加存储配置弹窗 — react-hook-form + zod,自包含表单逻辑,页面只传开关与回调 */
export const StorageFormDialog = memo(function StorageFormDialog({
open,
onOpenChange,
onCreated,
}: StorageFormDialogProps) {
const [submitting, setSubmitting] = useState(false)
const [testing, setTesting] = useState(false)
const [testResult, setTestResult] = useState<StorageTestResult | null>(null)
const [createIfMissing, setCreateIfMissing] = useState(true)
const form = useForm<StorageFormValues>({
resolver: zodResolver(storageFormSchema),
defaultValues: DEFAULT_VALUES,
})
const storageType = form.watch('storageType')
// 区域仅对公有云(s3/oss)有意义;minio/rustfs 为本地部署不显示、不提交
const isCloudStorage = storageType === 's3' || storageType === 'oss'
// 打开时重置(默认值),关闭/重开时机明确
useEffect(() => {
if (open) {
form.reset(DEFAULT_VALUES)
setTestResult(null)
}
}, [open, form])
// 测试连接:用当前表单值(未保存)直连对象存储验证
const handleTest = async () => {
const values = form.getValues()
if (!values.bucket.trim() || !values.accessKey?.trim() || !values.secretKey?.trim()) {
toast.error('请先填写 Bucket 与 Access Key / Secret Key')
return
}
setTesting(true)
setTestResult(null)
try {
const result = await storageApi.test({
storageType: values.storageType,
endpoint: values.endpoint,
bucket: values.bucket,
region: isCloudStorage ? values.region : undefined,
accessKey: values.accessKey,
secretKey: values.secretKey,
insecure: values.insecure,
createIfMissing,
})
setTestResult(result)
} catch (err) {
toast.error(err instanceof Error ? err.message : '测试连接失败')
} finally {
setTesting(false)
}
}
const onSubmit = form.handleSubmit(async (values) => {
if (!isCloudStorage) {
values.region = ''
}
setSubmitting(true)
try {
await storageApi.create(values)
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>添加存储配置</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-minio" {...field} />
</FormControl>
<FormMessage />
</FormItem>
)}
/>
<FormField
control={form.control}
name="storageType"
render={({ field }) => (
<FormItem>
<FormLabel>存储类型</FormLabel>
<FormControl>
<div className="grid grid-cols-4 gap-2">
{STORAGE_TYPES.map((type) => (
<button
key={type}
type="button"
onClick={() => field.onChange(type)}
className={`flex flex-col items-center gap-1 p-3 rounded-lg border transition-all ${
field.value === type
? 'border-primary bg-primary/10 text-primary'
: 'border-border hover:border-input text-slate-600'
}`}
>
{(() => {
const Icon = STORAGE_TYPE_ICONS[type] || HardDrive
return <Icon className={`w-5 h-5 ${STORAGE_TYPE_ICON_CLASS[type] || ''}`} />
})()}
<span className="text-xs font-medium uppercase">{type}</span>
</button>
))}
</div>
</FormControl>
<FormMessage />
</FormItem>
)}
/>
<FormField
control={form.control}
name="endpoint"
render={({ field }) => (
<FormItem>
<FormLabel>访问地址</FormLabel>
<FormControl>
<Input
placeholder={
storageType === 's3'
? 's3.amazonaws.com'
: storageType === 'oss'
? 'oss-cn-hangzhou.aliyuncs.com'
: 'http://10.0.0.8:9000'
}
{...field}
/>
</FormControl>
<FormMessage />
</FormItem>
)}
/>
<div className={isCloudStorage ? 'grid grid-cols-2 gap-4' : ''}>
<FormField
control={form.control}
name="bucket"
render={({ field }) => (
<FormItem>
<FormLabel>Bucket *</FormLabel>
<FormControl>
<Input placeholder="loki-logs" {...field} />
</FormControl>
<FormMessage />
</FormItem>
)}
/>
{isCloudStorage && (
<FormField
control={form.control}
name="region"
render={({ field }) => (
<FormItem>
<FormLabel>区域</FormLabel>
<FormControl>
<Input placeholder="us-east-1" {...field} />
</FormControl>
<FormMessage />
</FormItem>
)}
/>
)}
</div>
<div className="grid grid-cols-2 gap-4">
<FormField
control={form.control}
name="accessKey"
render={({ field }) => (
<FormItem>
<FormLabel>Access Key</FormLabel>
<FormControl>
<Input placeholder="minioadmin" {...field} />
</FormControl>
<FormMessage />
</FormItem>
)}
/>
<FormField
control={form.control}
name="secretKey"
render={({ field }) => (
<FormItem>
<FormLabel>Secret Key</FormLabel>
<FormControl>
<PasswordInput placeholder="minioadmin" {...field} />
</FormControl>
<FormMessage />
</FormItem>
)}
/>
</div>
<FormField
control={form.control}
name="pathPrefix"
render={({ field }) => (
<FormItem>
<FormLabel>路径前缀</FormLabel>
<FormControl>
<Input placeholder="loki" {...field} />
</FormControl>
<FormMessage />
</FormItem>
)}
/>
<div className="flex flex-wrap items-center gap-6">
<FormField
control={form.control}
name="insecure"
render={({ field }) => (
<FormItem className="flex items-center gap-2 space-y-0">
<FormControl>
<Switch
id="s-insecure"
checked={field.value}
onCheckedChange={field.onChange}
/>
</FormControl>
<Label htmlFor="s-insecure">不加密 (HTTP)</Label>
</FormItem>
)}
/>
<FormField
control={form.control}
name="isDefault"
render={({ field }) => (
<FormItem className="flex items-center gap-2 space-y-0">
<FormControl>
<Switch
id="s-default"
checked={field.value}
onCheckedChange={field.onChange}
/>
</FormControl>
<Label htmlFor="s-default">设为默认</Label>
</FormItem>
)}
/>
<div className="flex items-center gap-2">
<Switch
id="s-autocreate"
checked={createIfMissing}
onCheckedChange={setCreateIfMissing}
/>
<Label htmlFor="s-autocreate">测试时桶不存在则自动创建</Label>
</div>
</div>
{testResult && (
<div
className={`p-3 rounded-lg border text-sm ${
testResult.authenticated && testResult.bucketExists
? 'bg-success/10 border-success/30 text-success'
: 'bg-destructive/10 border-destructive/30 text-destructive'
}`}
role="status"
>
{testResult.message}
</div>
)}
<div className="flex gap-2">
<Button
type="button"
variant="outline"
className="flex-1"
disabled={testing || submitting}
onClick={handleTest}
>
<PlugZap className="w-4 h-4 mr-1" />
{testing ? '测试中...' : '测试连接'}
</Button>
<Button
type="submit"
className="flex-1 bg-primary hover:bg-primary/90"
disabled={submitting}
>
{submitting ? '添加中...' : '添加存储'}
</Button>
</div>
</form>
</Form>
</DialogContent>
</Dialog>
)
})
+25
View File
@@ -0,0 +1,25 @@
import { Cloud, Database, Package, type LucideIcon } from 'lucide-react'
// 存储类型展示常量(卡片与表单共用)— 图标存组件引用,渲染由消费方完成
export const STORAGE_TYPE_ICONS: Record<string, LucideIcon> = {
s3: Cloud,
oss: Cloud,
minio: Database,
rustfs: Package,
}
export const STORAGE_TYPE_ICON_CLASS: Record<string, string> = {
s3: 'text-warning',
oss: 'text-destructive',
minio: 'text-info',
rustfs: 'text-info',
}
export const STORAGE_TYPE_COLORS: Record<string, string> = {
s3: 'bg-warning/10 text-warning',
oss: 'bg-destructive/10 text-destructive',
minio: 'bg-info/10 text-info',
rustfs: 'bg-info/10 text-info',
}
export const STORAGE_TYPES = ['s3', 'oss', 'minio', 'rustfs'] as const
+136
View File
@@ -0,0 +1,136 @@
import { useEffect, memo, useCallback, useState } from 'react'
import { HardDrive, Plus } from 'lucide-react'
import { Button } from '@/components/ui/button'
import { storageApi, deploymentApi } 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 { StorageConfig } from '@/types'
import { StorageCard } from './components/StorageCard'
import { StorageFormDialog } from './components/StorageFormDialog'
/**
* 存储配置页 — 只做编排:数据走 useListQuery(取消+版本号),
* 卡片/表单/删除确认为域内子组件。成功操作静默(列表刷新即反馈)。
*/
const StoragePage = memo(function StoragePage() {
const query = useListQuery<StorageConfig>((params, signal) =>
storageApi.list(params, { signal })
)
const [formOpen, setFormOpen] = useState(false)
const [deleteTarget, setDeleteTarget] = useState<StorageConfig | null>(null)
const [deleting, setDeleting] = useState(false)
const [depRefCount, setDepRefCount] = useState(0)
useEffect(() => {
if (!deleteTarget) return
deploymentApi
.list({ page: 1, pageSize: 100 })
.then((d) => setDepRefCount(d.list.filter((x) => x.storageConfigID === deleteTarget.id).length))
.catch(() => setDepRefCount(0))
}, [deleteTarget])
const handleDelete = useCallback(async () => {
const id = deleteTarget?.id
if (!id) return
setDeleting(true)
try {
await storageApi.remove(id)
setDeleteTarget(null)
query.refresh()
} catch (err) {
toast.error(err instanceof Error ? err.message : '删除存储配置失败')
} finally {
setDeleting(false)
}
}, [deleteTarget, query])
// 设为默认存储(后端保证唯一默认:置新默认会取消旧默认)
const handleSetDefault = useCallback(
async (id: number) => {
try {
await storageApi.update(id, { isDefault: true })
query.refresh()
} catch (err) {
toast.error(err instanceof Error ? err.message : '设置默认存储失败')
}
},
[query]
)
return (
<PageContainer
title="存储配置"
description="为 Loki 配置对象存储后端"
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={HardDrive}
title="暂无存储配置"
description="添加第一个 Loki 存储后端"
/>
) : (
<>
<div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
{query.list.map((storage) => (
<StorageCard
key={storage.id}
storage={storage}
onSetDefault={handleSetDefault}
onDelete={setDeleteTarget}
/>
))}
</div>
<PaginationBar
page={query.page}
pageSize={query.pageSize}
total={query.total}
onPageChange={query.setPage}
/>
</>
)}
<StorageFormDialog
open={formOpen}
onOpenChange={setFormOpen}
onCreated={query.reload}
/>
<ConfirmDialog
open={deleteTarget !== null}
onOpenChange={(open) => {
if (!open) setDeleteTarget(null)
}}
name={deleteTarget?.name}
loading={deleting}
description={
depRefCount > 0
? `确定要删除「${deleteTarget?.name}」吗?警告:仍有 ${depRefCount} 个部署使用该存储,删除后这些部署的对象存储配置将失效。`
: undefined
}
onConfirm={handleDelete}
/>
</PageContainer>
)
})
export default StoragePage