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

-543
View File
@@ -1,543 +0,0 @@
import { memo, useCallback, useEffect, useRef, useState } from 'react'
import {
Server,
Plus,
RefreshCw,
Trash2,
Eye,
Key,
FileKey,
} from 'lucide-react'
import { Button } from '@/components/ui/button'
import { Input } from '@/components/ui/input'
import { Label } from '@/components/ui/label'
import { Textarea } from '@/components/ui/textarea'
import { Tabs, TabsList, TabsTrigger, TabsContent } from '@/components/ui/tabs'
import {
Dialog,
DialogContent,
DialogHeader,
DialogTitle,
DialogTrigger,
} from '@/components/ui/dialog'
import { Card, CardContent } from '@/components/ui/card'
import { clusterApi } from '@/api'
import { StatusBadge } from '@/components/StatusBadge'
import { LoadingSpinner } from '@/components/LoadingSpinner'
import { EmptyState } from '@/components/EmptyState'
import { PageHeader } from '@/components/PageHeader'
import { toast } from 'sonner'
import type { Cluster, ClusterInfo } from '@/types'
// 从 kubeconfig 文本自动提取 server 地址
const parseApiServer = (kubeconfig: string): string => {
const m = kubeconfig.match(/^\s*server:\s*(\S+)/m)
return m ? m[1] : ''
}
/**
* Clusters 页面 - 优化版本
*
* 优化点:
* 1. React.memo 包裹组件
* 2. 所有操作函数使用 useCallback 缓存
* 3. alert() 替换为 sonner toast
* 4. setTimeout 使用 ref 管理,添加清理函数
* 5. 使用 StatusBadge 公共组件
* 6. 使用 PageHeader、EmptyState、LoadingSpinner 公共组件
*/
const Clusters = memo(function Clusters() {
const [clusters, setClusters] = useState<Cluster[]>([])
const [loading, setLoading] = useState(true)
const [open, setOpen] = useState(false)
const [detailOpen, setDetailOpen] = useState(false)
const [selectedCluster, setSelectedCluster] = useState<Cluster | null>(null)
const [clusterInfo, setClusterInfo] = useState<ClusterInfo | null>(null)
const [validating, setValidating] = useState<number | null>(null)
// Form state
const [name, setName] = useState('')
const [description, setDescription] = useState('')
const [configType, setConfigType] = useState<'kubeconfig' | 'token'>('kubeconfig')
const [kubeconfig, setKubeconfig] = useState('')
const [apiServer, setApiServer] = useState('')
const [token, setToken] = useState('')
const [context, setContext] = useState('')
const [submitting, setSubmitting] = useState(false)
// 定时器管理ref
const timeoutsRef = useRef<ReturnType<typeof setTimeout>[]>([])
useEffect(() => {
return () => {
timeoutsRef.current.forEach((id) => clearTimeout(id))
}
}, [])
const addTimeout = useCallback((cb: () => void, delay: number) => {
const id = setTimeout(cb, delay)
timeoutsRef.current.push(id)
return id
}, [])
const loadClusters = useCallback(async () => {
try {
const res = await clusterApi.list(1, 100)
setClusters(res.list)
} catch (err) {
console.error('Failed to load clusters:', err)
toast.error('加载集群数据失败')
} finally {
setLoading(false)
}
}, [])
useEffect(() => {
loadClusters()
}, [loadClusters])
const resetForm = useCallback(() => {
setName('')
setDescription('')
setConfigType('kubeconfig')
setKubeconfig('')
setApiServer('')
setToken('')
setContext('')
}, [])
const handleSubmit = useCallback(
async (e: React.FormEvent) => {
e.preventDefault()
// 校验
if (configType === 'kubeconfig' && !kubeconfig.trim()) {
toast.error('请填写 kubeconfig 内容')
return
}
if (configType === 'token' && (!apiServer.trim() || !token.trim())) {
toast.error('Token 接入方式需要填写 API Server 和 Token')
return
}
setSubmitting(true)
try {
await clusterApi.create({
name,
description,
configType,
apiServer: configType === 'token' ? apiServer : undefined,
kubeconfig: configType === 'kubeconfig' ? kubeconfig : undefined,
token: configType === 'token' ? token : undefined,
context,
})
setOpen(false)
resetForm()
loadClusters()
toast.success('集群添加成功')
} catch (err: unknown) {
const message = err instanceof Error ? err.message : '创建集群失败'
toast.error(message)
} finally {
setSubmitting(false)
}
},
[name, description, configType, kubeconfig, apiServer, token, context, resetForm, loadClusters]
)
const handleDelete = useCallback(
async (id: number) => {
if (!confirm('确定删除此集群?')) return
try {
await clusterApi.remove(id)
loadClusters()
toast.success('集群已删除')
} catch (err) {
console.error('Failed to delete cluster:', err)
toast.error('删除集群失败')
}
},
[loadClusters]
)
const handleValidate = useCallback(
async (id: number) => {
setValidating(id)
try {
await clusterApi.validate(id)
addTimeout(loadClusters, 3000)
toast.success('验证指令已发送')
} catch (err) {
console.error('Failed to validate cluster:', err)
toast.error('验证失败')
} finally {
addTimeout(() => setValidating(null), 3000)
}
},
[loadClusters, addTimeout]
)
const viewClusterInfo = useCallback(async (cluster: Cluster) => {
setSelectedCluster(cluster)
setClusterInfo(null)
setDetailOpen(true)
try {
const info = await clusterApi.getInfo(cluster.id)
setClusterInfo(info)
} catch (err) {
console.error('Failed to get cluster info:', err)
toast.error('加载集群详情失败')
}
}, [])
return (
<div className="space-y-6">
{/* Header */}
<PageHeader
title="集群管理"
description="管理用于 Loki 部署的 Kubernetes 集群"
action={
<Dialog open={open} onOpenChange={setOpen}>
<DialogTrigger asChild>
<Button className="bg-emerald-600 hover:bg-emerald-700">
<Plus className="w-4 h-4 mr-1" />
添加集群
</Button>
</DialogTrigger>
<DialogContent className="max-w-2xl max-h-[90vh] overflow-y-auto">
<DialogHeader>
<DialogTitle>添加 Kubernetes 集群</DialogTitle>
</DialogHeader>
<form onSubmit={handleSubmit} className="space-y-4">
<div className="space-y-2">
<Label htmlFor="name">集群名称 *</Label>
<Input
id="name"
value={name}
onChange={(e) => setName(e.target.value)}
placeholder="production-cluster"
required
/>
</div>
<div className="space-y-2">
<Label htmlFor="description">描述</Label>
<Input
id="description"
value={description}
onChange={(e) => setDescription(e.target.value)}
placeholder="生产环境日志集群"
/>
</div>
<div className="space-y-2">
<Label>接入方式</Label>
<Tabs
value={configType}
onValueChange={(v) => setConfigType(v as 'kubeconfig' | 'token')}
>
<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">
<Label htmlFor="kubeconfig">Kubeconfig 内容 *</Label>
<Textarea
id="kubeconfig"
value={kubeconfig}
onChange={(e) => setKubeconfig(e.target.value)}
placeholder="粘贴 kubeconfig YAML(自动识别 API Server)..."
className="min-h-[200px] font-mono text-xs"
/>
{kubeconfig && parseApiServer(kubeconfig) && (
<p className="text-xs text-emerald-600">
已识别 API Server:{parseApiServer(kubeconfig)}
</p>
)}
</TabsContent>
<TabsContent value="token" className="space-y-2 pt-2">
<div className="space-y-2">
<Label htmlFor="apiServer">API Server *</Label>
<Input
id="apiServer"
value={apiServer}
onChange={(e) => setApiServer(e.target.value)}
placeholder="https://10.0.0.1:6443"
/>
</div>
<div className="space-y-2">
<Label htmlFor="token">Token *</Label>
<Textarea
id="token"
value={token}
onChange={(e) => setToken(e.target.value)}
placeholder="粘贴 Service Account Token..."
className="min-h-[120px] font-mono text-xs"
/>
<p className="text-xs text-slate-400">
采用 insecure 模式,便于内网/自签证书集群接入
</p>
</div>
</TabsContent>
</Tabs>
</div>
{configType === 'kubeconfig' && (
<div className="space-y-2">
<Label htmlFor="context">上下文(可选)</Label>
<Input
id="context"
value={context}
onChange={(e) => setContext(e.target.value)}
placeholder="留空则使用默认上下文"
/>
</div>
)}
<Button
type="submit"
className="w-full bg-emerald-600 hover:bg-emerald-700"
disabled={submitting}
>
{submitting ? '添加中...' : '添加集群'}
</Button>
</form>
</DialogContent>
</Dialog>
}
/>
{/* Clusters Grid */}
{loading ? (
<LoadingSpinner className="h-64" />
) : clusters.length === 0 ? (
<EmptyState
icon={Server}
title="暂无集群"
description="添加第一个 Kubernetes 集群开始使用"
/>
) : (
<div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
{clusters.map((cluster) => (
<ClusterCard
key={cluster.id}
cluster={cluster}
validating={validating}
onViewInfo={viewClusterInfo}
onValidate={handleValidate}
onDelete={handleDelete}
/>
))}
</div>
)}
{/* Cluster Detail Dialog */}
<Dialog open={detailOpen} onOpenChange={setDetailOpen}>
<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-blue-500" />
{selectedCluster?.name}
</DialogTitle>
</DialogHeader>
{clusterInfo ? (
<ClusterDetail info={clusterInfo} />
) : (
<LoadingSpinner className="h-32" />
)}
</DialogContent>
</Dialog>
</div>
)
})
// 子组件:集群卡片
interface ClusterCardProps {
cluster: Cluster
validating: number | null
onViewInfo: (c: Cluster) => void
onValidate: (id: number) => void
onDelete: (id: number) => void
}
const ClusterCard = memo(function ClusterCard({
cluster,
validating,
onViewInfo,
onValidate,
onDelete,
}: ClusterCardProps) {
return (
<Card className="border-slate-200 dark:border-slate-800 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-blue-500 flex-shrink-0" />
<h3 className="font-semibold text-slate-800 dark:text-white truncate">
{cluster.name}
</h3>
</div>
<StatusBadge status={cluster.status} />
</div>
<p className="text-sm text-slate-500 mb-3 line-clamp-2">
{cluster.description || '无描述'}
</p>
<div className="space-y-1.5 text-xs text-slate-500 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-slate-100 dark:border-slate-800">
<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"
className="text-red-500 hover:text-red-600 hover:bg-red-50"
onClick={() => onDelete(cluster.id)}
>
<Trash2 className="w-3 h-3" />
</Button>
</div>
</CardContent>
</Card>
)
})
// 子组件:信息行
const InfoRow = memo(function InfoRow({
label,
value,
valueClass,
}: {
label: string
value: string
valueClass?: string
}) {
return (
<div className="flex justify-between">
<span>{label}</span>
<span className={`font-medium text-slate-700 dark:text-slate-300 ${valueClass || ''}`}>
{value}
</span>
</div>
)
})
// 子组件:集群详情
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-slate-50 dark:bg-slate-800 rounded-lg">
<p className="text-xs text-slate-500">版本</p>
<p className="text-sm font-medium">{info.version || '未知'}</p>
</div>
<div className="p-3 bg-slate-50 dark:bg-slate-800 rounded-lg">
<p className="text-xs text-slate-500">当前上下文</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, idx) => (
<div
key={idx}
className="p-3 border border-slate-200 dark:border-slate-700 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-emerald-100 text-emerald-700'
: 'bg-red-100 text-red-700'
}`}
>
{node.status === 'Ready' ? '就绪' : '未就绪'}
</span>
</div>
<div className="grid grid-cols-3 gap-2 mt-2 text-xs text-slate-500">
<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, ridx) => (
<span
key={ridx}
className="px-1.5 py-0.5 bg-blue-100 text-blue-700 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, idx) => (
<span
key={idx}
className="px-2 py-0.5 bg-slate-100 dark:bg-slate-800 rounded text-xs"
>
{ns}
</span>
))}
</div>
</div>
</div>
)
})
export default Clusters
-503
View File
@@ -1,503 +0,0 @@
import { memo, useCallback, useEffect, useRef, useState } from 'react'
import {
RadioTower,
Plus,
Trash2,
Upload,
Download,
Server,
Monitor,
Cloud,
} from 'lucide-react'
import { Button } from '@/components/ui/button'
import { Input } from '@/components/ui/input'
import { Label } from '@/components/ui/label'
import {
Dialog,
DialogContent,
DialogHeader,
DialogTitle,
DialogTrigger,
} from '@/components/ui/dialog'
import { Card, CardContent } from '@/components/ui/card'
import {
Select,
SelectContent,
SelectItem,
SelectTrigger,
SelectValue,
} from '@/components/ui/select'
import { collectorApi, deploymentApi, clusterApi, hostApi } from '@/api'
import { statusLabel } from '@/lib/utils'
import { StatusBadge } from '@/components/StatusBadge'
import { LoadingSpinner } from '@/components/LoadingSpinner'
import { EmptyState } from '@/components/EmptyState'
import { PageHeader } from '@/components/PageHeader'
import { toast } from 'sonner'
import type { Collector, LokiDeployment, Cluster, Host } from '@/types'
// 采集器类型元数据 - 常量提取
const COLLECTOR_TYPE_META: Record<string, { label: string; icon: typeof Server; color: string }> = {
'host-promtail': { label: '主机 Promtail', icon: Monitor, color: 'bg-purple-100 text-purple-700' },
'k8s-daemonset': { label: 'K8s DaemonSet', icon: Cloud, color: 'bg-blue-100 text-blue-700' },
'k8s-fluentbit-sidecar': { label: 'K8s Sidecar', icon: Server, color: 'bg-cyan-100 text-cyan-700' },
}
const COLLECTOR_TYPES = [
{ value: 'host-promtail' as const, label: '主机 Promtail(SSH)' },
{ value: 'k8s-daemonset' as const, label: 'K8s Promtail DaemonSet' },
{ value: 'k8s-fluentbit-sidecar' as const, label: 'K8s Fluent Bit Sidecar' },
]
/**
* Collectors 页面 - 优化版本
*
* 优化点:
* 1. React.memo 包裹组件
* 2. 所有操作函数使用 useCallback 缓存
* 3. alert() 替换为 sonner toast
* 4. setTimeout 使用 ref 管理,添加清理
* 5. 使用公共组件替代重复代码
* 6. 常量映射提取到组件外部
*/
const Collectors = memo(function Collectors() {
const [collectors, setCollectors] = useState<Collector[]>([])
const [deployments, setDeployments] = useState<LokiDeployment[]>([])
const [clusters, setClusters] = useState<Cluster[]>([])
const [hosts, setHosts] = useState<Host[]>([])
const [loading, setLoading] = useState(true)
const [open, setOpen] = useState(false)
const [busy, setBusy] = useState<number | null>(null)
// Form state
const [name, setName] = useState('')
const [collectorType, setCollectorType] = useState<'host-promtail' | 'k8s-daemonset' | 'k8s-fluentbit-sidecar'>('host-promtail')
const [lokiID, setLokiID] = useState('')
const [hostID, setHostID] = useState('')
const [clusterID, setClusterID] = useState('')
const [targetDeployment, setTargetDeployment] = useState('')
const [namespace, setNamespace] = useState('')
const [logPath, setLogPath] = useState('')
const [labels, setLabels] = useState('')
const [submitting, setSubmitting] = useState(false)
const timeoutsRef = useRef<ReturnType<typeof setTimeout>[]>([])
useEffect(() => {
return () => {
timeoutsRef.current.forEach((id) => clearTimeout(id))
}
}, [])
const addTimeout = useCallback((cb: () => void, delay: number) => {
const id = setTimeout(cb, delay)
timeoutsRef.current.push(id)
return id
}, [])
const loadAll = useCallback(async () => {
try {
const [cRes, dRes, clRes, hRes] = await Promise.all([
collectorApi.list(1, 100),
deploymentApi.list(1, 100),
clusterApi.list(1, 100),
hostApi.list(1, 100),
])
setCollectors(cRes.list)
setDeployments(dRes.list)
setClusters(clRes.list)
setHosts(hRes.list)
} catch (err) {
console.error('Failed to load collectors:', err)
toast.error('加载采集器数据失败')
} finally {
setLoading(false)
}
}, [])
useEffect(() => {
loadAll()
}, [loadAll])
const resetForm = useCallback(() => {
setName('')
setCollectorType('host-promtail')
setLokiID('')
setHostID('')
setClusterID('')
setTargetDeployment('')
setNamespace('')
setLogPath('')
setLabels('')
}, [])
const handleSubmit = useCallback(
async (e: React.FormEvent) => {
e.preventDefault()
if (!lokiID) {
toast.error('请选择关联的 Loki 部署')
return
}
setSubmitting(true)
try {
await collectorApi.create({
name,
type: collectorType,
lokiDeploymentID: Number(lokiID),
hostID: collectorType === 'host-promtail' && hostID ? Number(hostID) : undefined,
clusterID: collectorType !== 'host-promtail' && clusterID ? Number(clusterID) : undefined,
targetDeployment: collectorType === 'k8s-fluentbit-sidecar' ? targetDeployment : undefined,
namespace: collectorType !== 'host-promtail' ? namespace : undefined,
logPath,
labels,
})
setOpen(false)
resetForm()
loadAll()
toast.success('采集器创建成功')
} catch (err: unknown) {
const message = err instanceof Error ? err.message : '创建采集器失败'
toast.error(message)
} finally {
setSubmitting(false)
}
},
[name, collectorType, lokiID, hostID, clusterID, targetDeployment, namespace, logPath, labels, resetForm, loadAll]
)
const handleDelete = useCallback(
async (id: number) => {
if (!confirm('确定删除此采集器?(将自动卸载)')) return
try {
await collectorApi.remove(id)
loadAll()
toast.success('采集器已删除')
} catch (err) {
console.error('Failed to delete collector:', err)
toast.error('删除采集器失败')
}
},
[loadAll]
)
const handleAction = useCallback(
async (id: number, action: 'install' | 'uninstall') => {
setBusy(id)
try {
await collectorApi[action](id)
addTimeout(loadAll, 3000)
toast.success(action === 'install' ? '部署指令已发送' : '卸载指令已发送')
} catch (err) {
console.error('Collector action failed:', err)
toast.error(action === 'install' ? '部署失败' : '卸载失败')
} finally {
addTimeout(() => setBusy(null), 3000)
}
},
[loadAll, addTimeout]
)
const isHostType = collectorType === 'host-promtail'
const isK8sType = collectorType !== 'host-promtail'
const isSidecarType = collectorType === 'k8s-fluentbit-sidecar'
return (
<div className="space-y-6">
<PageHeader
title="部署客户端"
description="部署日志采集器,将日志推送到关联的 Loki"
action={
<Dialog open={open} onOpenChange={setOpen}>
<DialogTrigger asChild>
<Button className="bg-emerald-600 hover:bg-emerald-700">
<Plus className="w-4 h-4 mr-1" />
新建采集器
</Button>
</DialogTrigger>
<DialogContent className="max-w-2xl max-h-[90vh] overflow-y-auto">
<DialogHeader>
<DialogTitle>新建日志采集器</DialogTitle>
</DialogHeader>
<form onSubmit={handleSubmit} className="space-y-4">
<div className="grid grid-cols-2 gap-4">
<div className="space-y-2">
<Label htmlFor="c-name">名称 *</Label>
<Input
id="c-name"
value={name}
onChange={(e) => setName(e.target.value)}
placeholder="app-logs-collector"
required
/>
</div>
<div className="space-y-2">
<Label>采集器类型</Label>
<Select
value={collectorType}
onValueChange={(v) =>
setCollectorType(v as 'host-promtail' | 'k8s-daemonset' | 'k8s-fluentbit-sidecar')
}
>
<SelectTrigger>
<SelectValue />
</SelectTrigger>
<SelectContent>
{COLLECTOR_TYPES.map((t) => (
<SelectItem key={t.value} value={t.value}>
{t.label}
</SelectItem>
))}
</SelectContent>
</Select>
</div>
</div>
<div className="space-y-2">
<Label>关联 Loki 部署 *</Label>
<Select value={lokiID} onValueChange={setLokiID}>
<SelectTrigger>
<SelectValue placeholder="选择已部署的 Loki(推送目标)" />
</SelectTrigger>
<SelectContent>
{deployments.map((d) => (
<SelectItem key={d.id} value={String(d.id)}>
{d.name}({statusLabel(d.status)})
</SelectItem>
))}
</SelectContent>
</Select>
</div>
{isHostType && (
<div className="space-y-2">
<Label>目标主机 *</Label>
<Select value={hostID} onValueChange={setHostID}>
<SelectTrigger>
<SelectValue placeholder="选择主机" />
</SelectTrigger>
<SelectContent>
{hosts.map((h) => (
<SelectItem key={h.id} value={String(h.id)}>
{h.name}({h.hostIP})
</SelectItem>
))}
</SelectContent>
</Select>
</div>
)}
{isK8sType && (
<>
<div className="space-y-2">
<Label>目标集群 *</Label>
<Select value={clusterID} onValueChange={setClusterID}>
<SelectTrigger>
<SelectValue placeholder="选择集群" />
</SelectTrigger>
<SelectContent>
{clusters.map((c) => (
<SelectItem key={c.id} value={String(c.id)}>
{c.name}({statusLabel(c.status)})
</SelectItem>
))}
</SelectContent>
</Select>
</div>
<div className="grid grid-cols-2 gap-4">
<div className="space-y-2">
<Label htmlFor="c-ns">命名空间</Label>
<Input
id="c-ns"
value={namespace}
onChange={(e) => setNamespace(e.target.value)}
placeholder={collectorType === 'k8s-daemonset' ? 'logging' : 'default'}
/>
</div>
{isSidecarType && (
<div className="space-y-2">
<Label htmlFor="c-deploy">目标 Deployment *</Label>
<Input
id="c-deploy"
value={targetDeployment}
onChange={(e) => setTargetDeployment(e.target.value)}
placeholder="my-app"
/>
</div>
)}
</div>
</>
)}
<div className="space-y-2">
<Label htmlFor="c-log">采集日志路径</Label>
<Input
id="c-log"
value={logPath}
onChange={(e) => setLogPath(e.target.value)}
placeholder={isHostType ? '/var/log/*.log' : '/var/log/app/*.log'}
/>
</div>
<Button
type="submit"
className="w-full bg-emerald-600 hover:bg-emerald-700"
disabled={submitting}
>
{submitting ? '创建中...' : '创建并部署'}
</Button>
</form>
</DialogContent>
</Dialog>
}
/>
{/* Collectors List */}
{loading ? (
<LoadingSpinner className="h-64" />
) : collectors.length === 0 ? (
<EmptyState
icon={RadioTower}
title="暂无采集器"
description="新建一个日志采集器,关联已部署的 Loki"
/>
) : (
<div className="grid grid-cols-1 lg:grid-cols-2 gap-4">
{collectors.map((c) => (
<CollectorCard
key={c.id}
collector={c}
busy={busy}
onInstall={(id) => handleAction(id, 'install')}
onUninstall={(id) => handleAction(id, 'uninstall')}
onDelete={handleDelete}
/>
))}
</div>
)}
</div>
)
})
// 子组件:采集器卡片
interface CollectorCardProps {
collector: Collector
busy: number | null
onInstall: (id: number) => void
onUninstall: (id: number) => void
onDelete: (id: number) => void
}
const CollectorCard = memo(function CollectorCard({
collector,
busy,
onInstall,
onUninstall,
onDelete,
}: CollectorCardProps) {
const meta = COLLECTOR_TYPE_META[collector.type] || {
label: collector.type,
icon: RadioTower,
color: 'bg-slate-100 text-slate-600',
}
const Icon = meta.icon
const isBusy = busy === collector.id
return (
<Card className="border-slate-200 dark:border-slate-800 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">
<Icon className="w-5 h-5 text-emerald-600 flex-shrink-0" />
<div className="min-w-0">
<h3 className="font-semibold text-slate-800 dark:text-white truncate">
{collector.name}
</h3>
<p className="text-xs text-slate-500">
关联 Loki:{collector.lokiDeployment?.name || '未知'}
</p>
</div>
</div>
<StatusBadge status={collector.status} />
</div>
<div className="space-y-1.5 text-xs text-slate-500 mb-3">
<div className="flex justify-between">
<span>类型</span>
<span className={`px-2 py-0.5 rounded-full text-xs font-medium ${meta.color}`}>
{meta.label}
</span>
</div>
{collector.host && (
<InfoRow label="主机" value={`${collector.host.name}(${collector.host.hostIP})`} />
)}
{collector.cluster && (
<InfoRow label="集群" value={collector.cluster.name} />
)}
{collector.targetDeployment && (
<InfoRow label="目标 Deployment" value={collector.targetDeployment} />
)}
{collector.namespace && <InfoRow label="命名空间" value={collector.namespace} />}
{collector.logPath && (
<InfoRow label="日志路径" value={collector.logPath} />
)}
{collector.statusMessage && (
<div className="p-2 bg-slate-50 dark:bg-slate-800 rounded text-xs mt-1">
{collector.statusMessage}
</div>
)}
</div>
<div className="flex gap-2 pt-3 border-t border-slate-100 dark:border-slate-800">
<Button
variant="outline"
size="sm"
className="flex-1 text-xs"
onClick={() => onInstall(collector.id)}
disabled={isBusy}
>
<Upload className="w-3 h-3 mr-1" />
{isBusy ? '处理中...' : '部署'}
</Button>
<Button
variant="outline"
size="sm"
className="flex-1 text-xs"
onClick={() => onUninstall(collector.id)}
disabled={isBusy}
>
<Download className="w-3 h-3 mr-1" />
卸载
</Button>
<Button
variant="outline"
size="sm"
className="text-red-500 hover:text-red-600 hover:bg-red-50"
onClick={() => onDelete(collector.id)}
>
<Trash2 className="w-3 h-3" />
</Button>
</div>
</CardContent>
</Card>
)
})
// 子组件:信息行
const InfoRow = memo(function InfoRow({
label,
value,
}: {
label: string
value: string
}) {
return (
<div className="flex justify-between">
<span>{label}</span>
<span className="font-medium text-slate-700 dark:text-slate-300 truncate max-w-[200px]">
{value}
</span>
</div>
)
})
export default Collectors
-404
View File
@@ -1,404 +0,0 @@
import { memo, useCallback, useEffect, useMemo, useRef, useState } from 'react'
import { useNavigate } from 'react-router'
import {
Rocket,
Server,
Monitor,
Activity,
TrendingUp,
CheckCircle,
} from 'lucide-react'
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card'
import { deploymentApi, clusterApi, hostApi } from '@/api'
import { statusLabel } from '@/lib/utils'
import { StatusIcon, getStatusColorClass } from '@/components/StatusBadge'
import { LoadingSpinner } from '@/components/LoadingSpinner'
import { EmptyState } from '@/components/EmptyState'
import type { DashboardStats, LokiDeployment, Cluster, Host } from '@/types'
// 统计卡片数据常量
const STATS_CONFIG = [
{
key: 'deployments' as const,
label: '部署总数',
icon: Rocket,
iconColor: 'text-emerald-600',
iconBg: 'bg-emerald-100 dark:bg-emerald-900/30',
getValue: (s: DashboardStats | null) => s?.totalDeployments || 0,
subLabel: (s: DashboardStats | null) => `${s?.running || 0} 个运行中`,
subIcon: TrendingUp,
subColor: 'text-emerald-500',
subTextColor: 'text-emerald-600',
},
{
key: 'clusters' as const,
label: '集群',
icon: Server,
iconColor: 'text-blue-600',
iconBg: 'bg-blue-100 dark:bg-blue-900/30',
getValue: (s: DashboardStats | null) => s?.clusterCount || 0,
subLabel: () => '已接入',
subIcon: CheckCircle,
subColor: 'text-emerald-500',
subTextColor: 'text-slate-500',
},
{
key: 'hosts' as const,
label: '主机',
icon: Monitor,
iconColor: 'text-purple-600',
iconBg: 'bg-purple-100 dark:bg-purple-900/30',
getValue: (s: DashboardStats | null) => s?.hostCount || 0,
subLabel: () => 'SSH 就绪',
subIcon: CheckCircle,
subColor: 'text-emerald-500',
subTextColor: 'text-slate-500',
},
{
key: 'status' as const,
label: '状态',
icon: Activity,
iconColor: 'text-orange-600',
iconBg: 'bg-orange-100 dark:bg-orange-900/30',
getValue: () => 0, // 状态卡片使用特殊渲染
isStatusCard: true,
},
]
const STATUS_ITEMS = [
{ key: 'running', label: '运行中', colorClass: 'text-emerald-600' },
{ key: 'failed', label: '失败', colorClass: 'text-red-600' },
{ key: 'pending', label: '等待中', colorClass: 'text-amber-600' },
] as const
const REFRESH_INTERVAL = 10000 // 10秒自动刷新
/**
* Dashboard 页面 - 全面优化版本
*
* 优化点:
* 1. 使用 React.memo 包裹组件,避免不必要的重渲染
* 2. 状态函数使用 useMemo 缓存(替代原来的getStatusIcon/getStatusColor)
* 3. 数据加载使用 useCallback 缓存引用
* 4. 自动刷新定时器添加清理函数,防止内存泄漏
* 5. 使用 StatusBadge/StatusIcon 公共组件替代重复的状态渲染逻辑
* 6. 提取常量配置避免重复创建
*/
const Dashboard = memo(function Dashboard() {
const [stats, setStats] = useState<DashboardStats | null>(null)
const [deployments, setDeployments] = useState<LokiDeployment[]>([])
const [clusters, setClusters] = useState<Cluster[]>([])
const [hosts, setHosts] = useState<Host[]>([])
const [loading, setLoading] = useState(true)
const navigate = useNavigate()
// 使用ref追踪组件是否已卸载,防止内存泄漏
const isMountedRef = useRef(true)
// 使用ref存储定时器ID以便清理
const intervalRef = useRef<ReturnType<typeof setInterval> | null>(null)
// 数据加载函数 - useCallback缓存引用
const loadDashboard = useCallback(async () => {
// 如果组件已卸载,不执行状态更新
if (!isMountedRef.current) return
try {
const [statsRes, deployRes, clusterRes, hostRes] = await Promise.all([
deploymentApi.stats(),
deploymentApi.list(1, 5),
clusterApi.list(1, 5),
hostApi.list(1, 5),
])
// 再次检查组件是否仍挂载
if (isMountedRef.current) {
setStats(statsRes)
setDeployments(deployRes.list)
setClusters(clusterRes.list)
setHosts(hostRes.list)
}
} catch (err) {
console.error('Failed to load dashboard:', err)
} finally {
if (isMountedRef.current) {
setLoading(false)
}
}
}, [])
// 初始化加载 + 自动刷新定时器
useEffect(() => {
isMountedRef.current = true
// 立即加载数据
loadDashboard()
// 设置自动刷新定时器
intervalRef.current = setInterval(loadDashboard, REFRESH_INTERVAL)
// 清理函数:组件卸载时清除定时器和标记
return () => {
isMountedRef.current = false
if (intervalRef.current) {
clearInterval(intervalRef.current)
intervalRef.current = null
}
}
}, [loadDashboard])
// 缓存导航处理函数
const navigateTo = useCallback(
(path: string) => () => navigate(path),
[navigate]
)
// 渲染状态概览数值
const statusSummary = useMemo(() => {
if (!stats) return null
return STATUS_ITEMS.map((item) => (
<div key={item.key} className="text-center">
<p className={`text-lg font-bold ${item.colorClass}`}>
{(stats[item.key as keyof DashboardStats] as number) || 0}
</p>
<p className="text-[10px] text-slate-400">{item.label}</p>
</div>
))
}, [stats])
if (loading) {
return <LoadingSpinner className="h-64" />
}
return (
<div className="space-y-6">
{/* Stats Cards */}
<div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-4">
{STATS_CONFIG.slice(0, 3).map((config) => {
const Icon = config.icon
const SubIcon = config.subIcon
return (
<Card key={config.key} className="border-slate-200 dark:border-slate-800">
<CardContent className="p-6">
<div className="flex items-center justify-between">
<div>
<p className="text-sm text-slate-500">{config.label}</p>
<p className="text-3xl font-bold text-slate-900 dark:text-white mt-1">
{config.getValue(stats)}
</p>
</div>
<div
className={`w-12 h-12 rounded-xl ${config.iconBg} flex items-center justify-center`}
>
<Icon className={`w-6 h-6 ${config.iconColor}`} />
</div>
</div>
<div className="flex items-center gap-2 mt-4">
{SubIcon && <SubIcon className={`w-4 h-4 ${config.subColor}`} />}
<span className={`text-xs ${config.subTextColor}`}>
{config.subLabel?.(stats)}
</span>
</div>
</CardContent>
</Card>
)
})}
{/* Status Overview Card */}
<Card className="border-slate-200 dark:border-slate-800">
<CardContent className="p-6">
<div className="flex items-center justify-between">
<div>
<p className="text-sm text-slate-500">状态</p>
<div className="flex gap-3 mt-1">{statusSummary}</div>
</div>
<div className="w-12 h-12 rounded-xl bg-orange-100 dark:bg-orange-900/30 flex items-center justify-center">
<Activity className="w-6 h-6 text-orange-600" />
</div>
</div>
</CardContent>
</Card>
</div>
{/* Recent Deployments & Quick Resources */}
<div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
{/* Recent Deployments */}
<RecentDeploymentsCard
deployments={deployments}
onViewAll={navigateTo('/deployments')}
/>
{/* Quick Resources */}
<div className="space-y-4">
<ResourceListCard
title="集群"
icon={<Server className="w-4 h-4 text-blue-500" />}
items={clusters.slice(0, 3)}
onManage={navigateTo('/clusters')}
getItemIcon={() => <Server className="w-4 h-4 text-blue-500" />}
getItemLabel={(c) => c.name}
getItemStatus={(c) => c.status}
/>
<ResourceListCard
title="主机"
icon={<Monitor className="w-4 h-4 text-purple-500" />}
items={hosts.slice(0, 3)}
onManage={navigateTo('/hosts')}
getItemIcon={() => <Monitor className="w-4 h-4 text-purple-500" />}
getItemLabel={(h) => h.name}
getItemStatus={(h) => h.status}
getItemExtra={(h) => h.hostIP}
/>
</div>
</div>
</div>
)
})
// 子组件:最近部署卡片 - 独立memo优化
const RecentDeploymentsCard = memo(function RecentDeploymentsCard({
deployments,
onViewAll,
}: {
deployments: LokiDeployment[]
onViewAll: () => void
}) {
const navigate = useNavigate()
return (
<Card className="border-slate-200 dark:border-slate-800">
<CardHeader className="pb-3">
<div className="flex items-center justify-between">
<CardTitle className="text-base">最近部署</CardTitle>
<button
onClick={onViewAll}
className="text-xs text-emerald-600 hover:text-emerald-700 font-medium"
>
查看全部
</button>
</div>
</CardHeader>
<CardContent>
<div className="space-y-3">
{deployments.length === 0 ? (
<EmptyState
icon={Rocket}
title="暂无部署"
description="创建你的第一个 Loki 部署"
/>
) : (
deployments.map((d) => (
<div
key={d.id}
className="flex items-center justify-between p-3 rounded-lg bg-slate-50 dark:bg-slate-800/50 hover:bg-slate-100 dark:hover:bg-slate-800 transition-colors cursor-pointer"
onClick={() => navigate('/deployments')}
>
<div className="flex items-center gap-3 min-w-0">
<StatusIcon status={d.status} size="sm" />
<div className="min-w-0">
<p className="text-sm font-medium text-slate-800 dark:text-slate-200 truncate">
{d.name}
</p>
<p className="text-xs text-slate-500">
{d.mode} &middot; {d.namespace || 'loki'}
</p>
</div>
</div>
<span
className={`px-2 py-0.5 rounded-full text-xs font-medium flex-shrink-0 ${getStatusColorClass(
d.status
)}`}
>
{statusLabel(d.status)}
</span>
</div>
))
)}
</div>
</CardContent>
</Card>
)
})
// 子组件:资源列表卡片 - 独立memo优化
// 用具体结构类型而非泛型:memo 包裹泛型组件会导致 TS 无法从 props 推断 T,
// 退化为约束类型 {id:number},使 getItemLabel/Status 中访问 name/status 报错。
interface ResourceItem {
id: number
name: string
status: string
hostIP?: string
}
interface ResourceListCardProps {
title: string
icon: React.ReactNode
items: ResourceItem[]
onManage: () => void
getItemIcon: (item: ResourceItem) => React.ReactNode
getItemLabel: (item: ResourceItem) => string
getItemStatus: (item: ResourceItem) => string
getItemExtra?: (item: ResourceItem) => string | undefined
}
const ResourceListCard = memo(function ResourceListCard({
title,
icon,
items,
onManage,
getItemIcon,
getItemLabel,
getItemStatus,
getItemExtra,
}: ResourceListCardProps) {
return (
<Card className="border-slate-200 dark:border-slate-800">
<CardHeader className="pb-3">
<div className="flex items-center justify-between">
<CardTitle className="text-base flex items-center gap-2">
{icon}
{title}
</CardTitle>
<button
onClick={onManage}
className="text-xs text-emerald-600 hover:text-emerald-700 font-medium"
>
管理
</button>
</div>
</CardHeader>
<CardContent>
<div className="space-y-2">
{items.length === 0 ? (
<p className="text-sm text-slate-400 text-center py-4">暂无{title}</p>
) : (
items.map((item) => (
<div
key={item.id}
className="flex items-center justify-between p-2 rounded-md hover:bg-slate-50 dark:hover:bg-slate-800 transition-colors"
>
<div className="flex items-center gap-2 min-w-0">
{getItemIcon(item)}
<span className="text-sm truncate">{getItemLabel(item)}</span>
{getItemExtra?.(item) && (
<span className="text-xs text-slate-400 flex-shrink-0">
{getItemExtra(item)}
</span>
)}
</div>
<span
className={`px-2 py-0.5 rounded-full text-xs flex-shrink-0 ${getStatusColorClass(
getItemStatus(item)
)}`}
>
{statusLabel(getItemStatus(item))}
</span>
</div>
))
)}
</div>
</CardContent>
</Card>
)
})
export default Dashboard
-743
View File
@@ -1,743 +0,0 @@
import { memo, useCallback, useEffect, useMemo, useRef, useState } from 'react'
import {
Rocket,
Plus,
Play,
Square,
RotateCw,
Trash2,
Terminal,
ExternalLink,
} 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 { Textarea } from '@/components/ui/textarea'
import {
Dialog,
DialogContent,
DialogHeader,
DialogTitle,
DialogTrigger,
} from '@/components/ui/dialog'
import { Card, CardContent } from '@/components/ui/card'
import {
Select,
SelectContent,
SelectItem,
SelectTrigger,
SelectValue,
} from '@/components/ui/select'
import { deploymentApi, clusterApi, hostApi, storageApi } from '@/api'
import { statusLabel } from '@/lib/utils'
import { StatusBadge, StatusIcon } from '@/components/StatusBadge'
import { LoadingSpinner } from '@/components/LoadingSpinner'
import { EmptyState } from '@/components/EmptyState'
import { PageHeader } from '@/components/PageHeader'
import { toast } from 'sonner'
import type { LokiDeployment, Cluster, Host, StorageConfig, DeploymentLog } from '@/types'
// 表单默认值常量 - 避免重复创建
const FORM_DEFAULTS = {
name: '',
description: '',
version: '3.0.0',
mode: 'k8s-helm' as 'k8s-helm' | 'k8s-yaml' | 'host-binary',
clusterID: '',
hostID: '',
namespace: 'loki',
storageConfigID: '',
authEnabled: false,
retentionDays: 30,
replicas: 1,
resourcesCPU: '500m',
resourcesMem: '512Mi',
storageSize: '10Gi',
}
/**
* Deployments 页面 - 全面优化版本
*
* 优化点:
* 1. React.memo 包裹整个组件
* 2. 使用 useReducer 简化大量 useState(替代原始15+个 useState)
* 3. 所有操作函数使用 useCallback 缓存
* 4. 部署卡片列表使用 useMemo 优化渲染
* 5. setTimeout 添加清理函数,修复内存泄漏
* 6. alert() 替换为 sonner toast 错误提示
* 7. 使用 StatusBadge 公共组件替代重复状态函数
* 8. 定时器使用 ref 存储以便清理
*/
const Deployments = memo(function Deployments() {
// === State ===
const [deployments, setDeployments] = useState<LokiDeployment[]>([])
const [clusters, setClusters] = useState<Cluster[]>([])
const [hosts, setHosts] = useState<Host[]>([])
const [storages, setStorages] = useState<StorageConfig[]>([])
const [loading, setLoading] = useState(true)
const [open, setOpen] = useState(false)
const [logsOpen, setLogsOpen] = useState(false)
const [selectedDeployment, setSelectedDeployment] = useState<LokiDeployment | null>(null)
const [logs, setLogs] = useState<DeploymentLog[]>([])
const [deploying, setDeploying] = useState<number | null>(null)
const [submitting, setSubmitting] = useState(false)
// 表单状态 - 合并为一个对象减少state数量
const [form, setForm] = useState({ ...FORM_DEFAULTS })
// 使用ref存储所有定时器ID以便清理
const timeoutsRef = useRef<ReturnType<typeof setTimeout>[]>([])
// 组件卸载时清理所有定时器
useEffect(() => {
return () => {
timeoutsRef.current.forEach((id) => clearTimeout(id))
timeoutsRef.current = []
}
}, [])
// 添加定时器的辅助函数
const addTimeout = useCallback((cb: () => void, delay: number) => {
const id = setTimeout(cb, delay)
timeoutsRef.current.push(id)
return id
}, [])
// === 数据加载 ===
const loadAll = useCallback(async () => {
try {
const [deployRes, clusterRes, hostRes, storageRes] = await Promise.all([
deploymentApi.list(1, 100),
clusterApi.list(1, 100),
hostApi.list(1, 100),
storageApi.list(1, 100),
])
setDeployments(deployRes.list)
setClusters(clusterRes.list)
setHosts(hostRes.list)
setStorages(storageRes.list)
} catch (err) {
console.error('Failed to load deployments:', err)
toast.error('加载部署数据失败')
} finally {
setLoading(false)
}
}, [])
useEffect(() => {
loadAll()
}, [loadAll])
// === 表单处理 ===
const resetForm = useCallback(() => {
setForm({ ...FORM_DEFAULTS })
}, [])
const handleFormChange = useCallback(
<K extends keyof typeof FORM_DEFAULTS>(key: K, value: (typeof FORM_DEFAULTS)[K]) => {
setForm((prev) => ({ ...prev, [key]: value }))
},
[]
)
const handleSubmit = useCallback(
async (e: React.FormEvent) => {
e.preventDefault()
setSubmitting(true)
try {
const clusterIDNum = form.clusterID ? Number(form.clusterID) : undefined
const hostIDNum = form.hostID ? Number(form.hostID) : undefined
const storageIDNum = form.storageConfigID ? Number(form.storageConfigID) : 0
await deploymentApi.create({
name: form.name,
description: form.description,
version: form.version,
mode: form.mode,
clusterID: clusterIDNum,
hostID: hostIDNum,
namespace: form.namespace,
storageConfigID: storageIDNum,
authEnabled: form.authEnabled,
retentionDays: form.retentionDays,
replicas: form.replicas,
resourcesCPU: form.resourcesCPU,
resourcesMem: form.resourcesMem,
storageSize: form.storageSize,
})
setOpen(false)
resetForm()
loadAll()
toast.success('部署创建成功')
} catch (err: unknown) {
const message = err instanceof Error ? err.message : '创建部署失败'
toast.error(message)
} finally {
setSubmitting(false)
}
},
[form, resetForm, loadAll]
)
// === 操作函数 - useCallback 缓存 ===
const handleDeploy = useCallback(
async (id: number) => {
setDeploying(id)
try {
await deploymentApi.deploy(id)
addTimeout(loadAll, 2000)
} catch (err) {
console.error('Failed to deploy:', err)
toast.error('部署失败')
} finally {
addTimeout(() => setDeploying(null), 5000)
}
},
[loadAll, addTimeout]
)
const handleStop = useCallback(
async (id: number) => {
try {
await deploymentApi.stop(id)
loadAll()
toast.success('服务已停止')
} catch (err) {
console.error('Failed to stop:', err)
toast.error('停止失败')
}
},
[loadAll]
)
const handleRestart = useCallback(
async (id: number) => {
setDeploying(id)
try {
await deploymentApi.restart(id)
addTimeout(loadAll, 3000)
toast.success('重启指令已发送')
} catch (err) {
console.error('Failed to restart:', err)
toast.error('重启失败')
} finally {
addTimeout(() => setDeploying(null), 5000)
}
},
[loadAll, addTimeout]
)
const handleDelete = useCallback(
async (id: number) => {
if (!confirm('确定删除此部署?')) return
try {
await deploymentApi.remove(id)
loadAll()
toast.success('部署已删除')
} catch (err) {
console.error('Failed to delete:', err)
toast.error('删除失败')
}
},
[loadAll]
)
const viewLogs = useCallback(
async (deployment: LokiDeployment) => {
setSelectedDeployment(deployment)
setLogsOpen(true)
try {
const res = await deploymentApi.logs(deployment.id, 1, 100)
setLogs(res.list)
} catch (err) {
console.error('Failed to load logs:', err)
toast.error('加载日志失败')
}
},
[]
)
// === 辅助函数 ===
const getTargetLabel = useCallback((d: LokiDeployment) => {
if (d.cluster) return `集群:${d.cluster.name}`
if (d.host) return `主机:${d.host.name}`
return '未知'
}, [])
// === 渲染优化 ===
const deploymentCards = useMemo(
() =>
deployments.map((d) => (
<DeploymentCard
key={d.id}
deployment={d}
deploying={deploying}
onDeploy={handleDeploy}
onStop={handleStop}
onRestart={handleRestart}
onDelete={handleDelete}
onViewLogs={viewLogs}
getTargetLabel={getTargetLabel}
/>
)),
[deployments, deploying, handleDeploy, handleStop, handleRestart, handleDelete, viewLogs, getTargetLabel]
)
return (
<div className="space-y-6">
{/* Header */}
<PageHeader
title="部署Loki"
description="部署与管理 Grafana Loki 日志聚合服务"
action={
<Dialog open={open} onOpenChange={setOpen}>
<DialogTrigger asChild>
<Button className="bg-emerald-600 hover:bg-emerald-700">
<Plus className="w-4 h-4 mr-1" />
新建部署
</Button>
</DialogTrigger>
<DialogContent className="max-w-2xl max-h-[90vh] overflow-y-auto">
<DialogHeader>
<DialogTitle>创建 Loki 部署</DialogTitle>
</DialogHeader>
<DeploymentForm
form={form}
onChange={handleFormChange}
onSubmit={handleSubmit}
submitting={submitting}
clusters={clusters}
hosts={hosts}
storages={storages}
/>
</DialogContent>
</Dialog>
}
/>
{/* Deployments Grid */}
{loading ? (
<LoadingSpinner className="h-64" />
) : deployments.length === 0 ? (
<EmptyState
icon={Rocket}
title="暂无部署"
description="创建你的第一个 Loki 部署"
/>
) : (
<div className="grid grid-cols-1 lg:grid-cols-2 gap-4">{deploymentCards}</div>
)}
{/* Logs Dialog */}
<Dialog open={logsOpen} onOpenChange={setLogsOpen}>
<DialogContent className="max-w-4xl max-h-[80vh]">
<DialogHeader>
<DialogTitle className="flex items-center gap-2">
<Terminal className="w-5 h-5 text-emerald-500" />
部署日志 - {selectedDeployment?.name}
</DialogTitle>
</DialogHeader>
<LogViewer logs={logs} />
</DialogContent>
</Dialog>
</div>
)
})
// 子组件:部署卡片 - 独立memo优化
interface DeploymentCardProps {
deployment: LokiDeployment
deploying: number | null
onDeploy: (id: number) => void
onStop: (id: number) => void
onRestart: (id: number) => void
onDelete: (id: number) => void
onViewLogs: (d: LokiDeployment) => void
getTargetLabel: (d: LokiDeployment) => string
}
const DeploymentCard = memo(function DeploymentCard({
deployment: d,
deploying,
onDeploy,
onStop,
onRestart,
onDelete,
onViewLogs,
getTargetLabel,
}: DeploymentCardProps) {
const isDeploying = d.status === 'deploying'
const isBusy = deploying === d.id
const canDeploy = d.status === 'pending' || d.status === 'failed' || d.status === 'stopped'
return (
<Card className="border-slate-200 dark:border-slate-800 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">
<StatusIcon status={d.status} size="md" />
<div className="min-w-0">
<h3 className="font-semibold text-slate-800 dark:text-white truncate">
{d.name}
</h3>
<p className="text-xs text-slate-500">{d.uuid}</p>
</div>
</div>
<StatusBadge status={d.status} />
</div>
<p className="text-sm text-slate-500 mb-3">{d.description || '无描述'}</p>
<div className="space-y-1.5 text-xs text-slate-500 mb-4">
<InfoRow label="方式" value={d.mode} />
<InfoRow label="版本" value={d.version} />
<InfoRow label="目标" value={getTargetLabel(d)} />
<InfoRow label="命名空间" value={d.namespace || 'loki'} />
<InfoRow label="副本数" value={String(d.replicas)} />
<InfoRow label="存储" value={d.storageConfig?.name || '本地'} />
{d.endpoint && (
<InfoRow label="访问地址" value={d.endpoint} valueClass="text-emerald-600 truncate max-w-[200px]" />
)}
{d.statusMessage && (
<div className="p-2 bg-slate-50 dark:bg-slate-800 rounded text-xs">
{d.statusMessage}
</div>
)}
</div>
<div className="flex gap-1 pt-3 border-t border-slate-100 dark:border-slate-800">
{canDeploy ? (
<Button
variant="outline"
size="sm"
className="flex-1 text-xs bg-emerald-50 text-emerald-700 hover:bg-emerald-100 border-emerald-200"
onClick={() => onDeploy(d.id)}
disabled={isBusy}
>
<Play className="w-3 h-3 mr-1" />
{isBusy ? '部署中...' : '部署'}
</Button>
) : isDeploying ? (
<Button variant="outline" size="sm" className="flex-1 text-xs" disabled>
<RotateCw className="w-3 h-3 mr-1 animate-spin" />
部署中...
</Button>
) : (
<>
<Button variant="outline" size="sm" className="text-xs" onClick={() => onStop(d.id)}>
<Square className="w-3 h-3 mr-1" />
停止
</Button>
<Button
variant="outline"
size="sm"
className="text-xs"
onClick={() => onRestart(d.id)}
disabled={isBusy}
>
<RotateCw className={`w-3 h-3 mr-1 ${isBusy ? 'animate-spin' : ''}`} />
重启
</Button>
</>
)}
<Button variant="outline" size="sm" className="text-xs" onClick={() => onViewLogs(d)}>
<Terminal className="w-3 h-3 mr-1" />
日志
</Button>
{d.endpoint && (
<Button
variant="outline"
size="sm"
className="text-xs text-emerald-600 hover:text-emerald-700"
onClick={() => window.open(d.endpoint, '_blank')}
title="浏览器访问"
>
<ExternalLink className="w-3 h-3 mr-1" />
访问
</Button>
)}
<Button
variant="outline"
size="sm"
className="text-red-500 hover:text-red-600 hover:bg-red-50"
onClick={() => onDelete(d.id)}
>
<Trash2 className="w-3 h-3" />
</Button>
</div>
</CardContent>
</Card>
)
})
// 子组件:信息行
const InfoRow = memo(function InfoRow({
label,
value,
valueClass,
}: {
label: string
value: string
valueClass?: string
}) {
return (
<div className="flex justify-between">
<span>{label}</span>
<span className={`font-medium text-slate-700 dark:text-slate-300 ${valueClass || ''}`}>
{value}
</span>
</div>
)
})
// 子组件:日志查看器
const LogViewer = memo(function LogViewer({ logs }: { logs: DeploymentLog[] }) {
return (
<div className="bg-slate-900 text-green-400 font-mono text-xs p-4 rounded-lg h-96 overflow-auto">
{logs.length === 0 ? (
<p className="text-slate-500">暂无日志...</p>
) : (
logs.map((log) => (
<div
key={log.id}
className={`mb-1 ${
log.level === 'error'
? 'text-red-400'
: log.level === 'warn'
? 'text-amber-400'
: log.level === 'success'
? 'text-emerald-400'
: 'text-green-400'
}`}
>
<span className="text-slate-500">
[{new Date(log.createdAt).toLocaleTimeString()}]
</span>{' '}
<span className="font-bold uppercase">{log.level}</span> {log.message}
</div>
))
)}
</div>
)
})
// 子组件:部署表单
interface DeploymentFormProps {
form: typeof FORM_DEFAULTS
onChange: <K extends keyof typeof FORM_DEFAULTS>(key: K, value: (typeof FORM_DEFAULTS)[K]) => void
onSubmit: (e: React.FormEvent) => void
submitting: boolean
clusters: Cluster[]
hosts: Host[]
storages: StorageConfig[]
}
const DeploymentForm = memo(function DeploymentForm({
form,
onChange,
onSubmit,
submitting,
clusters,
hosts,
storages,
}: DeploymentFormProps) {
const isK8s = form.mode === 'k8s-helm' || form.mode === 'k8s-yaml'
const isHost = form.mode === 'host-binary'
return (
<form onSubmit={onSubmit} className="space-y-4">
<div className="space-y-2">
<Label htmlFor="d-name">部署名称 *</Label>
<Input
id="d-name"
value={form.name}
onChange={(e) => onChange('name', e.target.value)}
placeholder="production-loki"
required
/>
</div>
<div className="space-y-2">
<Label htmlFor="d-desc">描述</Label>
<Textarea
id="d-desc"
value={form.description}
onChange={(e) => onChange('description', e.target.value)}
placeholder="生产环境 Loki 日志服务"
/>
</div>
<div className="grid grid-cols-2 gap-4">
<div className="space-y-2">
<Label>版本</Label>
<Select value={form.version} onValueChange={(v) => onChange('version', v)}>
<SelectTrigger>
<SelectValue />
</SelectTrigger>
<SelectContent>
<SelectItem value="3.0.0">3.0.0</SelectItem>
<SelectItem value="2.9.8">2.9.8</SelectItem>
<SelectItem value="2.9.7">2.9.7</SelectItem>
<SelectItem value="2.9.6">2.9.6</SelectItem>
</SelectContent>
</Select>
</div>
<div className="space-y-2">
<Label>部署方式</Label>
<Select
value={form.mode}
onValueChange={(v) =>
onChange('mode', v as 'k8s-helm' | 'k8s-yaml' | 'host-binary')
}
>
<SelectTrigger>
<SelectValue />
</SelectTrigger>
<SelectContent>
<SelectItem value="k8s-helm">K8s Helm 部署</SelectItem>
<SelectItem value="k8s-yaml">K8s YAML 部署</SelectItem>
<SelectItem value="host-binary">主机二进制部署</SelectItem>
</SelectContent>
</Select>
</div>
</div>
{isK8s && (
<>
<div className="space-y-2">
<Label>目标集群 *</Label>
<Select value={form.clusterID} onValueChange={(v) => onChange('clusterID', v)}>
<SelectTrigger>
<SelectValue placeholder="请选择集群" />
</SelectTrigger>
<SelectContent>
{clusters.map((c) => (
<SelectItem key={c.id} value={String(c.id)}>
{c.name}({statusLabel(c.status)})
</SelectItem>
))}
</SelectContent>
</Select>
</div>
<div className="space-y-2">
<Label htmlFor="d-ns">命名空间</Label>
<Input
id="d-ns"
value={form.namespace}
onChange={(e) => onChange('namespace', e.target.value)}
placeholder="loki"
/>
</div>
</>
)}
{isHost && (
<div className="space-y-2">
<Label>目标主机 *</Label>
<Select value={form.hostID} onValueChange={(v) => onChange('hostID', v)}>
<SelectTrigger>
<SelectValue placeholder="请选择主机" />
</SelectTrigger>
<SelectContent>
{hosts.map((h) => (
<SelectItem key={h.id} value={String(h.id)}>
{h.name}({h.hostIP})
</SelectItem>
))}
</SelectContent>
</Select>
</div>
)}
<div className="space-y-2">
<Label>存储配置</Label>
<Select value={form.storageConfigID} onValueChange={(v) => onChange('storageConfigID', v)}>
<SelectTrigger>
<SelectValue placeholder="请选择存储(可选)" />
</SelectTrigger>
<SelectContent>
<SelectItem value="0">本地存储(默认)</SelectItem>
{storages.map((s) => (
<SelectItem key={s.id} value={String(s.id)}>
{s.name}({s.storageType})
</SelectItem>
))}
</SelectContent>
</Select>
</div>
<div className="grid grid-cols-3 gap-4">
<div className="space-y-2">
<Label htmlFor="d-replicas">副本数</Label>
<Input
id="d-replicas"
type="number"
min={1}
max={10}
value={form.replicas}
onChange={(e) => onChange('replicas', Number(e.target.value))}
/>
</div>
<div className="space-y-2">
<Label htmlFor="d-retention">保留天数</Label>
<Input
id="d-retention"
type="number"
min={1}
value={form.retentionDays}
onChange={(e) => onChange('retentionDays', Number(e.target.value))}
/>
</div>
<div className="space-y-2">
<Label htmlFor="d-size">存储容量</Label>
<Input
id="d-size"
value={form.storageSize}
onChange={(e) => onChange('storageSize', e.target.value)}
placeholder="10Gi"
/>
</div>
</div>
<div className="grid grid-cols-2 gap-4">
<div className="space-y-2">
<Label htmlFor="d-cpu">CPU</Label>
<Input
id="d-cpu"
value={form.resourcesCPU}
onChange={(e) => onChange('resourcesCPU', e.target.value)}
placeholder="500m"
/>
</div>
<div className="space-y-2">
<Label htmlFor="d-mem">内存</Label>
<Input
id="d-mem"
value={form.resourcesMem}
onChange={(e) => onChange('resourcesMem', e.target.value)}
placeholder="512Mi"
/>
</div>
</div>
<div className="flex items-center gap-2">
<Switch
id="d-auth"
checked={form.authEnabled}
onCheckedChange={(v) => onChange('authEnabled', v)}
/>
<Label htmlFor="d-auth">启用多租户鉴权</Label>
</div>
<Button
type="submit"
className="w-full bg-emerald-600 hover:bg-emerald-700"
disabled={submitting}
>
{submitting ? '创建中...' : '创建部署'}
</Button>
</form>
)
})
export default Deployments
-633
View File
@@ -1,633 +0,0 @@
import { memo, useCallback, useEffect, useRef, useState } from 'react'
import {
Monitor,
Plus,
RefreshCw,
Trash2,
Eye,
Terminal,
Key,
Lock,
} from 'lucide-react'
import { Button } from '@/components/ui/button'
import { Input } from '@/components/ui/input'
import { Label } from '@/components/ui/label'
import { Textarea } from '@/components/ui/textarea'
import {
Dialog,
DialogContent,
DialogHeader,
DialogTitle,
DialogTrigger,
} from '@/components/ui/dialog'
import { Card, CardContent } from '@/components/ui/card'
import { hostApi } from '@/api'
import { StatusBadge } from '@/components/StatusBadge'
import { LoadingSpinner } from '@/components/LoadingSpinner'
import { EmptyState } from '@/components/EmptyState'
import { PageHeader } from '@/components/PageHeader'
import { toast } from 'sonner'
import type { Host, HostInfo } from '@/types'
// 使用率颜色阈值 - 常量提取
const usageColor = (v: number) =>
v >= 90 ? 'bg-red-500' : v >= 70 ? 'bg-amber-500' : 'bg-emerald-500'
/**
* Hosts 页面 - 优化版本
*
* 优化点:
* 1. React.memo 包裹组件
* 2. 所有操作函数使用 useCallback 缓存
* 3. alert() 替换为 sonner toast
* 4. setTimeout 使用 ref 管理
* 5. 使用公共组件替代重复代码
*/
const Hosts = memo(function Hosts() {
const [hosts, setHosts] = useState<Host[]>([])
const [loading, setLoading] = useState(true)
const [open, setOpen] = useState(false)
const [detailOpen, setDetailOpen] = useState(false)
const [terminalOpen, setTerminalOpen] = useState(false)
const [selectedHost, setSelectedHost] = useState<Host | null>(null)
const [hostInfo, setHostInfo] = useState<HostInfo | null>(null)
const [validating, setValidating] = useState<number | null>(null)
// Terminal state
const [command, setCommand] = useState('')
const [terminalOutput, setTerminalOutput] = useState('')
const [executing, setExecuting] = useState(false)
// Form state
const [name, setName] = useState('')
const [hostIP, setHostIP] = useState('')
const [port, setPort] = useState(22)
const [user, setUser] = useState('root')
const [authType, setAuthType] = useState<'password' | 'key'>('password')
const [password, setPassword] = useState('')
const [privateKey, setPrivateKey] = useState('')
const [keyPhrase, setKeyPhrase] = useState('')
const [labels, setLabels] = useState('')
const [submitting, setSubmitting] = useState(false)
const timeoutsRef = useRef<ReturnType<typeof setTimeout>[]>([])
useEffect(() => {
return () => {
timeoutsRef.current.forEach((id) => clearTimeout(id))
}
}, [])
const addTimeout = useCallback((cb: () => void, delay: number) => {
const id = setTimeout(cb, delay)
timeoutsRef.current.push(id)
return id
}, [])
const loadHosts = useCallback(async () => {
try {
const res = await hostApi.list(1, 100)
setHosts(res.list)
} catch (err) {
console.error('Failed to load hosts:', err)
toast.error('加载主机数据失败')
} finally {
setLoading(false)
}
}, [])
useEffect(() => {
loadHosts()
}, [loadHosts])
const resetForm = useCallback(() => {
setName('')
setHostIP('')
setPort(22)
setUser('root')
setAuthType('password')
setPassword('')
setPrivateKey('')
setKeyPhrase('')
setLabels('')
}, [])
const handleSubmit = useCallback(
async (e: React.FormEvent) => {
e.preventDefault()
setSubmitting(true)
try {
await hostApi.create({
name,
hostIP,
port,
user,
authType,
password: authType === 'password' ? password : undefined,
privateKey: authType === 'key' ? privateKey : undefined,
keyPhrase: authType === 'key' ? keyPhrase : undefined,
labels,
})
setOpen(false)
resetForm()
loadHosts()
toast.success('主机添加成功')
} catch (err: unknown) {
const message = err instanceof Error ? err.message : '添加主机失败'
toast.error(message)
} finally {
setSubmitting(false)
}
},
[name, hostIP, port, user, authType, password, privateKey, keyPhrase, labels, resetForm, loadHosts]
)
const handleDelete = useCallback(
async (id: number) => {
if (!confirm('确定删除此主机?')) return
try {
await hostApi.remove(id)
loadHosts()
toast.success('主机已删除')
} catch (err) {
console.error('Failed to delete host:', err)
toast.error('删除主机失败')
}
},
[loadHosts]
)
const handleValidate = useCallback(
async (id: number) => {
setValidating(id)
try {
await hostApi.validate(id)
addTimeout(loadHosts, 3000)
toast.success('验证指令已发送')
} catch (err) {
console.error('Failed to validate host:', err)
toast.error('验证失败')
} finally {
addTimeout(() => setValidating(null), 3000)
}
},
[loadHosts, addTimeout]
)
const viewHostInfo = useCallback(
async (host: Host) => {
setSelectedHost(host)
setHostInfo(null)
setDetailOpen(true)
try {
const info = await hostApi.getInfo(host.id)
setHostInfo(info)
} catch (err) {
console.error('Failed to get host info:', err)
toast.error('加载主机详情失败')
}
},
[]
)
const openTerminal = useCallback((host: Host) => {
setSelectedHost(host)
setTerminalOpen(true)
setTerminalOutput(`已连接到 ${host.name} (${host.hostIP})\n输入命令后按"执行"...\n`)
setCommand('')
}, [])
const executeCommand = useCallback(async () => {
if (!selectedHost || !command.trim()) return
setExecuting(true)
setTerminalOutput((prev) => prev + `\n$ ${command}\n`)
try {
const res = await hostApi.execute(selectedHost.id, command)
setTerminalOutput((prev) => prev + (res.stdout || '') + (res.stderr || '') + '\n')
} catch (err: unknown) {
const message = err instanceof Error ? err.message : '命令执行失败'
setTerminalOutput((prev) => prev + `错误:${message}\n`)
} finally {
setExecuting(false)
setCommand('')
}
}, [selectedHost, command])
return (
<div className="space-y-6">
<PageHeader
title="主机管理"
description="管理用于二进制方式部署 Loki 的 SSH 主机"
action={
<Dialog open={open} onOpenChange={setOpen}>
<DialogTrigger asChild>
<Button className="bg-emerald-600 hover:bg-emerald-700">
<Plus className="w-4 h-4 mr-1" />
添加主机
</Button>
</DialogTrigger>
<DialogContent className="max-w-2xl max-h-[90vh] overflow-y-auto">
<DialogHeader>
<DialogTitle>添加 SSH 主机</DialogTitle>
</DialogHeader>
<form onSubmit={handleSubmit} className="space-y-4">
<div className="grid grid-cols-2 gap-4">
<div className="space-y-2">
<Label htmlFor="h-name">名称 *</Label>
<Input
id="h-name"
value={name}
onChange={(e) => setName(e.target.value)}
placeholder="loki-server-1"
required
/>
</div>
<div className="space-y-2">
<Label htmlFor="h-ip">主机 IP *</Label>
<Input
id="h-ip"
value={hostIP}
onChange={(e) => setHostIP(e.target.value)}
placeholder="192.168.1.100"
required
/>
</div>
</div>
<div className="grid grid-cols-2 gap-4">
<div className="space-y-2">
<Label htmlFor="h-port">端口</Label>
<Input
id="h-port"
type="number"
value={port}
onChange={(e) => setPort(Number(e.target.value))}
placeholder="22"
/>
</div>
<div className="space-y-2">
<Label htmlFor="h-user">用户名 *</Label>
<Input
id="h-user"
value={user}
onChange={(e) => setUser(e.target.value)}
placeholder="root"
required
/>
</div>
</div>
<div className="space-y-2">
<Label>认证方式</Label>
<div className="flex gap-4">
<label className="flex items-center gap-2 cursor-pointer">
<input
type="radio"
name="authType"
value="password"
checked={authType === 'password'}
onChange={() => setAuthType('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={authType === 'key'}
onChange={() => setAuthType('key')}
/>
<Key className="w-4 h-4" />
<span className="text-sm">SSH 密钥</span>
</label>
</div>
</div>
{authType === 'password' ? (
<div className="space-y-2">
<Label htmlFor="h-password">密码 *</Label>
<Input
id="h-password"
type="password"
value={password}
onChange={(e) => setPassword(e.target.value)}
placeholder="SSH 登录密码"
required
/>
</div>
) : (
<>
<div className="space-y-2">
<Label htmlFor="h-key">私钥 *</Label>
<Textarea
id="h-key"
value={privateKey}
onChange={(e) => setPrivateKey(e.target.value)}
placeholder="-----BEGIN OPENSSH PRIVATE KEY-----"
required
className="min-h-[120px] font-mono text-xs"
/>
</div>
<div className="space-y-2">
<Label htmlFor="h-phrase">密钥口令(可选)</Label>
<Input
id="h-phrase"
type="password"
value={keyPhrase}
onChange={(e) => setKeyPhrase(e.target.value)}
placeholder="无口令则留空"
/>
</div>
</>
)}
<div className="space-y-2">
<Label htmlFor="h-labels">标签(JSON)</Label>
<Input
id="h-labels"
value={labels}
onChange={(e) => setLabels(e.target.value)}
placeholder='["loki", "logging"]'
/>
</div>
<Button
type="submit"
className="w-full bg-emerald-600 hover:bg-emerald-700"
disabled={submitting}
>
{submitting ? '添加中...' : '添加主机'}
</Button>
</form>
</DialogContent>
</Dialog>
}
/>
{/* Hosts Grid */}
{loading ? (
<LoadingSpinner className="h-64" />
) : hosts.length === 0 ? (
<EmptyState
icon={Monitor}
title="暂无主机"
description="添加第一台 SSH 主机开始使用"
/>
) : (
<div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
{hosts.map((host) => (
<HostCard
key={host.id}
host={host}
validating={validating}
onViewInfo={viewHostInfo}
onOpenTerminal={openTerminal}
onValidate={handleValidate}
onDelete={handleDelete}
/>
))}
</div>
)}
{/* Host Detail Dialog */}
<Dialog open={detailOpen} onOpenChange={setDetailOpen}>
<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" />
{selectedHost?.name}
</DialogTitle>
</DialogHeader>
{hostInfo ? (
<HostDetail info={hostInfo} />
) : (
<LoadingSpinner className="h-32" />
)}
</DialogContent>
</Dialog>
{/* Terminal Dialog */}
<Dialog open={terminalOpen} onOpenChange={setTerminalOpen}>
<DialogContent className="max-w-4xl">
<DialogHeader>
<DialogTitle className="flex items-center gap-2">
<Terminal className="w-5 h-5 text-emerald-500" />
终端 - {selectedHost?.name}
</DialogTitle>
</DialogHeader>
<div className="space-y-4">
<div className="bg-slate-900 text-green-400 font-mono text-xs p-4 rounded-lg h-80 overflow-auto whitespace-pre-wrap">
{terminalOutput}
</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-emerald-600 hover:bg-emerald-700"
>
{executing ? '执行中...' : '执行'}
</Button>
</div>
</div>
</DialogContent>
</Dialog>
</div>
)
})
// 子组件:主机卡片
interface HostCardProps {
host: Host
validating: number | null
onViewInfo: (h: Host) => void
onOpenTerminal: (h: Host) => void
onValidate: (id: number) => void
onDelete: (id: number) => void
}
const HostCard = memo(function HostCard({
host,
validating,
onViewInfo,
onOpenTerminal,
onValidate,
onDelete,
}: HostCardProps) {
return (
<Card className="border-slate-200 dark:border-slate-800 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-slate-800 dark:text-white truncate">
{host.name}
</h3>
</div>
<StatusBadge status={host.status} />
</div>
<div className="space-y-1.5 text-xs text-slate-500 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-slate-100 dark:border-slate-800">
<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"
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"
className="text-red-500 hover:text-red-600 hover:bg-red-50"
onClick={() => onDelete(host.id)}
>
<Trash2 className="w-3 h-3" />
</Button>
</div>
</CardContent>
</Card>
)
})
// 子组件:信息行
const InfoRow = memo(function InfoRow({
label,
value,
}: {
label: string
value: string
}) {
return (
<div className="flex justify-between">
<span>{label}</span>
<span className="font-medium text-slate-700 dark:text-slate-300">{value}</span>
</div>
)
})
// 子组件:主机详情
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-slate-500">{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-slate-50 dark:bg-slate-800 rounded-lg">
<p className="text-xs text-slate-500">{label}</p>
<p className="text-sm font-medium truncate">{value}</p>
</div>
)
})
export default Hosts
-438
View File
@@ -1,438 +0,0 @@
import { memo, useCallback, useEffect, useState } from 'react'
import {
HardDrive,
Plus,
Trash2,
Star,
Cloud,
Database,
Package,
} 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,
DialogTrigger,
} from '@/components/ui/dialog'
import { Card, CardContent } from '@/components/ui/card'
import { storageApi } from '@/api'
import { LoadingSpinner } from '@/components/LoadingSpinner'
import { EmptyState } from '@/components/EmptyState'
import { PageHeader } from '@/components/PageHeader'
import { toast } from 'sonner'
import type { StorageConfig } from '@/types'
// 存储类型图标映射 - 常量提取
const STORAGE_TYPE_ICONS: Record<string, React.ReactNode> = {
s3: <Cloud className="w-5 h-5 text-orange-500" />,
oss: <Cloud className="w-5 h-5 text-red-500" />,
minio: <Database className="w-5 h-5 text-blue-500" />,
rustfs: <Package className="w-5 h-5 text-cyan-500" />,
}
// 存储类型颜色
const STORAGE_TYPE_COLORS: Record<string, string> = {
s3: 'bg-orange-100 text-orange-700',
oss: 'bg-red-100 text-red-700',
minio: 'bg-blue-100 text-blue-700',
rustfs: 'bg-cyan-100 text-cyan-700',
}
const STORAGE_TYPES = ['s3', 'oss', 'minio', 'rustfs'] as const
/**
* Storage 页面 - 优化版本
*
* 优化点:
* 1. React.memo 包裹组件
* 2. 所有操作函数使用 useCallback 缓存
* 3. alert() 替换为 sonner toast
* 4. 使用公共组件替代重复代码
* 5. 常量图标和颜色映射提取
*/
const Storage = memo(function Storage() {
const [storages, setStorages] = useState<StorageConfig[]>([])
const [loading, setLoading] = useState(true)
const [open, setOpen] = useState(false)
// Form state
const [name, setName] = useState('')
const [storageType, setStorageType] = useState<'s3' | 'oss' | 'minio' | 'rustfs'>('minio')
const [endpoint, setEndpoint] = useState('')
const [bucket, setBucket] = useState('')
const [region, setRegion] = useState('')
const [accessKey, setAccessKey] = useState('')
const [secretKey, setSecretKey] = useState('')
const [pathPrefix, setPathPrefix] = useState('loki')
const [insecure, setInsecure] = useState(false)
const [isDefault, setIsDefault] = useState(false)
const [submitting, setSubmitting] = useState(false)
const loadStorages = useCallback(async () => {
try {
const res = await storageApi.list(1, 100)
setStorages(res.list)
} catch (err) {
console.error('Failed to load storages:', err)
toast.error('加载存储配置失败')
} finally {
setLoading(false)
}
}, [])
useEffect(() => {
loadStorages()
}, [loadStorages])
const resetForm = useCallback(() => {
setName('')
setStorageType('minio')
setEndpoint('')
setBucket('')
setRegion('')
setAccessKey('')
setSecretKey('')
setPathPrefix('loki')
setInsecure(false)
setIsDefault(false)
}, [])
const handleSubmit = useCallback(
async (e: React.FormEvent) => {
e.preventDefault()
setSubmitting(true)
try {
await storageApi.create({
name,
storageType,
endpoint,
bucket,
region,
accessKey,
secretKey,
pathPrefix,
insecure,
isDefault,
})
setOpen(false)
resetForm()
loadStorages()
toast.success('存储配置添加成功')
} catch (err: unknown) {
const message = err instanceof Error ? err.message : '创建存储配置失败'
toast.error(message)
} finally {
setSubmitting(false)
}
},
[name, storageType, endpoint, bucket, region, accessKey, secretKey, pathPrefix, insecure, isDefault, resetForm, loadStorages]
)
const handleDelete = useCallback(
async (id: number) => {
if (!confirm('确定删除此存储配置?')) return
try {
await storageApi.remove(id)
loadStorages()
toast.success('存储配置已删除')
} catch (err) {
console.error('Failed to delete storage:', err)
toast.error('删除存储配置失败')
}
},
[loadStorages]
)
const handleSetDefault = useCallback(
async (id: number) => {
try {
await storageApi.update(id, { isDefault: true })
loadStorages()
toast.success('已设为默认存储')
} catch (err) {
console.error('Failed to set default storage:', err)
toast.error('设置默认存储失败')
}
},
[loadStorages]
)
return (
<div className="space-y-6">
<PageHeader
title="存储配置"
description="为 Loki 配置对象存储后端"
action={
<Dialog open={open} onOpenChange={setOpen}>
<DialogTrigger asChild>
<Button className="bg-emerald-600 hover:bg-emerald-700">
<Plus className="w-4 h-4 mr-1" />
添加存储
</Button>
</DialogTrigger>
<DialogContent className="max-w-2xl max-h-[90vh] overflow-y-auto">
<DialogHeader>
<DialogTitle>添加存储配置</DialogTitle>
</DialogHeader>
<form onSubmit={handleSubmit} className="space-y-4">
<div className="space-y-2">
<Label htmlFor="s-name">名称 *</Label>
<Input
id="s-name"
value={name}
onChange={(e) => setName(e.target.value)}
placeholder="production-minio"
required
/>
</div>
<div className="space-y-2">
<Label>存储类型</Label>
<div className="grid grid-cols-4 gap-2">
{STORAGE_TYPES.map((type) => (
<button
key={type}
type="button"
onClick={() => setStorageType(type)}
className={`flex flex-col items-center gap-1 p-3 rounded-lg border transition-all ${
storageType === type
? 'border-emerald-500 bg-emerald-50 text-emerald-700'
: 'border-slate-200 hover:border-slate-300 text-slate-600'
}`}
>
{STORAGE_TYPE_ICONS[type]}
<span className="text-xs font-medium uppercase">{type}</span>
</button>
))}
</div>
</div>
<div className="space-y-2">
<Label htmlFor="s-endpoint">访问地址</Label>
<Input
id="s-endpoint"
value={endpoint}
onChange={(e) => setEndpoint(e.target.value)}
placeholder={
storageType === 's3'
? 's3.amazonaws.com'
: storageType === 'minio'
? 'http://minio.example.com:9000'
: ''
}
/>
</div>
<div className="grid grid-cols-2 gap-4">
<div className="space-y-2">
<Label htmlFor="s-bucket">Bucket *</Label>
<Input
id="s-bucket"
value={bucket}
onChange={(e) => setBucket(e.target.value)}
placeholder="loki-logs"
required
/>
</div>
<div className="space-y-2">
<Label htmlFor="s-region">区域</Label>
<Input
id="s-region"
value={region}
onChange={(e) => setRegion(e.target.value)}
placeholder="us-east-1"
/>
</div>
</div>
<div className="grid grid-cols-2 gap-4">
<div className="space-y-2">
<Label htmlFor="s-access">Access Key</Label>
<Input
id="s-access"
value={accessKey}
onChange={(e) => setAccessKey(e.target.value)}
placeholder="minioadmin"
/>
</div>
<div className="space-y-2">
<Label htmlFor="s-secret">Secret Key</Label>
<Input
id="s-secret"
type="password"
value={secretKey}
onChange={(e) => setSecretKey(e.target.value)}
placeholder="minioadmin"
/>
</div>
</div>
<div className="space-y-2">
<Label htmlFor="s-prefix">路径前缀</Label>
<Input
id="s-prefix"
value={pathPrefix}
onChange={(e) => setPathPrefix(e.target.value)}
placeholder="loki"
/>
</div>
<div className="flex gap-6">
<div className="flex items-center gap-2">
<Switch
id="s-insecure"
checked={insecure}
onCheckedChange={setInsecure}
/>
<Label htmlFor="s-insecure">不加密 (HTTP)</Label>
</div>
<div className="flex items-center gap-2">
<Switch
id="s-default"
checked={isDefault}
onCheckedChange={setIsDefault}
/>
<Label htmlFor="s-default">设为默认</Label>
</div>
</div>
<Button
type="submit"
className="w-full bg-emerald-600 hover:bg-emerald-700"
disabled={submitting}
>
{submitting ? '添加中...' : '添加存储'}
</Button>
</form>
</DialogContent>
</Dialog>
}
/>
{/* Storage Grid */}
{loading ? (
<LoadingSpinner className="h-64" />
) : storages.length === 0 ? (
<EmptyState
icon={HardDrive}
title="暂无存储配置"
description="添加第一个 Loki 存储后端"
/>
) : (
<div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
{storages.map((storage) => (
<StorageCard
key={storage.id}
storage={storage}
onSetDefault={handleSetDefault}
onDelete={handleDelete}
/>
))}
</div>
)}
</div>
)
})
// 子组件:存储卡片
interface StorageCardProps {
storage: StorageConfig
onSetDefault: (id: number) => void
onDelete: (id: number) => void
}
const StorageCard = memo(function StorageCard({
storage,
onSetDefault,
onDelete,
}: StorageCardProps) {
return (
<Card
className={`border-slate-200 dark:border-slate-800 hover:shadow-md transition-shadow ${
storage.isDefault ? 'ring-1 ring-emerald-500' : ''
}`}
>
<CardContent className="p-5">
<div className="flex items-start justify-between mb-3">
<div className="flex items-center gap-2 min-w-0">
{STORAGE_TYPE_ICONS[storage.storageType] || (
<HardDrive className="w-5 h-5 text-slate-400" />
)}
<h3 className="font-semibold text-slate-800 dark:text-white 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-emerald-100 text-emerald-700 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-slate-100 text-slate-600'
}`}
>
{storage.storageType}
</span>
</div>
</div>
<div className="space-y-1.5 text-xs text-slate-500 mb-4">
<InfoRow label="访问地址" value={storage.endpoint || '默认'} />
<InfoRow label="Bucket" value={storage.bucket} />
<InfoRow label="区域" value={storage.region || '无'} />
<InfoRow label="路径前缀" value={storage.pathPrefix || '无'} />
<InfoRow label="不加密" value={storage.insecure ? '是' : '否'} />
</div>
<div className="flex gap-2 pt-3 border-t border-slate-100 dark:border-slate-800">
<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"
className="text-red-500 hover:text-red-600 hover:bg-red-50"
onClick={() => onDelete(storage.id)}
>
<Trash2 className="w-3 h-3" />
</Button>
</div>
</CardContent>
</Card>
)
})
// 子组件:信息行
const InfoRow = memo(function InfoRow({
label,
value,
}: {
label: string
value: string
}) {
return (
<div className="flex justify-between">
<span>{label}</span>
<span className="font-medium text-slate-700 dark:text-slate-300 truncate max-w-[150px]">
{value}
</span>
</div>
)
})
export default Storage
@@ -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
@@ -0,0 +1,144 @@
import { memo } from 'react'
import {
RadioTower,
Trash2,
Upload,
Download,
Server,
Monitor,
Cloud,
type LucideIcon,
} 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 { Collector } from '@/types'
// 采集器类型元数据(图标 + 类型徽章配色)
const COLLECTOR_TYPE_META: Record<string, { label: string; icon: LucideIcon; color: string }> = {
'host-promtail': { label: '主机 Promtail', icon: Monitor, color: 'bg-purple-100 text-purple-700' },
'k8s-daemonset': { label: 'K8s DaemonSet', icon: Cloud, color: 'bg-info/10 text-info' },
'k8s-fluentbit-sidecar': { label: 'K8s Sidecar', icon: Server, color: 'bg-cyan-100 text-cyan-700' },
}
const FALLBACK_META = { label: '', icon: RadioTower, color: 'bg-muted text-slate-600' }
interface CollectorCardProps {
collector: Collector
/** 部署/卸载进行中的采集器 ID(按钮 loading 态) */
operating: number | null
onInstall: (id: number) => void
onUninstall: (id: number) => void
onDelete: (c: Collector) => void
}
/** 采集器卡片 — 列表项展示与操作入口(部署/卸载/删除) */
export const CollectorCard = memo(function CollectorCard({
collector,
operating,
onInstall,
onUninstall,
onDelete,
}: CollectorCardProps) {
const meta = COLLECTOR_TYPE_META[collector.type] ?? {
...FALLBACK_META,
label: collector.type,
}
const Icon = meta.icon
const isBusy = operating === collector.id
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">
<Icon className="w-5 h-5 text-primary flex-shrink-0" />
<div className="min-w-0">
<h3 className="font-semibold text-foreground truncate">
{collector.name}
</h3>
<p className="text-xs text-muted-foreground">
关联 Loki:{collector.lokiDeployment?.name || '未知'}
</p>
</div>
</div>
<StatusBadge status={collector.status} />
</div>
<div className="space-y-1.5 text-xs text-muted-foreground mb-3">
<div className="flex justify-between">
<span>类型</span>
<span className={`px-2 py-0.5 rounded-full text-xs font-medium ${meta.color}`}>
{meta.label}
</span>
</div>
{collector.host && (
<InfoRow
label="主机"
value={`${collector.host.name}(${collector.host.hostIP})`}
valueClass="truncate max-w-[200px]"
/>
)}
{collector.cluster && (
<InfoRow
label="集群"
value={collector.cluster.name}
valueClass="truncate max-w-[200px]"
/>
)}
{collector.targetDeployment && (
<InfoRow
label="目标 Deployment"
value={collector.targetDeployment}
valueClass="truncate max-w-[200px]"
/>
)}
{collector.namespace && (
<InfoRow label="命名空间" value={collector.namespace} valueClass="truncate max-w-[200px]" />
)}
{collector.logPath && (
<InfoRow label="日志路径" value={collector.logPath} valueClass="truncate max-w-[200px]" />
)}
{collector.statusMessage && (
<div className="p-2 bg-muted rounded text-xs mt-1">
{collector.statusMessage}
</div>
)}
</div>
<div className="flex gap-2 pt-3 border-t border-border">
<Button
variant="outline"
size="sm"
className="flex-1 text-xs"
onClick={() => onInstall(collector.id)}
disabled={isBusy}
>
<Upload className="w-3 h-3 mr-1" />
{isBusy ? '处理中...' : '部署'}
</Button>
<Button
variant="outline"
size="sm"
className="flex-1 text-xs"
onClick={() => onUninstall(collector.id)}
disabled={isBusy}
>
<Download className="w-3 h-3 mr-1" />
卸载
</Button>
<Button
variant="outline"
size="sm"
aria-label={`删除采集器 ${collector.name}`}
className="text-destructive hover:text-destructive hover:bg-destructive/10"
onClick={() => onDelete(collector)}
>
<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 { Button } from '@/components/ui/button'
import { Input } from '@/components/ui/input'
import {
Dialog,
DialogContent,
DialogHeader,
DialogTitle,
} from '@/components/ui/dialog'
import {
Select,
SelectContent,
SelectItem,
SelectTrigger,
SelectValue,
} from '@/components/ui/select'
import {
Form,
FormControl,
FormField,
FormItem,
FormLabel,
FormMessage,
} from '@/components/ui/form'
import { collectorApi } from '@/api'
import { statusLabel } from '@/lib/utils'
import { toast } from 'sonner'
import type { Cluster, Host, LokiDeployment } from '@/types'
type CollectorType = 'host-promtail' | 'k8s-daemonset' | 'k8s-fluentbit-sidecar'
const COLLECTOR_TYPES: Array<{ value: CollectorType; label: string }> = [
{ value: 'host-promtail', label: '主机 Promtail(SSH)' },
{ value: 'k8s-daemonset', label: 'K8s Promtail DaemonSet' },
{ value: 'k8s-fluentbit-sidecar', label: 'K8s Fluent Bit Sidecar' },
]
// 表单 schema:zod 为唯一校验源,消息中文且具体
const collectorFormSchema = z
.object({
name: z.string().min(1, '请输入采集器名称'),
type: z.enum(['host-promtail', 'k8s-daemonset', 'k8s-fluentbit-sidecar']),
lokiDeploymentID: z.string().min(1, '请选择关联的 Loki 部署'),
hostID: z.string(),
clusterID: z.string(),
targetDeployment: z.string(),
namespace: z.string(),
logPath: z.string(),
/** 旧版表单即无录入入口,仅透传(默认空串) */
labels: z.string(),
})
.superRefine((data, ctx) => {
if (data.type === 'host-promtail' && !data.hostID) {
ctx.addIssue({ code: 'custom', path: ['hostID'], message: '请选择目标主机' })
}
if (data.type !== 'host-promtail' && !data.clusterID) {
ctx.addIssue({ code: 'custom', path: ['clusterID'], message: '请选择目标集群' })
}
if (
data.type === 'k8s-fluentbit-sidecar' &&
!data.targetDeployment.trim()
) {
ctx.addIssue({
code: 'custom',
path: ['targetDeployment'],
message: '请填写目标 Deployment 名称',
})
}
})
type CollectorFormValues = z.infer<typeof collectorFormSchema>
const DEFAULT_VALUES: CollectorFormValues = {
name: '',
type: 'host-promtail',
lokiDeploymentID: '',
hostID: '',
clusterID: '',
targetDeployment: '',
namespace: '',
logPath: '',
labels: '',
}
interface CollectorFormDialogProps {
open: boolean
onOpenChange: (open: boolean) => void
/** 创建成功回调(父级刷新列表并回到第 1 页) */
onCreated: () => void
deployments: LokiDeployment[]
clusters: Cluster[]
hosts: Host[]
}
/** 新建采集器弹窗 — react-hook-form + zod;类型切换条件显示主机/集群选择与字段 */
export const CollectorFormDialog = memo(function CollectorFormDialog({
open,
onOpenChange,
onCreated,
deployments,
clusters,
hosts,
}: CollectorFormDialogProps) {
const [submitting, setSubmitting] = useState(false)
const form = useForm<CollectorFormValues>({
resolver: zodResolver(collectorFormSchema),
defaultValues: DEFAULT_VALUES,
})
const collectorType = form.watch('type')
// 打开时重置(关闭重置时机明确)
useEffect(() => {
if (open) {
form.reset(DEFAULT_VALUES)
}
}, [open, form])
const onSubmit = form.handleSubmit(async (values) => {
setSubmitting(true)
try {
await collectorApi.create({
name: values.name,
type: values.type,
lokiDeploymentID: Number(values.lokiDeploymentID),
hostID:
values.type === 'host-promtail' && values.hostID
? Number(values.hostID)
: undefined,
clusterID:
values.type !== 'host-promtail' && values.clusterID
? Number(values.clusterID)
: undefined,
targetDeployment:
values.type === 'k8s-fluentbit-sidecar' ? values.targetDeployment : undefined,
namespace: values.type !== 'host-promtail' ? values.namespace : undefined,
logPath: values.logPath,
labels: values.labels,
})
onOpenChange(false)
onCreated()
} catch (err) {
toast.error(err instanceof Error ? err.message : '创建采集器失败')
} finally {
setSubmitting(false)
}
})
const isHostType = collectorType === 'host-promtail'
const isK8sType = collectorType !== 'host-promtail'
const isSidecarType = collectorType === 'k8s-fluentbit-sidecar'
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">
<div className="grid grid-cols-2 gap-4">
<FormField
control={form.control}
name="name"
render={({ field }) => (
<FormItem>
<FormLabel>名称 *</FormLabel>
<FormControl>
<Input placeholder="app-logs-collector" {...field} />
</FormControl>
<FormMessage />
</FormItem>
)}
/>
<FormField
control={form.control}
name="type"
render={({ field }) => (
<FormItem>
<FormLabel>采集器类型</FormLabel>
<FormControl>
<Select value={field.value} onValueChange={field.onChange}>
<SelectTrigger>
<SelectValue />
</SelectTrigger>
<SelectContent>
{COLLECTOR_TYPES.map((t) => (
<SelectItem key={t.value} value={t.value}>
{t.label}
</SelectItem>
))}
</SelectContent>
</Select>
</FormControl>
<FormMessage />
</FormItem>
)}
/>
</div>
<FormField
control={form.control}
name="lokiDeploymentID"
render={({ field }) => (
<FormItem>
<FormLabel>关联 Loki 部署 *</FormLabel>
<FormControl>
<Select value={field.value} onValueChange={field.onChange}>
<SelectTrigger>
<SelectValue placeholder="选择已部署的 Loki(推送目标)" />
</SelectTrigger>
<SelectContent>
{deployments.map((d) => (
<SelectItem key={d.id} value={String(d.id)}>
{d.name}({statusLabel(d.status)})
</SelectItem>
))}
</SelectContent>
</Select>
</FormControl>
<FormMessage />
</FormItem>
)}
/>
{isHostType && (
<FormField
control={form.control}
name="hostID"
render={({ field }) => (
<FormItem>
<FormLabel>目标主机 *</FormLabel>
<FormControl>
<Select value={field.value} onValueChange={field.onChange}>
<SelectTrigger>
<SelectValue placeholder="选择主机" />
</SelectTrigger>
<SelectContent>
{hosts.map((h) => (
<SelectItem key={h.id} value={String(h.id)}>
{h.name}({h.hostIP})
</SelectItem>
))}
</SelectContent>
</Select>
</FormControl>
<FormMessage />
</FormItem>
)}
/>
)}
{isK8sType && (
<>
<FormField
control={form.control}
name="clusterID"
render={({ field }) => (
<FormItem>
<FormLabel>目标集群 *</FormLabel>
<FormControl>
<Select value={field.value} onValueChange={field.onChange}>
<SelectTrigger>
<SelectValue placeholder="选择集群" />
</SelectTrigger>
<SelectContent>
{clusters.map((c) => (
<SelectItem key={c.id} value={String(c.id)}>
{c.name}({statusLabel(c.status)})
</SelectItem>
))}
</SelectContent>
</Select>
</FormControl>
<FormMessage />
</FormItem>
)}
/>
<div className="grid grid-cols-2 gap-4">
<FormField
control={form.control}
name="namespace"
render={({ field }) => (
<FormItem>
<FormLabel>命名空间</FormLabel>
<FormControl>
<Input
placeholder={collectorType === 'k8s-daemonset' ? 'logging' : 'default'}
{...field}
/>
</FormControl>
<FormMessage />
</FormItem>
)}
/>
{isSidecarType && (
<FormField
control={form.control}
name="targetDeployment"
render={({ field }) => (
<FormItem>
<FormLabel>目标 Deployment *</FormLabel>
<FormControl>
<Input placeholder="my-app" {...field} />
</FormControl>
<FormMessage />
</FormItem>
)}
/>
)}
</div>
</>
)}
<FormField
control={form.control}
name="logPath"
render={({ field }) => (
<FormItem>
<FormLabel>采集日志路径</FormLabel>
<FormControl>
<Input
placeholder={isHostType ? '/var/log/*.log' : '/var/log/app/*.log'}
{...field}
/>
</FormControl>
<FormMessage />
{isHostType && (
<p className="text-xs text-muted-foreground">
支持 glob 通配(如 /var/log/*.log /var/log/syslog);多个路径用逗号分隔
</p>
)}
</FormItem>
)}
/>
<FormField
control={form.control}
name="labels"
render={({ field }) => (
<FormItem>
<FormLabel>自定义标签(JSON,可选)</FormLabel>
<FormControl>
<Input placeholder='{"env": "prod", "team": "ops"}' {...field} />
</FormControl>
<FormMessage />
<p className="text-xs text-muted-foreground">
合法 JSON 时将附加到每条日志的标签,便于在 Loki/Grafana 中筛选;留空则不加
</p>
</FormItem>
)}
/>
<Button
type="submit"
className="w-full bg-primary hover:bg-primary/90"
disabled={submitting}
>
{submitting ? '创建中...' : '创建并部署'}
</Button>
</form>
</Form>
</DialogContent>
</Dialog>
)
})
+179
View File
@@ -0,0 +1,179 @@
import { memo, useCallback, useEffect, useRef, useState } from 'react'
import { RadioTower, Plus } from 'lucide-react'
import { Button } from '@/components/ui/button'
import { clusterApi, collectorApi, deploymentApi, hostApi } 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, Collector, Host, LokiDeployment } from '@/types'
import { CollectorCard } from './components/CollectorCard'
import { CollectorFormDialog } from './components/CollectorFormDialog'
/**
* 日志采集页 — 采集策略编排:列表走 useListQuery(取消+版本号),
* Loki 部署/集群/主机下拉数据为页面局部加载(与列表分页解耦)。
* 部署(install)/卸载(uninstall)/删除保留;成功操作静默(列表刷新即反馈)。
*/
const CollectorsPage = memo(function CollectorsPage() {
const query = useListQuery<Collector>((params, signal) =>
collectorApi.list(params, { signal })
)
// 表单下拉数据:一次性局部加载
const [deployments, setDeployments] = useState<LokiDeployment[]>([])
const [clusters, setClusters] = useState<Cluster[]>([])
const [hosts, setHosts] = useState<Host[]>([])
const [formOpen, setFormOpen] = useState(false)
const [deleteTarget, setDeleteTarget] = useState<Collector | null>(null)
const [deleting, setDeleting] = useState(false)
/** 部署/卸载指令进行中的采集器 ID(按钮 loading + 防重复点击) */
const [operating, setOperating] = useState<number | null>(null)
// 操作后延时刷新列表/清除按钮态的定时器(卸载清理)
const timeoutsRef = useRef<ReturnType<typeof setTimeout>[]>([])
useEffect(() => {
return () => {
timeoutsRef.current.forEach((id) => clearTimeout(id))
timeoutsRef.current = []
}
}, [])
const addTimeout = useCallback((cb: () => void, delay: number) => {
timeoutsRef.current.push(setTimeout(cb, delay))
}, [])
// 下拉数据加载(失败仅提示,不阻塞列表)
useEffect(() => {
let cancelled = false
Promise.all([
deploymentApi.list({ page: 1, pageSize: 100 }),
clusterApi.list({ page: 1, pageSize: 100 }),
hostApi.list({ page: 1, pageSize: 100 }),
])
.then(([deployRes, clusterRes, hostRes]) => {
if (cancelled) return
setDeployments(deployRes.list)
setClusters(clusterRes.list)
setHosts(hostRes.list)
})
.catch((err) => {
toast.error(err instanceof Error ? err.message : '加载 Loki 部署/集群/主机数据失败')
})
return () => {
cancelled = true
}
}, [])
const handleAction = useCallback(
async (id: number, action: 'install' | 'uninstall') => {
setOperating(id)
try {
await collectorApi[action](id)
addTimeout(query.refresh, 3000)
} catch (err) {
toast.error(
err instanceof Error ? err.message : action === 'install' ? '部署采集器失败' : '卸载采集器失败'
)
} finally {
addTimeout(() => setOperating(null), 3000)
}
},
[query, addTimeout]
)
const handleDelete = useCallback(async () => {
const id = deleteTarget?.id
if (!id) return
setDeleting(true)
try {
await collectorApi.remove(id)
setDeleteTarget(null)
query.refresh()
} catch (err) {
toast.error(err instanceof Error ? err.message : '删除采集器失败')
} finally {
setDeleting(false)
}
}, [deleteTarget, 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={RadioTower}
title='暂无采集策略'
description="新建一个日志采集器,关联已部署的 Loki"
/>
) : (
<>
<div className="grid grid-cols-1 lg:grid-cols-2 gap-4">
{query.list.map((collector) => (
<CollectorCard
key={collector.id}
collector={collector}
operating={operating}
onInstall={(id) => handleAction(id, 'install')}
onUninstall={(id) => handleAction(id, 'uninstall')}
onDelete={setDeleteTarget}
/>
))}
</div>
<PaginationBar
page={query.page}
pageSize={query.pageSize}
total={query.total}
onPageChange={query.setPage}
/>
</>
)}
<CollectorFormDialog
open={formOpen}
onOpenChange={setFormOpen}
onCreated={query.reload}
deployments={deployments}
clusters={clusters}
hosts={hosts}
/>
<ConfirmDialog
open={deleteTarget !== null}
onOpenChange={(open) => {
if (!open) setDeleteTarget(null)
}}
name={deleteTarget?.name}
description={
deleteTarget
? `确定要删除「${deleteTarget.name}」吗?删除时将自动卸载采集端,此操作不可恢复。`
: undefined
}
loading={deleting}
onConfirm={handleDelete}
/>
</PageContainer>
)
})
export default CollectorsPage
@@ -0,0 +1,74 @@
import { memo } from 'react'
import { useNavigate } from 'react-router'
import { Rocket } from 'lucide-react'
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card'
import { EmptyState } from '@/components/EmptyState'
import { StatusIcon } from '@/components/StatusBadge'
import { getStatusColorClass } from '@/components/status-config'
import { statusLabel } from '@/lib/utils'
import type { LokiDeployment } from '@/types'
/** 最近部署卡片 — 展示最近 5 条部署,点击跳转部署页 */
export const RecentDeploymentsCard = memo(function RecentDeploymentsCard({
deployments,
onViewAll,
}: {
deployments: LokiDeployment[]
onViewAll: () => void
}) {
const navigate = useNavigate()
return (
<Card className="border-border">
<CardHeader className="pb-3">
<div className="flex items-center justify-between">
<CardTitle className="text-base">最近部署</CardTitle>
<button
onClick={onViewAll}
className="text-xs text-primary hover:text-primary/80 font-medium"
>
查看全部
</button>
</div>
</CardHeader>
<CardContent>
<div className="space-y-3">
{deployments.length === 0 ? (
<EmptyState
icon={Rocket}
title="暂无部署"
description="创建你的第一个 Loki 部署"
/>
) : (
deployments.map((d) => (
<div
key={d.id}
className="flex items-center justify-between p-3 rounded-lg bg-muted/50 hover:bg-muted dark:hover:bg-slate-800 transition-colors cursor-pointer"
onClick={() => navigate('/deployments')}
>
<div className="flex items-center gap-3 min-w-0">
<StatusIcon status={d.status} size="sm" />
<div className="min-w-0">
<p className="text-sm font-medium text-foreground truncate">
{d.name}
</p>
<p className="text-xs text-muted-foreground">
{d.mode} &middot; {d.namespace || 'loki'}
</p>
</div>
</div>
<span
className={`px-2 py-0.5 rounded-full text-xs font-medium flex-shrink-0 ${getStatusColorClass(
d.status
)}`}
>
{statusLabel(d.status)}
</span>
</div>
))
)}
</div>
</CardContent>
</Card>
)
})
@@ -0,0 +1,85 @@
import { memo } from 'react'
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card'
import { getStatusColorClass } from '@/components/status-config'
import { statusLabel } from '@/lib/utils'
// 用具体结构类型而非泛型:memo 包裹泛型组件会导致 TS 无法从 props 推断 T
interface ResourceItem {
id: number
name: string
status: string
hostIP?: string
}
interface ResourceListCardProps {
title: string
icon: React.ReactNode
items: ResourceItem[]
onManage: () => void
getItemIcon: (item: ResourceItem) => React.ReactNode
getItemLabel: (item: ResourceItem) => string
getItemStatus: (item: ResourceItem) => string
getItemExtra?: (item: ResourceItem) => string | undefined
}
/** 资源列表卡片 — 集群/主机快捷列表(仪表盘) */
export const ResourceListCard = memo(function ResourceListCard({
title,
icon,
items,
onManage,
getItemIcon,
getItemLabel,
getItemStatus,
getItemExtra,
}: ResourceListCardProps) {
return (
<Card className="border-border">
<CardHeader className="pb-3">
<div className="flex items-center justify-between">
<CardTitle className="text-base flex items-center gap-2">
{icon}
{title}
</CardTitle>
<button
onClick={onManage}
className="text-xs text-primary hover:text-primary/80 font-medium"
>
管理
</button>
</div>
</CardHeader>
<CardContent>
<div className="space-y-2">
{items.length === 0 ? (
<p className="text-sm text-muted-foreground text-center py-4">暂无{title}</p>
) : (
items.map((item) => (
<div
key={item.id}
className="flex items-center justify-between p-2 rounded-md hover:bg-muted dark:hover:bg-slate-800 transition-colors"
>
<div className="flex items-center gap-2 min-w-0">
{getItemIcon(item)}
<span className="text-sm truncate">{getItemLabel(item)}</span>
{getItemExtra?.(item) && (
<span className="text-xs text-muted-foreground flex-shrink-0">
{getItemExtra(item)}
</span>
)}
</div>
<span
className={`px-2 py-0.5 rounded-full text-xs flex-shrink-0 ${getStatusColorClass(
getItemStatus(item)
)}`}
>
{statusLabel(getItemStatus(item))}
</span>
</div>
))
)}
</div>
</CardContent>
</Card>
)
})
@@ -0,0 +1,52 @@
import { memo } from 'react'
import type { LucideIcon } from 'lucide-react'
import { Card, CardContent } from '@/components/ui/card'
interface StatCardProps {
label: string
value: string | number
icon: LucideIcon
iconColor: string
iconBg: string
sub?: {
icon: LucideIcon
color: string
textColor: string
text: string
}
}
/** 指标卡 — 数字 + 图标 + 副指标(仪表盘通用件) */
export const StatCard = memo(function StatCard({
label,
value,
icon: Icon,
iconColor,
iconBg,
sub,
}: StatCardProps) {
const SubIcon = sub?.icon
return (
<Card className="border-border">
<CardContent className="p-6">
<div className="flex items-center justify-between">
<div>
<p className="text-sm text-muted-foreground">{label}</p>
<p className="text-3xl font-bold text-foreground mt-1 tabular-nums">
{value}
</p>
</div>
<div className={`w-12 h-12 rounded-xl ${iconBg} flex items-center justify-center`}>
<Icon className={`w-6 h-6 ${iconColor}`} />
</div>
</div>
{sub && SubIcon && (
<div className="flex items-center gap-2 mt-4">
<SubIcon className={`w-4 h-4 ${sub.color}`} />
<span className={`text-xs ${sub.textColor}`}>{sub.text}</span>
</div>
)}
</CardContent>
</Card>
)
})
@@ -0,0 +1,82 @@
import { useCallback, useEffect, useRef, useState } from 'react'
import { clusterApi, deploymentApi, hostApi } from '@/api'
import type { Cluster, DashboardStats, Host, LokiDeployment } from '@/types'
export interface DashboardData {
stats: DashboardStats
deployments: LokiDeployment[]
clusters: Cluster[]
hosts: Host[]
}
const REFRESH_INTERVAL = 10000 // 10 秒自动刷新
/**
* 仪表盘数据 hook — 轮询 + AbortController/版本号双重防护。
* - 页面隐藏(document.hidden)时暂停轮询,重新可见立即刷新
* - 首次加载失败暴露 error(由页面渲染 ErrorState,不再吞错)
*/
export function useDashboardStats(intervalMs: number = REFRESH_INTERVAL) {
const [data, setData] = useState<DashboardData | null>(null)
const [loading, setLoading] = useState(true)
const [error, setError] = useState<string | null>(null)
const abortRef = useRef<AbortController | null>(null)
const versionRef = useRef(0)
const load = useCallback(async () => {
abortRef.current?.abort()
const controller = new AbortController()
abortRef.current = controller
const version = ++versionRef.current
try {
const [stats, deployRes, clusterRes, hostRes] = await Promise.all([
deploymentApi.stats(),
deploymentApi.list({ page: 1, pageSize: 5 }, { signal: controller.signal }),
clusterApi.list({ page: 1, pageSize: 5 }, { signal: controller.signal }),
hostApi.list({ page: 1, pageSize: 5 }, { signal: controller.signal }),
])
if (version !== versionRef.current) return
setData({
stats,
deployments: deployRes.list,
clusters: clusterRes.list,
hosts: hostRes.list,
})
setError(null)
} catch (err) {
if (version !== versionRef.current) return
setError(err instanceof Error ? err.message : '加载仪表盘数据失败')
} finally {
if (version === versionRef.current) {
setLoading(false)
}
}
}, [])
useEffect(() => {
void load()
const intervalId = setInterval(() => {
if (!document.hidden) void load()
}, intervalMs)
// 重新可见时立即刷新一次
const onVisibilityChange = () => {
if (!document.hidden) void load()
}
document.addEventListener('visibilitychange', onVisibilityChange)
return () => {
clearInterval(intervalId)
document.removeEventListener('visibilitychange', onVisibilityChange)
// 写入而非读取:递增使在途响应按版本号判过期(exhaustive-deps 误报)
// eslint-disable-next-line react-hooks/exhaustive-deps
versionRef.current++
abortRef.current?.abort()
}
}, [load, intervalMs])
return { data, loading, error, refresh: load }
}
+183
View File
@@ -0,0 +1,183 @@
import { memo, useCallback, useMemo } from 'react'
import { useNavigate } from 'react-router'
import { Server, Monitor, Activity, TrendingUp, CheckCircle, Rocket, Wand2 } from 'lucide-react'
import { Link } from 'react-router'
import { Card, CardContent } from '@/components/ui/card'
import { Button } from '@/components/ui/button'
import { PageContainer } from '@/components/PageContainer'
import { LoadingSpinner } from '@/components/LoadingSpinner'
import { ErrorState } from '@/components/ErrorState'
import { useDashboardStats } from './hooks/useDashboardStats'
import { StatCard } from './components/StatCard'
import { RecentDeploymentsCard } from './components/RecentDeploymentsCard'
import { ResourceListCard } from './components/ResourceListCard'
import type { DashboardStats } from '@/types'
const STATUS_ITEMS = [
{ key: 'running', label: '运行中', colorClass: 'text-primary' },
{ key: 'failed', label: '失败', colorClass: 'text-destructive' },
{ key: 'pending', label: '等待中', colorClass: 'text-warning' },
] as const
/**
* 仪表盘 — 指标卡 + 最近部署 + 资源快捷列表。
* 数据由 useDashboardStats 轮询(页面隐藏暂停);首次失败渲染错误态而非空数据。
*/
const DashboardPage = memo(function DashboardPage() {
const { data, loading, error, refresh } = useDashboardStats()
const navigate = useNavigate()
const navigateTo = useCallback(
(path: string) => () => navigate(path),
[navigate]
)
const stats = data?.stats ?? null
const statCards = useMemo(() => {
if (!stats) return null
const cards: Array<React.ReactNode> = [
<StatCard
key="deployments"
label="部署总数"
value={stats.totalDeployments}
icon={Rocket}
iconColor="text-primary"
iconBg="bg-success/10"
sub={{
icon: TrendingUp,
color: 'text-primary',
textColor: 'text-primary',
text: `${stats.running} 个运行中`,
}}
/>,
<StatCard
key="clusters"
label="集群"
value={stats.clusterCount}
icon={Server}
iconColor="text-info"
iconBg="bg-info/10"
sub={{
icon: CheckCircle,
color: 'text-primary',
textColor: 'text-muted-foreground',
text: '已接入',
}}
/>,
<StatCard
key="hosts"
label="主机"
value={stats.hostCount}
icon={Monitor}
iconColor="text-purple-600"
iconBg="bg-purple-100 dark:bg-purple-900/30"
sub={{
icon: CheckCircle,
color: 'text-primary',
textColor: 'text-muted-foreground',
text: 'SSH 就绪',
}}
/>,
]
return cards
}, [stats])
if (loading) {
return <LoadingSpinner className="h-64" />
}
if (error && !data) {
return <ErrorState message={error} onRetry={refresh} />
}
return (
<PageContainer>
{/* 快速开始引导:尚无任何部署时置顶(状态推导引导,opsx-sec 范式) */}
{(data?.stats.totalDeployments ?? 0) === 0 && (
<Card className="border-primary/30 bg-primary/5">
<CardContent className="p-5 flex items-center justify-between flex-wrap gap-3">
<div className="flex items-center gap-3">
<div className="w-10 h-10 rounded-xl bg-primary/10 flex items-center justify-center">
<Wand2 className="w-5 h-5 text-primary" />
</div>
<div>
<p className="font-medium">三步开始收集日志</p>
<p className="text-xs text-muted-foreground mt-0.5">
环境与目标 → 存储 → 部署 Loki 与 Grafana,最后添加采集策略
</p>
</div>
</div>
<Button asChild className="bg-primary hover:bg-primary/90">
<Link to="/wizard">
进入部署向导
<Wand2 className="w-4 h-4 ml-1" />
</Link>
</Button>
</CardContent>
</Card>
)}
{/* Stats Cards */}
<div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-4">
{statCards}
{/* 状态概览卡 */}
<Card className="border-border">
<CardContent className="p-6">
<div className="flex items-center justify-between">
<div>
<p className="text-sm text-muted-foreground">状态</p>
<div className="flex gap-3 mt-1">
{STATUS_ITEMS.map((item) => (
<div key={item.key} className="text-center">
<p className={`text-lg font-bold tabular-nums ${item.colorClass}`}>
{(stats?.[item.key as keyof DashboardStats] as number) || 0}
</p>
<p className="text-xs text-muted-foreground">{item.label}</p>
</div>
))}
</div>
</div>
<div className="w-12 h-12 rounded-xl bg-warning/10 flex items-center justify-center">
<Activity className="w-6 h-6 text-warning" />
</div>
</div>
</CardContent>
</Card>
</div>
{/* Recent Deployments & Quick Resources */}
<div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
<RecentDeploymentsCard
deployments={data?.deployments ?? []}
onViewAll={navigateTo('/deployments')}
/>
<div className="space-y-4">
<ResourceListCard
title="集群"
icon={<Server className="w-4 h-4 text-info" />}
items={(data?.clusters ?? []).slice(0, 3)}
onManage={navigateTo('/clusters')}
getItemIcon={() => <Server className="w-4 h-4 text-info" />}
getItemLabel={(c) => c.name}
getItemStatus={(c) => c.status}
/>
<ResourceListCard
title="主机"
icon={<Monitor className="w-4 h-4 text-purple-500" />}
items={(data?.hosts ?? []).slice(0, 3)}
onManage={navigateTo('/hosts')}
getItemIcon={() => <Monitor className="w-4 h-4 text-purple-500" />}
getItemLabel={(h) => h.name}
getItemStatus={(h) => h.status}
getItemExtra={(h) => h.hostIP}
/>
</div>
</div>
</PageContainer>
)
})
export default DashboardPage
@@ -0,0 +1,179 @@
import { memo, useEffect, useState } from 'react'
import { Play, Square, RotateCw, Trash2, Terminal, ExternalLink } from 'lucide-react'
import { Button } from '@/components/ui/button'
import { Card, CardContent } from '@/components/ui/card'
import { StatusBadge, StatusIcon } from '@/components/StatusBadge'
import { InfoRow } from '@/components/InfoRow'
import { deploymentApi } from '@/api'
import type { LokiDeployment } from '@/types'
/** 部署目标展示:优先集群,其次主机 */
const getTargetLabel = (d: LokiDeployment) => {
if (d.cluster) return `集群:${d.cluster.name}`
if (d.host) return `主机:${d.host.name}`
return '未知'
}
interface DeploymentCardProps {
deployment: LokiDeployment
/** 部署/重启进行中的部署 ID(按钮 loading 态) */
operating: number | null
onDeploy: (id: number) => void
onStop: (id: number) => void
onRestart: (id: number) => void
onDelete: (d: LokiDeployment) => void
onViewLogs: (d: LokiDeployment) => void
}
/** 部署卡片 — 列表项展示与操作入口(部署/停止/重启/日志/访问/删除) */
export const DeploymentCard = memo(function DeploymentCard({
deployment: d,
operating,
onDeploy,
onStop,
onRestart,
onDelete,
onViewLogs,
}: DeploymentCardProps) {
// Loki 就绪探测(运行中时经数据源代理 /ready)
const [ready, setReady] = useState<boolean | null>(null)
useEffect(() => {
if (d.status !== 'running') return
let cancelled = false
deploymentApi
.ready(d.id)
.then((r) => {
if (!cancelled) setReady(r.ready)
})
.catch(() => {
if (!cancelled) setReady(false)
})
return () => {
cancelled = true
}
}, [d.id, d.status])
const isDeploying = d.status === 'deploying'
const isBusy = operating === d.id
const canDeploy = d.status === 'pending' || d.status === 'failed' || d.status === 'stopped'
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">
<StatusIcon status={d.status} size="md" />
<div className="min-w-0">
<h3 className="font-semibold text-foreground truncate">
{d.name}
</h3>
<p className="text-xs text-muted-foreground">{d.uuid}</p>
</div>
</div>
<StatusBadge status={d.status} />
{d.status === 'running' && ready !== null && (
<span
className={`w-2 h-2 rounded-full ${ready ? 'bg-success' : 'bg-destructive'}`}
title={ready ? 'Loki 就绪' : 'Loki 未就绪'}
/>
)}
</div>
<p className="text-sm text-muted-foreground mb-3">{d.description || '无描述'}</p>
<div className="space-y-1.5 text-xs text-muted-foreground mb-4">
<InfoRow label="方式" value={d.mode} />
<InfoRow label="版本" value={d.version} />
<InfoRow label="目标" value={getTargetLabel(d)} />
<InfoRow label="命名空间" value={d.namespace || 'loki'} />
<InfoRow label="副本数" value={String(d.replicas)} />
<InfoRow label="存储" value={d.storageConfig?.name || '本地'} />
{d.endpoint && (
<InfoRow label="访问地址" value={d.endpoint} valueClass="text-primary truncate max-w-[200px]" />
)}
{d.grafanaEnabled && d.grafanaEndpoint && (
<div className="flex justify-between items-center gap-2">
<span>Grafana</span>
<a
href={d.grafanaEndpoint}
target="_blank"
rel="noopener noreferrer"
className="font-medium text-primary hover:underline truncate max-w-[200px]"
title={`${d.grafanaEndpoint}(admin/admin)`}
>
{d.grafanaEndpoint.replace(/^https?:\/\//, '')}
</a>
</div>
)}
{d.statusMessage && (
<div className="p-2 bg-muted rounded text-xs">
{d.statusMessage}
</div>
)}
</div>
<div className="flex gap-1 pt-3 border-t border-border">
{canDeploy ? (
<Button
variant="outline"
size="sm"
className="flex-1 text-xs bg-success/10 text-primary hover:bg-success/20 border-success/30"
onClick={() => onDeploy(d.id)}
disabled={isBusy}
>
<Play className="w-3 h-3 mr-1" />
{isBusy ? '部署中...' : '部署'}
</Button>
) : isDeploying ? (
<Button variant="outline" size="sm" className="flex-1 text-xs" disabled>
<RotateCw className="w-3 h-3 mr-1 animate-spin" />
部署中...
</Button>
) : (
<>
<Button variant="outline" size="sm" className="text-xs" onClick={() => onStop(d.id)}>
<Square className="w-3 h-3 mr-1" />
停止
</Button>
<Button
variant="outline"
size="sm"
className="text-xs"
onClick={() => onRestart(d.id)}
disabled={isBusy}
>
<RotateCw className={`w-3 h-3 mr-1 ${isBusy ? 'animate-spin' : ''}`} />
重启
</Button>
</>
)}
<Button variant="outline" size="sm" className="text-xs" onClick={() => onViewLogs(d)}>
<Terminal className="w-3 h-3 mr-1" />
日志
</Button>
{d.endpoint && (
<Button
variant="outline"
size="sm"
className="text-xs text-primary hover:text-primary/80"
onClick={() => window.open(d.endpoint, '_blank', 'noopener,noreferrer')}
title="浏览器访问"
>
<ExternalLink className="w-3 h-3 mr-1" />
访问
</Button>
)}
<Button
variant="outline"
size="sm"
aria-label={`删除部署 ${d.name}`}
className="text-destructive hover:text-destructive hover:bg-destructive/10"
onClick={() => onDelete(d)}
>
<Trash2 className="w-3 h-3" />
</Button>
</div>
</CardContent>
</Card>
)
})
@@ -0,0 +1,442 @@
import { memo, useEffect, useState } from 'react'
import { useForm } from 'react-hook-form'
import { zodResolver } from '@hookform/resolvers/zod'
import { Button } from '@/components/ui/button'
import { Input } from '@/components/ui/input'
import { Switch } from '@/components/ui/switch'
import { Textarea } from '@/components/ui/textarea'
import {
Dialog,
DialogContent,
DialogHeader,
DialogTitle,
} from '@/components/ui/dialog'
import {
Select,
SelectContent,
SelectItem,
SelectTrigger,
SelectValue,
} from '@/components/ui/select'
import {
Form,
FormControl,
FormField,
FormItem,
FormLabel,
FormMessage,
} from '@/components/ui/form'
import { deploymentApi } from '@/api'
import { statusLabel } from '@/lib/utils'
import { toast } from 'sonner'
import type { Cluster, Host, StorageConfig } from '@/types'
import {
FALLBACK_VERSIONS,
isK8sMode,
deploymentFormSchema,
DEFAULT_VALUES,
type DeploymentFormValues,
} from '../form-schema'
interface DeploymentFormDialogProps {
open: boolean
onOpenChange: (open: boolean) => void
/** 创建成功回调(父级刷新列表并回到第 1 页) */
onCreated: () => void
clusters: Cluster[]
hosts: Host[]
storages: StorageConfig[]
}
/** 创建 Loki 部署弹窗 — react-hook-form + zod;部署方式切换条件显示集群/主机选择 */
export const DeploymentFormDialog = memo(function DeploymentFormDialog({
open,
onOpenChange,
onCreated,
clusters,
hosts,
storages,
}: DeploymentFormDialogProps) {
const [submitting, setSubmitting] = useState(false)
// 版本列表来自后端 LokiVersionList,失败回退兜底
const [versions, setVersions] = useState<string[]>(FALLBACK_VERSIONS)
useEffect(() => {
let cancelled = false
deploymentApi
.versions()
.then((res) => {
if (!cancelled && res.versions?.length) setVersions(res.versions)
})
.catch(() => {
// 静默:保留兜底列表
})
return () => {
cancelled = true
}
}, [])
const form = useForm<DeploymentFormValues>({
resolver: zodResolver(deploymentFormSchema),
defaultValues: DEFAULT_VALUES,
})
const mode = form.watch('mode')
const grafanaEnabled = form.watch('grafanaEnabled')
// 打开时重置(关闭重置时机明确)
useEffect(() => {
if (open) {
form.reset(DEFAULT_VALUES)
}
}, [open, form])
const onSubmit = form.handleSubmit(async (values) => {
setSubmitting(true)
try {
await deploymentApi.create({
name: values.name,
description: values.description,
version: values.version,
mode: values.mode,
clusterID: values.clusterID ? Number(values.clusterID) : undefined,
hostID: values.hostID ? Number(values.hostID) : undefined,
namespace: values.namespace,
storageConfigID: values.storageConfigID ? Number(values.storageConfigID) : 0,
authEnabled: values.authEnabled,
retentionDays: Number(values.retentionDays),
replicas: Number(values.replicas),
resourcesCPU: values.resourcesCPU,
resourcesMem: values.resourcesMem,
storageSize: values.storageSize,
grafanaEnabled: values.grafanaEnabled,
grafanaVersion: values.grafanaEnabled ? values.grafanaVersion || undefined : undefined,
})
onOpenChange(false)
onCreated()
} catch (err) {
toast.error(err instanceof Error ? err.message : '创建部署失败')
} finally {
setSubmitting(false)
}
})
const showK8s = isK8sMode(mode)
const showHost = mode === 'host-binary'
return (
<Dialog open={open} onOpenChange={onOpenChange}>
<DialogContent className="max-w-2xl max-h-[90vh] overflow-y-auto">
<DialogHeader>
<DialogTitle>创建 Loki 部署</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-loki" {...field} />
</FormControl>
<FormMessage />
</FormItem>
)}
/>
<FormField
control={form.control}
name="description"
render={({ field }) => (
<FormItem>
<FormLabel>描述</FormLabel>
<FormControl>
<Textarea placeholder="生产环境 Loki 日志服务" {...field} />
</FormControl>
<FormMessage />
</FormItem>
)}
/>
<div className="grid grid-cols-2 gap-4">
<FormField
control={form.control}
name="version"
render={({ field }) => (
<FormItem>
<FormLabel>版本</FormLabel>
<FormControl>
<Select value={field.value} onValueChange={field.onChange}>
<SelectTrigger>
<SelectValue />
</SelectTrigger>
<SelectContent>
{versions.map((v) => (
<SelectItem key={v} value={v}>
{v}
</SelectItem>
))}
</SelectContent>
</Select>
</FormControl>
<FormMessage />
</FormItem>
)}
/>
<FormField
control={form.control}
name="mode"
render={({ field }) => (
<FormItem>
<FormLabel>部署方式</FormLabel>
<FormControl>
<Select value={field.value} onValueChange={field.onChange}>
<SelectTrigger>
<SelectValue />
</SelectTrigger>
<SelectContent>
<SelectItem value="k8s-helm">K8s Helm 部署</SelectItem>
<SelectItem value="k8s-yaml">K8s YAML 部署</SelectItem>
<SelectItem value="host-binary">主机二进制部署</SelectItem>
</SelectContent>
</Select>
</FormControl>
<FormMessage />
</FormItem>
)}
/>
</div>
{showK8s && (
<>
<FormField
control={form.control}
name="clusterID"
render={({ field }) => (
<FormItem>
<FormLabel>目标集群 *</FormLabel>
<FormControl>
<Select value={field.value} onValueChange={field.onChange}>
<SelectTrigger>
<SelectValue placeholder="请选择集群" />
</SelectTrigger>
<SelectContent>
{clusters.map((c) => (
<SelectItem key={c.id} value={String(c.id)}>
{c.name}({statusLabel(c.status)})
</SelectItem>
))}
</SelectContent>
</Select>
</FormControl>
<FormMessage />
</FormItem>
)}
/>
<FormField
control={form.control}
name="namespace"
render={({ field }) => (
<FormItem>
<FormLabel>命名空间 *</FormLabel>
<FormControl>
<Input placeholder="loki" {...field} />
</FormControl>
<FormMessage />
</FormItem>
)}
/>
</>
)}
{showHost && (
<FormField
control={form.control}
name="hostID"
render={({ field }) => (
<FormItem>
<FormLabel>目标主机 *</FormLabel>
<FormControl>
<Select value={field.value} onValueChange={field.onChange}>
<SelectTrigger>
<SelectValue placeholder="请选择主机" />
</SelectTrigger>
<SelectContent>
{hosts.map((h) => (
<SelectItem key={h.id} value={String(h.id)}>
{h.name}({h.hostIP})
</SelectItem>
))}
</SelectContent>
</Select>
</FormControl>
<FormMessage />
</FormItem>
)}
/>
)}
<FormField
control={form.control}
name="storageConfigID"
render={({ field }) => (
<FormItem>
<FormLabel>存储配置</FormLabel>
<FormControl>
<Select value={field.value} onValueChange={field.onChange}>
<SelectTrigger>
<SelectValue placeholder="请选择存储(可选)" />
</SelectTrigger>
<SelectContent>
<SelectItem value="0">本地存储(默认)</SelectItem>
{storages.map((s) => (
<SelectItem key={s.id} value={String(s.id)}>
{s.name}({s.storageType})
</SelectItem>
))}
</SelectContent>
</Select>
</FormControl>
<FormMessage />
</FormItem>
)}
/>
<div className="grid grid-cols-3 gap-4">
<FormField
control={form.control}
name="replicas"
render={({ field }) => (
<FormItem>
<FormLabel>副本数</FormLabel>
<FormControl>
<Input type="number" min={1} max={10} {...field} />
</FormControl>
<FormMessage />
</FormItem>
)}
/>
<FormField
control={form.control}
name="retentionDays"
render={({ field }) => (
<FormItem>
<FormLabel>保留天数</FormLabel>
<FormControl>
<Input type="number" min={1} {...field} />
</FormControl>
<FormMessage />
</FormItem>
)}
/>
<FormField
control={form.control}
name="storageSize"
render={({ field }) => (
<FormItem>
<FormLabel>存储容量</FormLabel>
<FormControl>
<Input placeholder="10Gi" {...field} />
</FormControl>
<FormMessage />
</FormItem>
)}
/>
</div>
<div className="grid grid-cols-2 gap-4">
<FormField
control={form.control}
name="resourcesCPU"
render={({ field }) => (
<FormItem>
<FormLabel>CPU</FormLabel>
<FormControl>
<Input placeholder="500m" {...field} />
</FormControl>
<FormMessage />
</FormItem>
)}
/>
<FormField
control={form.control}
name="resourcesMem"
render={({ field }) => (
<FormItem>
<FormLabel>内存</FormLabel>
<FormControl>
<Input placeholder="512Mi" {...field} />
</FormControl>
<FormMessage />
</FormItem>
)}
/>
</div>
<FormField
control={form.control}
name="authEnabled"
render={({ field }) => (
<FormItem>
<FormControl>
<div className="flex items-center gap-2">
<Switch
checked={field.value}
onCheckedChange={field.onChange}
/>
<FormLabel>启用多租户鉴权</FormLabel>
</div>
</FormControl>
<FormMessage />
</FormItem>
)}
/>
<FormField
control={form.control}
name="grafanaEnabled"
render={({ field }) => (
<FormItem>
<FormControl>
<div className="flex items-center gap-2">
<Switch
checked={field.value}
onCheckedChange={field.onChange}
/>
<FormLabel>同时部署 Grafana(可选 — 平台已内置日志查询,通常无需 Grafana)</FormLabel>
</div>
</FormControl>
<FormMessage />
</FormItem>
)}
/>
{grafanaEnabled && (
<FormField
control={form.control}
name="grafanaVersion"
render={({ field }) => (
<FormItem>
<FormLabel>Grafana 版本</FormLabel>
<FormControl>
<Input placeholder="11.3.0" {...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,109 @@
import { memo, useCallback, useEffect, useRef, useState } from 'react'
import { Terminal } from 'lucide-react'
import {
Dialog,
DialogContent,
DialogHeader,
DialogTitle,
} from '@/components/ui/dialog'
import { deploymentApi } from '@/api'
import { LoadingSpinner } from '@/components/LoadingSpinner'
import { ErrorState } from '@/components/ErrorState'
import type { DeploymentLog, LokiDeployment } from '@/types'
interface LogViewerDialogProps {
deployment: LokiDeployment | null
onClose: () => void
}
/** 部署日志弹窗 — 自负责拉取日志(打开即加载,版本号丢弃过期响应,失败可重试) */
export const LogViewerDialog = memo(function LogViewerDialog({
deployment,
onClose,
}: LogViewerDialogProps) {
const [logs, setLogs] = useState<DeploymentLog[]>([])
const [loading, setLoading] = useState(false)
const [error, setError] = useState<string | null>(null)
// 版本号令牌:快速重开/切换部署时丢弃过期响应
const versionRef = useRef(0)
const loadLogs = useCallback(async (id: number) => {
const current = ++versionRef.current
setLoading(true)
setError(null)
try {
const res = await deploymentApi.logs(id, { page: 1, pageSize: 100 })
if (current !== versionRef.current) return
setLogs(res.list ?? [])
} catch (err) {
if (current !== versionRef.current) return
setError(err instanceof Error ? err.message : '加载部署日志失败')
} finally {
if (current === versionRef.current) {
setLoading(false)
}
}
}, [])
useEffect(() => {
if (!deployment) return
setLogs([])
setError(null)
void loadLogs(deployment.id)
}, [deployment, loadLogs])
return (
<Dialog open={deployment !== null} onOpenChange={(open) => !open && onClose()}>
<DialogContent className="max-w-4xl max-h-[80vh]">
<DialogHeader>
<DialogTitle className="flex items-center gap-2">
<Terminal className="w-5 h-5 text-primary" />
部署日志 - {deployment?.name}
</DialogTitle>
</DialogHeader>
{error ? (
<ErrorState
message={error}
onRetry={() => deployment && loadLogs(deployment.id)}
/>
) : loading ? (
<LoadingSpinner className="h-64" />
) : (
<LogView logs={logs} />
)}
</DialogContent>
</Dialog>
)
})
/** 终端风格日志列表 */
const LogView = memo(function LogView({ logs }: { logs: DeploymentLog[] }) {
return (
<div className="bg-card dark:bg-card text-green-400 font-mono text-xs p-4 rounded-lg h-96 overflow-auto">
{logs.length === 0 ? (
<p className="text-muted-foreground">暂无日志...</p>
) : (
logs.map((log) => (
<div
key={log.id}
className={`mb-1 ${
log.level === 'error'
? 'text-destructive'
: log.level === 'warn'
? 'text-warning'
: log.level === 'success'
? 'text-success'
: 'text-green-400'
}`}
>
<span className="text-muted-foreground">
[{new Date(log.createdAt).toLocaleTimeString()}]
</span>{' '}
<span className="font-bold uppercase">{log.level}</span> {log.message}
</div>
))
)}
</div>
)
})
@@ -0,0 +1,73 @@
import { z } from 'zod'
// 部署表单 schema 与常量 — zod 为唯一校验源,消息中文且具体
// (纯数据/纯逻辑抽离,见开发标准 07 章页面内聚 utils 范式)
// 版本下拉兜底值;实际列表运行时从 GET /deployments/versions 拉取
export const FALLBACK_VERSIONS = ['3.0.0', '2.9.8', '2.9.7', '2.9.6']
export type DeploymentMode = 'k8s-helm' | 'k8s-yaml' | 'host-binary'
export const isK8sMode = (mode: DeploymentMode) =>
mode === 'k8s-helm' || mode === 'k8s-yaml'
// 整数字段校验(输入框 type=number 产出字符串,提交前统一转换)
const isPositiveInt = (v: string, min: number, max?: number) => {
const n = Number(v)
return Number.isInteger(n) && n >= min && (max === undefined || n <= max)
}
export const deploymentFormSchema = z
.object({
name: z.string().min(1, '请输入部署名称'),
description: z.string(),
version: z.string().min(1, '请选择 Loki 版本'),
mode: z.enum(['k8s-helm', 'k8s-yaml', 'host-binary']),
clusterID: z.string(),
hostID: z.string(),
namespace: z.string(),
grafanaEnabled: z.boolean(),
grafanaVersion: z.string().optional(),
storageConfigID: z.string(),
authEnabled: z.boolean(),
retentionDays: z
.string()
.refine((v) => isPositiveInt(v, 1), '保留天数需为不小于 1 的整数'),
replicas: z
.string()
.refine((v) => isPositiveInt(v, 1, 10), '副本数需为 1-10 之间的整数'),
resourcesCPU: z.string().min(1, '请填写 CPU 配额(如 500m)'),
resourcesMem: z.string().min(1, '请填写内存配额(如 512Mi)'),
storageSize: z.string().min(1, '请填写存储容量(如 10Gi)'),
})
.superRefine((data, ctx) => {
if (isK8sMode(data.mode) && !data.clusterID) {
ctx.addIssue({ code: 'custom', path: ['clusterID'], message: '请选择目标集群' })
}
if (data.mode === 'host-binary' && !data.hostID) {
ctx.addIssue({ code: 'custom', path: ['hostID'], message: '请选择目标主机' })
}
if (isK8sMode(data.mode) && !data.namespace.trim()) {
ctx.addIssue({ code: 'custom', path: ['namespace'], message: '请填写命名空间' })
}
})
export type DeploymentFormValues = z.infer<typeof deploymentFormSchema>
export const DEFAULT_VALUES: DeploymentFormValues = {
name: '',
description: '',
version: '3.0.0',
mode: 'k8s-helm',
clusterID: '',
hostID: '',
namespace: 'log',
grafanaEnabled: false,
grafanaVersion: '11.3.0',
storageConfigID: '',
authEnabled: false,
retentionDays: '30',
replicas: '1',
resourcesCPU: '500m',
resourcesMem: '512Mi',
storageSize: '10Gi',
}
+208
View File
@@ -0,0 +1,208 @@
import { memo, useCallback, useEffect, useRef, useState } from 'react'
import { Rocket, Plus } from 'lucide-react'
import { Button } from '@/components/ui/button'
import { clusterApi, deploymentApi, hostApi, storageApi } 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, Host, LokiDeployment, StorageConfig } from '@/types'
import { DeploymentCard } from './components/DeploymentCard'
import { DeploymentFormDialog } from './components/DeploymentFormDialog'
import { LogViewerDialog } from './components/LogViewerDialog'
/**
* Loki 部署页 — 只做编排:部署列表走 useListQuery(取消+版本号),
* 集群/主机/存储下拉数据为页面局部加载(与列表分页解耦);
* 卡片/表单/日志查看均为域内子组件。成功操作静默(列表刷新即反馈)。
*/
const DeploymentsPage = memo(function DeploymentsPage() {
const query = useListQuery<LokiDeployment>((params, signal) =>
deploymentApi.list(params, { signal })
)
// 表单下拉数据:一次性局部加载,创建部署不依赖其刷新
const [clusters, setClusters] = useState<Cluster[]>([])
const [hosts, setHosts] = useState<Host[]>([])
const [storages, setStorages] = useState<StorageConfig[]>([])
const [formOpen, setFormOpen] = useState(false)
const [logsDeployment, setLogsDeployment] = useState<LokiDeployment | null>(null)
const [deleteTarget, setDeleteTarget] = useState<LokiDeployment | null>(null)
const [deleting, setDeleting] = useState(false)
/** 部署/重启进行中的部署 ID(按钮 loading + 防重复点击) */
const [operating, setOperating] = useState<number | null>(null)
// 操作后延时刷新列表/清除按钮态的定时器(卸载清理)
const timeoutsRef = useRef<ReturnType<typeof setTimeout>[]>([])
useEffect(() => {
return () => {
timeoutsRef.current.forEach((id) => clearTimeout(id))
timeoutsRef.current = []
}
}, [])
const addTimeout = useCallback((cb: () => void, delay: number) => {
timeoutsRef.current.push(setTimeout(cb, delay))
}, [])
// 下拉数据加载(失败仅提示,不阻塞列表)
useEffect(() => {
let cancelled = false
Promise.all([
clusterApi.list({ page: 1, pageSize: 100 }),
hostApi.list({ page: 1, pageSize: 100 }),
storageApi.list({ page: 1, pageSize: 100 }),
])
.then(([clusterRes, hostRes, storageRes]) => {
if (cancelled) return
setClusters(clusterRes.list)
setHosts(hostRes.list)
setStorages(storageRes.list)
})
.catch((err) => {
toast.error(err instanceof Error ? err.message : '加载集群/主机/存储数据失败')
})
return () => {
cancelled = true
}
}, [])
const handleDeploy = useCallback(
async (id: number) => {
setOperating(id)
try {
await deploymentApi.deploy(id)
addTimeout(query.refresh, 2000)
} catch (err) {
toast.error(err instanceof Error ? err.message : '部署失败')
} finally {
addTimeout(() => setOperating(null), 5000)
}
},
[query, addTimeout]
)
const handleStop = useCallback(
async (id: number) => {
try {
await deploymentApi.stop(id)
query.refresh()
} catch (err) {
toast.error(err instanceof Error ? err.message : '停止失败')
}
},
[query]
)
const handleRestart = useCallback(
async (id: number) => {
setOperating(id)
try {
await deploymentApi.restart(id)
addTimeout(query.refresh, 3000)
} catch (err) {
toast.error(err instanceof Error ? err.message : '重启失败')
} finally {
addTimeout(() => setOperating(null), 5000)
}
},
[query, addTimeout]
)
const handleDelete = useCallback(async () => {
const id = deleteTarget?.id
if (!id) return
setDeleting(true)
try {
await deploymentApi.remove(id)
setDeleteTarget(null)
query.refresh()
} catch (err) {
toast.error(err instanceof Error ? err.message : '删除部署失败')
} finally {
setDeleting(false)
}
}, [deleteTarget, query])
return (
<PageContainer
title="部署Loki"
description="部署与管理 Grafana 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={Rocket}
title="暂无部署"
description="创建你的第一个 Loki 部署"
/>
) : (
<>
<div className="grid grid-cols-1 lg:grid-cols-2 gap-4">
{query.list.map((deployment) => (
<DeploymentCard
key={deployment.id}
deployment={deployment}
operating={operating}
onDeploy={handleDeploy}
onStop={handleStop}
onRestart={handleRestart}
onDelete={setDeleteTarget}
onViewLogs={setLogsDeployment}
/>
))}
</div>
<PaginationBar
page={query.page}
pageSize={query.pageSize}
total={query.total}
onPageChange={query.setPage}
/>
</>
)}
<DeploymentFormDialog
open={formOpen}
onOpenChange={setFormOpen}
onCreated={query.reload}
clusters={clusters}
hosts={hosts}
storages={storages}
/>
<LogViewerDialog
deployment={logsDeployment}
onClose={() => setLogsDeployment(null)}
/>
<ConfirmDialog
open={deleteTarget !== null}
onOpenChange={(open) => {
if (!open) setDeleteTarget(null)
}}
name={deleteTarget?.name}
loading={deleting}
onConfirm={handleDelete}
/>
</PageContainer>
)
})
export default DeploymentsPage
@@ -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>
)
})
+171
View File
@@ -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
@@ -1,38 +1,34 @@
import { memo, useCallback, useEffect, useState } from 'react'
import { useNavigate } from 'react-router'
import { useLocation, useNavigate } from 'react-router'
import { Activity, Eye, EyeOff, Shield, ServerOff } from 'lucide-react'
import { Button } from '@/components/ui/button'
import { Input } from '@/components/ui/input'
import { Label } from '@/components/ui/label'
import { authApi } from '@/api'
import { toast } from 'sonner'
import { authApi, ApiError } from '@/api'
import { saveAuth, isLoggedIn, getUser } from '@/lib/auth-storage'
import { readRedirectParam } from '@/lib/redirect'
/**
* Login 页面 - 优化版本
*
* 优化点:
* 1. React.memo 包裹组件
* 2. 表单处理使用 useCallback 缓存
* 3. 错误处理使用 sonner toast 替代 alert
* 4. 清理 useEffect 中的未使用变量
* Login 页面
* - 登录接口 silent(错误密码 401 不触发全局跳转)
* - 登录成功按 redirect 参数回跳来源页(同源校验)
* - 后端探活走 api 层(authApi.health)
*/
const Login = memo(function Login() {
const [username, setUsername] = useState('admin')
const [password, setPassword] = useState('admin123')
const [username, setUsername] = useState('')
const [password, setPassword] = useState('')
const [showPassword, setShowPassword] = useState(false)
const [loading, setLoading] = useState(false)
const [error, setError] = useState('')
const [backendStatus, setBackendStatus] = useState<'checking' | 'online' | 'offline'>('checking')
const navigate = useNavigate()
const location = useLocation()
useEffect(() => {
// Check if already logged in
const token = localStorage.getItem('token')
if (token) {
navigate('/')
if (isLoggedIn()) {
navigate(getUser()?.role === 'admin' ? '/' : '/logs', { replace: true })
return
}
// Quick backend check
checkBackend()
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [navigate])
@@ -40,16 +36,10 @@ const Login = memo(function Login() {
// 后端状态检查 - useCallback缓存
const checkBackend = useCallback(async () => {
try {
const controller = new AbortController()
const timeoutId = setTimeout(() => controller.abort(), 3000)
// 用公开的健康检查端点探活;避免打 /auth/login(生产环境被 nginx 限流 5r/m,
// 反复刷新登录页会触发限流并锁死真正的登录请求)
const res = await fetch('/api/v1/health', {
method: 'GET',
signal: controller.signal,
})
clearTimeout(timeoutId)
setBackendStatus(res.ok ? 'online' : 'offline')
await authApi.health()
setBackendStatus('online')
} catch {
setBackendStatus('offline')
}
@@ -64,31 +54,27 @@ const Login = memo(function Login() {
try {
const result = await authApi.login(username, password)
localStorage.setItem('token', result.accessToken)
localStorage.setItem('refreshToken', result.refreshToken)
localStorage.setItem('user', JSON.stringify(result.user))
toast.success('登录成功')
navigate('/')
saveAuth(result, result.user)
navigate(result.user.role === 'admin' ? readRedirectParam(location.search) : '/logs', { replace: true })
} catch (err: unknown) {
const message = err instanceof Error ? err.message : '登录失败'
if (message.includes('Cannot connect')) {
setError('无法连接后端服务,请确认后端已启动(端口 8080)。')
setBackendStatus('offline')
} else if (
message.includes('invalid') ||
message.includes('password') ||
message.includes('密码') ||
message.includes('Unauthorized')
) {
setError('用户名或密码错误')
if (err instanceof ApiError) {
if (err.status === 0) {
// 网络/超时类错误
setError('无法连接后端服务,请确认后端已启动(端口 8080)。')
setBackendStatus('offline')
} else if (err.status === 401) {
setError('用户名或密码错误')
} else {
setError(err.message || '登录失败')
}
} else {
setError(message)
setError(err instanceof Error ? err.message : '登录失败')
}
} finally {
setLoading(false)
}
},
[username, password, navigate]
[username, password, navigate, location.search]
)
// 密码显示切换 - useCallback缓存
@@ -97,27 +83,27 @@ const Login = memo(function Login() {
}, [])
return (
<div className="min-h-screen bg-slate-50 dark:bg-slate-950 flex items-center justify-center p-4">
<div className="min-h-screen bg-background flex justify-center px-4 pt-[8vh] md:pt-[14vh] pb-8">
<div className="w-full max-w-md">
{/* Logo */}
<div className="text-center mb-8">
<div className="inline-flex items-center justify-center w-16 h-16 rounded-2xl bg-emerald-500 mb-4">
<Activity className="w-9 h-9 text-white" />
<div className="text-center mb-6">
<div className="inline-flex items-center justify-center w-14 h-14 rounded-2xl bg-primary mb-3">
<Activity className="w-8 h-8 text-primary-foreground" />
</div>
<h1 className="text-2xl font-bold text-slate-900 dark:text-white">LokiDeploy</h1>
<p className="text-sm text-slate-500 mt-1">Kubernetes Loki 日志部署平台</p>
<h1 className="text-2xl font-bold text-foreground">opsx-loki</h1>
<p className="text-sm text-muted-foreground mt-1">Kubernetes Loki 日志部署平台</p>
</div>
{/* Backend Status */}
{backendStatus === 'offline' && (
<div className="mb-4 p-4 rounded-xl bg-amber-50 border border-amber-200 flex items-start gap-3">
<ServerOff className="w-5 h-5 text-amber-600 flex-shrink-0 mt-0.5" />
<div className="mb-4 p-4 rounded-xl bg-warning/10 border border-warning/30 flex items-start gap-3">
<ServerOff className="w-5 h-5 text-warning flex-shrink-0 mt-0.5" />
<div>
<p className="text-sm font-medium text-amber-800">后端服务未启动</p>
<p className="text-xs text-amber-700 mt-1">
<p className="text-sm font-medium text-warning">后端服务未启动</p>
<p className="text-xs text-warning mt-1">
无法连接 API 服务,请先启动后端:
</p>
<code className="block mt-2 px-3 py-2 bg-amber-100 rounded text-xs font-mono text-amber-900">
<code className="block mt-2 px-3 py-2 bg-warning/20 rounded text-xs font-mono text-warning">
./run.sh
</code>
</div>
@@ -125,14 +111,14 @@ const Login = memo(function Login() {
)}
{/* Login Card */}
<div className="bg-white dark:bg-slate-900 rounded-2xl shadow-lg border border-slate-200 dark:border-slate-800 p-8">
<div className="bg-card rounded-2xl shadow-lg border border-border p-8">
<div className="flex items-center gap-2 mb-6">
<Shield className="w-5 h-5 text-emerald-500" />
<h2 className="text-lg font-semibold text-slate-800 dark:text-white">登录</h2>
<Shield className="w-5 h-5 text-primary" />
<h2 className="text-lg font-semibold text-foreground">登录</h2>
</div>
{error && (
<div className="mb-4 p-3 rounded-lg bg-red-50 border border-red-200 text-red-600 text-sm">
<div className="mb-4 p-3 rounded-lg bg-destructive/10 border border-destructive/30 text-destructive text-sm">
{error}
</div>
)}
@@ -167,7 +153,7 @@ const Login = memo(function Login() {
<button
type="button"
onClick={togglePassword}
className="absolute right-3 top-1/2 -translate-y-1/2 text-slate-400 hover:text-slate-600"
className="absolute right-3 top-1/2 -translate-y-1/2 text-muted-foreground hover:text-foreground"
tabIndex={-1}
>
{showPassword ? (
@@ -181,18 +167,12 @@ const Login = memo(function Login() {
<Button
type="submit"
className="w-full h-10 bg-emerald-600 hover:bg-emerald-700 text-white"
className="w-full h-10 bg-primary hover:bg-primary/90 text-primary-foreground"
disabled={loading}
>
{loading ? '登录中...' : '登录'}
</Button>
</form>
<div className="mt-6 pt-4 border-t border-slate-100 dark:border-slate-800">
<p className="text-xs text-center text-slate-500">
默认账号:admin / admin123
</p>
</div>
</div>
</div>
</div>
+24
View File
@@ -0,0 +1,24 @@
import { FileQuestion, Home } from 'lucide-react'
import { Link } from 'react-router'
import { Button } from '@/components/ui/button'
/** 404 页面 — 通配路由的显式落点,不静默跳首页 */
export default function NotFound() {
return (
<div className="min-h-screen bg-muted dark:bg-slate-950 flex items-center justify-center p-6">
<div className="max-w-md w-full text-center">
<div className="inline-flex items-center justify-center w-16 h-16 rounded-2xl bg-muted mb-6">
<FileQuestion className="w-8 h-8 text-muted-foreground" />
</div>
<h1 className="text-5xl font-bold text-foreground mb-2">404</h1>
<p className="text-muted-foreground mb-8">页面不存在或已被移除</p>
<Button asChild className="bg-primary hover:bg-primary/90 text-primary-foreground">
<Link to="/">
<Home className="w-4 h-4 mr-2" />
返回首页
</Link>
</Button>
</div>
</div>
)
}
@@ -0,0 +1,203 @@
import { memo, useCallback, useEffect, useState } from 'react'
import { Building2 } 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 { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card'
import { PasswordInput } from '@/components/PasswordInput'
import { ldapApi, type LdapConfig, type LdapTestResult } from '@/api/ldap'
import { toast } from 'sonner'
const EMPTY: LdapConfig = {
enabled: false,
host: '',
port: 389,
useSSL: false,
bindDN: '',
bindPassword: '',
baseDN: '',
userFilter: '(objectClass=inetOrgPerson)',
usernameAttr: 'uid',
nameAttr: 'displayName',
emailAttr: 'mail',
}
/**
* LDAP 配置卡片 — 启用开关 + 表单 + 表单参数直测(未保存也可测);
* 密码已保存时占位提示,留空提交即保留旧值。启用且配置齐全后,
* 用户管理页才会出现「从 LDAP 导入」。
*/
export const LdapSection = memo(function LdapSection() {
const [cfg, setCfg] = useState<LdapConfig>(EMPTY)
const [loaded, setLoaded] = useState(false)
const [saving, setSaving] = useState(false)
const [testing, setTesting] = useState(false)
const [testResult, setTestResult] = useState<LdapTestResult | null>(null)
useEffect(() => {
ldapApi
.getConfig()
.then((c) => {
setCfg({ ...EMPTY, ...c, bindPassword: '' })
setLoaded(true)
})
.catch(() => toast.error('加载 LDAP 配置失败'))
}, [])
const set = useCallback(<K extends keyof LdapConfig>(k: K, v: LdapConfig[K]) => {
setCfg((prev) => ({ ...prev, [k]: v }))
}, [])
const handleTest = async () => {
if (!cfg.host || !cfg.bindDN || !cfg.baseDN) {
toast.error('请先填写服务器地址 / Bind DN / Base DN')
return
}
setTesting(true)
setTestResult(null)
try {
const result = await ldapApi.test(cfg)
setTestResult(result)
} catch (err) {
toast.error(err instanceof Error ? err.message : '测试失败')
} finally {
setTesting(false)
}
}
const handleSave = async () => {
setSaving(true)
try {
const saved = await ldapApi.saveConfig(cfg)
setCfg({ ...EMPTY, ...saved, bindPassword: '' })
toast.success('LDAP 配置已保存')
} catch (err) {
toast.error(err instanceof Error ? err.message : '保存失败')
} finally {
setSaving(false)
}
}
return (
<Card className="border-border">
<CardHeader className="pb-3">
<CardTitle className="text-base flex items-center justify-between">
<span className="flex items-center gap-2">
<Building2 className="w-4 h-4" />
LDAP 接入
</span>
<div className="flex items-center gap-2">
<span className="text-xs text-muted-foreground">启用后支持 LDAP 登录与批量导入</span>
<Switch checked={cfg.enabled} onCheckedChange={(v) => set('enabled', v)} />
</div>
</CardTitle>
</CardHeader>
<CardContent className="space-y-4">
{loaded && !cfg.enabled ? (
<p className="text-sm text-muted-foreground py-2 text-center">
LDAP 未启用 —— 打开开关填写目录服务信息(服务器 / Bind DN / Base DN),
保存后用户管理页将出现「从 LDAP 导入」
</p>
) : (
<div className="grid grid-cols-1 md:grid-cols-2 gap-4">
<div className="space-y-2">
<Label>服务器地址 *</Label>
<Input
placeholder="8.217.205.92"
value={cfg.host}
onChange={(e) => set('host', e.target.value)}
/>
</div>
<div className="grid grid-cols-3 gap-3">
<div className="space-y-2 col-span-2">
<Label>端口</Label>
<Input
type="number"
value={cfg.port || 389}
onChange={(e) => set('port', Number(e.target.value))}
/>
</div>
<div className="space-y-2 flex flex-col">
<Label>LDAPS</Label>
<div className="pt-2">
<Switch checked={cfg.useSSL} onCheckedChange={(v) => set('useSSL', v)} />
</div>
</div>
</div>
<div className="space-y-2 md:col-span-2">
<Label>Bind DN *</Label>
<Input
placeholder="cn=admin,dc=example,dc=com"
value={cfg.bindDN}
onChange={(e) => set('bindDN', e.target.value)}
/>
</div>
<div className="space-y-2">
<Label>Bind 密码 *</Label>
<PasswordInput
placeholder={cfg.hasPassword ? '已保存,输入新密码以修改' : '管理员密码'}
value={cfg.bindPassword}
onChange={(e) => set('bindPassword', e.target.value)}
autoComplete="new-password"
/>
</div>
<div className="space-y-2">
<Label>Base DN *</Label>
<Input
placeholder="dc=example,dc=com"
value={cfg.baseDN}
onChange={(e) => set('baseDN', e.target.value)}
/>
</div>
<div className="space-y-2">
<Label>用户过滤器</Label>
<Input value={cfg.userFilter} onChange={(e) => set('userFilter', e.target.value)} />
</div>
<div className="grid grid-cols-3 gap-3">
<div className="space-y-2">
<Label>用户名</Label>
<Input value={cfg.usernameAttr} onChange={(e) => set('usernameAttr', e.target.value)} />
</div>
<div className="space-y-2">
<Label>姓名</Label>
<Input value={cfg.nameAttr} onChange={(e) => set('nameAttr', e.target.value)} />
</div>
<div className="space-y-2">
<Label>邮箱</Label>
<Input value={cfg.emailAttr} onChange={(e) => set('emailAttr', e.target.value)} />
</div>
</div>
</div>
)}
{testResult && (
<div
role="status"
className={`p-3 rounded-lg border text-sm ${
testResult.success
? 'bg-success/10 border-success/30 text-success'
: 'bg-destructive/10 border-destructive/30 text-destructive'
}`}
>
{testResult.message}
{testResult.userInfo && (
<span className="block text-xs mt-1 opacity-80">
{testResult.userInfo.displayName} · {testResult.userInfo.email || '无邮箱'}
</span>
)}
</div>
)}
<div className="flex justify-end gap-2">
<Button variant="outline" onClick={handleTest} disabled={testing || !cfg.enabled}>
{testing ? '测试中...' : '测试连接'}
</Button>
<Button onClick={handleSave} disabled={saving || !cfg.enabled}>
{saving ? '保存中...' : '保存配置'}
</Button>
</div>
</CardContent>
</Card>
)
})
@@ -1,33 +1,35 @@
import { memo, useCallback, useState } from 'react'
import { useNavigate } from 'react-router'
import { KeyRound, Settings as SettingsIcon } from 'lucide-react'
import { Button } from '@/components/ui/button'
import { Input } from '@/components/ui/input'
import { Label } from '@/components/ui/label'
import { PasswordInput } from '@/components/PasswordInput'
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card'
import { authApi } from '@/api'
import { clearAuth } from '@/lib/auth-storage'
import { toast } from 'sonner'
import { PageHeader } from '@/components/PageHeader'
import { PageContainer } from '@/components/PageContainer'
import { LdapSection } from './components/LdapSection'
// 构建指纹由 vite define 注入;本地 tsc/预览时回退
const APP_VERSION = typeof __APP_VERSION__ !== 'undefined' ? __APP_VERSION__ : 'dev'
const COMMIT_HASH = typeof __COMMIT_HASH__ !== 'undefined' ? __COMMIT_HASH__ : '-'
// 系统信息常量
const SYSTEM_INFO = [
{ label: '版本', value: 'v1.0.0' },
{ label: '版本', value: `${APP_VERSION} (${COMMIT_HASH})` },
{ label: '后端', value: 'Go + Gin + JSON 文件存储' },
{ label: '前端', value: 'React 19 + TypeScript + Tailwind CSS' },
{ label: '部署工具', value: 'kubectl + helm(镜像内置)' },
{ label: '简介', value: '轻量级 K8s Loki 部署平台', align: 'right' as const },
{ label: '简介', value: '轻量级 K8s Loki 部署平台' },
]
/**
* Settings 页面 - 优化版本
*
* 优化点:
* 1. React.memo 包裹组件
* 2. 表单处理使用 useCallback 缓存
* 3. alert() 替换为 sonner toast
* 4. 使用 PageHeader 公共组件
* 5. 提取常量避免重复创建
* 系统设置 — 修改密码 + 关于。
* 表单保持手写(字段少、校验已达标准);成功后清空表单即反馈(成功静默)。
*/
const Settings = memo(function Settings() {
const SettingsPage = memo(function SettingsPage() {
const navigate = useNavigate()
const [oldPassword, setOldPassword] = useState('')
const [newPassword, setNewPassword] = useState('')
const [confirmPassword, setConfirmPassword] = useState('')
@@ -47,10 +49,9 @@ const Settings = memo(function Settings() {
setChanging(true)
try {
await authApi.changePassword(oldPassword, newPassword)
toast.success('密码修改成功')
setOldPassword('')
setNewPassword('')
setConfirmPassword('')
// 改密后后端已吊销当前会话(TokenVersion+1),主动登出回登录页
clearAuth()
navigate('/login', { replace: true })
} catch (err: unknown) {
const message = err instanceof Error ? err.message : '密码修改失败'
toast.error(message)
@@ -58,16 +59,16 @@ const Settings = memo(function Settings() {
setChanging(false)
}
},
[oldPassword, newPassword, confirmPassword]
[oldPassword, newPassword, confirmPassword, navigate]
)
return (
<div className="space-y-6">
<PageHeader title="系统设置" description="修改登录密码与查看系统信息" />
<PageContainer title="系统设置" description="修改登录密码、LDAP 接入与系统信息">
<LdapSection />
<div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
{/* 修改密码 */}
<Card className="border-slate-200 dark:border-slate-800">
<Card className="border-border">
<CardHeader className="pb-3">
<CardTitle className="text-base flex items-center gap-2">
<KeyRound className="w-4 h-4" />
@@ -78,41 +79,41 @@ const Settings = memo(function Settings() {
<form onSubmit={handleChangePassword} className="space-y-4">
<div className="space-y-2">
<Label htmlFor="old-pwd">当前密码</Label>
<Input
<PasswordInput
id="old-pwd"
type="password"
value={oldPassword}
onChange={(e) => setOldPassword(e.target.value)}
placeholder="请输入当前密码"
required
autoComplete="current-password"
/>
</div>
<div className="space-y-2">
<Label htmlFor="new-pwd">新密码</Label>
<Input
<PasswordInput
id="new-pwd"
type="password"
value={newPassword}
onChange={(e) => setNewPassword(e.target.value)}
placeholder="请输入新密码(至少 6 位)"
required
minLength={6}
autoComplete="new-password"
/>
</div>
<div className="space-y-2">
<Label htmlFor="confirm-pwd">确认新密码</Label>
<Input
<PasswordInput
id="confirm-pwd"
type="password"
value={confirmPassword}
onChange={(e) => setConfirmPassword(e.target.value)}
placeholder="请再次输入新密码"
required
autoComplete="new-password"
/>
</div>
<Button
type="submit"
className="bg-emerald-600 hover:bg-emerald-700"
className="bg-primary hover:bg-primary/90"
disabled={changing}
>
{changing ? '修改中...' : '修改密码'}
@@ -122,11 +123,11 @@ const Settings = memo(function Settings() {
</Card>
{/* 关于 */}
<Card className="border-slate-200 dark:border-slate-800">
<Card className="border-border">
<CardHeader className="pb-3">
<CardTitle className="text-base flex items-center gap-2">
<SettingsIcon className="w-4 h-4" />
关于 LokiDeploy
关于 opsx-loki
</CardTitle>
</CardHeader>
<CardContent>
@@ -136,26 +137,20 @@ const Settings = memo(function Settings() {
key={item.label}
className={`flex justify-between py-2.5 ${
index < SYSTEM_INFO.length - 1
? 'border-b border-slate-100 dark:border-slate-800'
? 'border-b border-border'
: ''
}`}
>
<span className="text-sm text-slate-500">{item.label}</span>
<span
className={`text-sm font-medium ${
item.align === 'right' ? 'text-right' : ''
}`}
>
{item.value}
</span>
<span className="text-sm text-muted-foreground">{item.label}</span>
<span className="text-sm font-medium">{item.value}</span>
</div>
))}
</div>
</CardContent>
</Card>
</div>
</div>
</PageContainer>
)
})
export default Settings
export default SettingsPage
@@ -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
@@ -0,0 +1,203 @@
import { memo, useCallback, useEffect, useMemo, useState } from 'react'
import { Link } from 'react-router'
import { Users, RefreshCw } from 'lucide-react'
import { Button } from '@/components/ui/button'
import { Checkbox } from '@/components/ui/checkbox'
import {
Dialog,
DialogContent,
DialogDescription,
DialogHeader,
DialogTitle,
} from '@/components/ui/dialog'
import { ScrollArea } from '@/components/ui/scroll-area'
import { ldapApi, type LdapUserPreview, type LdapImportResult } from '@/api/ldap'
import { toast } from 'sonner'
import type { User } from '@/types'
interface LdapImportDialogProps {
open: boolean
onOpenChange: (open: boolean) => void
/** 本地用户列表(用于标记已导入,禁选) */
localUsers: User[]
onImported: () => void
}
/**
* 从 LDAP 导入用户弹窗 — 打开即拉取 LDAP 用户列表;
* 已导入(LDAP 来源)置灰禁选;本地同名用户标注「将转为 LDAP」。
*/
export const LdapImportDialog = memo(function LdapImportDialog({
open,
onOpenChange,
localUsers,
onImported,
}: LdapImportDialogProps) {
const [loading, setLoading] = useState(false)
const [importing, setImporting] = useState(false)
const [users, setUsers] = useState<LdapUserPreview[]>([])
const [selected, setSelected] = useState<Set<string>>(new Set())
const [result, setResult] = useState<LdapImportResult | null>(null)
const [error, setError] = useState('')
const localMap = useMemo(() => {
const m = new Map<string, User>()
localUsers.forEach((u) => m.set(u.username, u))
return m
}, [localUsers])
const loadUsers = useCallback(async () => {
setLoading(true)
setError('')
setResult(null)
try {
const list = await ldapApi.listUsers()
setUsers(list)
setSelected(new Set())
} catch (err) {
setError(err instanceof Error ? err.message : '加载 LDAP 用户失败')
} finally {
setLoading(false)
}
}, [])
useEffect(() => {
if (open) void loadUsers()
}, [open, loadUsers])
const toggle = (username: string, disabled: boolean) => {
if (disabled) return
setSelected((prev) => {
const next = new Set(prev)
if (next.has(username)) next.delete(username)
else next.add(username)
return next
})
}
const handleImport = async () => {
const picked = users.filter((u) => selected.has(u.username))
if (picked.length === 0) return
setImporting(true)
try {
const r = await ldapApi.batchImport(
picked.map((u) => ({
dn: u.dn, username: u.username, nickname: u.displayName, email: u.email,
}))
)
setResult(r)
onImported()
} catch (err) {
toast.error(err instanceof Error ? err.message : '导入失败')
} finally {
setImporting(false)
}
}
return (
<Dialog open={open} onOpenChange={onOpenChange}>
<DialogContent className="max-w-2xl">
<DialogHeader>
<DialogTitle>从 LDAP 导入用户</DialogTitle>
<DialogDescription>
来自 LDAP 目录的用户;导入后使用 LDAP 密码登录,角色为普通用户
</DialogDescription>
</DialogHeader>
{result ? (
<div className="space-y-3">
<div className="flex items-center gap-4 text-sm">
{result.successCount > 0 && (
<span className="text-success">新增 {result.successCount}</span>
)}
{result.updatedCount > 0 && <span className="text-info">转为 LDAP {result.updatedCount}</span>}
{result.skippedCount > 0 && <span className="text-muted-foreground">跳过 {result.skippedCount}</span>}
{result.failedCount > 0 && <span className="text-destructive">失败 {result.failedCount}</span>}
</div>
{result.failedUsers.length > 0 && (
<div className="text-xs text-destructive space-y-1 max-h-32 overflow-y-auto">
{result.failedUsers.map((f) => (
<p key={f.username}>{f.username}:{f.error}</p>
))}
</div>
)}
<div className="flex justify-end gap-2">
<Button variant="outline" onClick={() => void loadUsers()}>继续导入</Button>
<Button onClick={() => onOpenChange(false)}>完成</Button>
</div>
</div>
) : (
<>
<div className="flex items-center justify-between">
<p className="text-xs text-muted-foreground">
{loading ? '加载 LDAP 用户…' : `共 ${users.length} 个用户,已选 ${selected.size} 个`}
</p>
<Button variant="ghost" size="sm" onClick={() => void loadUsers()} disabled={loading}>
<RefreshCw className={`w-3.5 h-3.5 ${loading ? 'animate-spin' : ''}`} />
</Button>
</div>
{error ? (
<div className="space-y-3">
<p className="text-sm text-destructive">{error}</p>
<p className="text-xs text-muted-foreground">
请到
<Link to="/settings" className="text-primary mx-1">系统设置</Link>
检查 LDAP 配置与启用状态
</p>
</div>
) : (
<ScrollArea className="h-72 rounded-lg border border-border">
<div className="divide-y divide-border">
{users.map((u) => {
const local = localMap.get(u.username)
const isLdapAlready = local?.['authSource'] === 'ldap'
const willConvert = !!local && !isLdapAlready
const disabled = isLdapAlready
const checked = selected.has(u.username)
return (
<label
key={u.dn}
className={`flex items-center gap-3 px-3 py-2.5 ${disabled ? 'opacity-50' : 'cursor-pointer hover:bg-muted/50'}`}
>
<Checkbox
checked={checked}
disabled={disabled}
onCheckedChange={() => toggle(u.username, disabled)}
/>
<div className="flex-1 min-w-0">
<div className="flex items-center gap-2">
<span className="text-sm font-medium">{u.username}</span>
{isLdapAlready && (
<span className="text-xs text-muted-foreground">已导入</span>
)}
{willConvert && (
<span className="text-xs text-info">本地同名,将转为 LDAP</span>
)}
</div>
<p className="text-xs text-muted-foreground truncate">
{u.displayName || '无姓名'} · {u.email || '无邮箱'}
</p>
</div>
</label>
)
})}
{!loading && users.length === 0 && (
<div className="flex items-center justify-center gap-2 py-10 text-muted-foreground text-sm">
<Users className="w-4 h-4" /> 目录下没有用户
</div>
)}
</div>
</ScrollArea>
)}
<div className="flex justify-end gap-2">
<Button variant="outline" onClick={() => onOpenChange(false)}>取消</Button>
<Button onClick={handleImport} disabled={importing || selected.size === 0}>
{importing ? '导入中...' : `导入 ${selected.size} 个用户`}
</Button>
</div>
</>
)}
</DialogContent>
</Dialog>
)
})
@@ -0,0 +1,124 @@
import { memo, useEffect, useState } from 'react'
import { Dice5 } from 'lucide-react'
import { Button } from '@/components/ui/button'
import {
Dialog,
DialogContent,
DialogDescription,
DialogHeader,
DialogTitle,
} from '@/components/ui/dialog'
import { Label } from '@/components/ui/label'
import { PasswordInput } from '@/components/PasswordInput'
import { userApi } from '@/api'
import { toast } from 'sonner'
import type { User } from '@/types'
// 随机密码:12 位,大小写字母 + 数字,满足后端 min=6
function randomPassword(): string {
const chars = 'ABCDEFGHJKLMNPQRSTUVWXYZabcdefghjkmnpqrstuvwxyz23456789'
let pwd = ''
const array = new Uint32Array(12)
crypto.getRandomValues(array)
for (let i = 0; i < 12; i++) {
pwd += chars[array[i] % chars.length]
}
return pwd
}
interface ResetPasswordDialogProps {
user: User | null
onClose: () => void
/** 重置成功回调(提示信息由调用方决定) */
onReset: () => void
}
/** 管理员重置密码弹窗 — 重置后目标用户全部旧会话立即失效(后端递增 TokenVersion) */
export const ResetPasswordDialog = memo(function ResetPasswordDialog({
user,
onClose,
onReset,
}: ResetPasswordDialogProps) {
const [password, setPassword] = useState('')
const [submitting, setSubmitting] = useState(false)
const [error, setError] = useState('')
useEffect(() => {
if (user) {
setPassword('')
setError('')
}
}, [user])
const handleSubmit = async (e: React.FormEvent) => {
e.preventDefault()
if (password.length < 6) {
setError('密码至少需要 6 位')
return
}
if (!user) return
setSubmitting(true)
try {
await userApi.resetPassword(user.id, password)
onClose()
onReset()
} catch (err) {
toast.error(err instanceof Error ? err.message : '重置密码失败')
} finally {
setSubmitting(false)
}
}
return (
<Dialog open={user !== null} onOpenChange={(open) => !open && onClose()}>
<DialogContent className="max-w-md">
<DialogHeader>
<DialogTitle>重置密码</DialogTitle>
<DialogDescription>
重置「{user?.username}」的密码后,该用户的所有登录会话将立即失效。
</DialogDescription>
</DialogHeader>
<form onSubmit={handleSubmit} className="space-y-4">
<div className="space-y-2">
<Label htmlFor="reset-password">新密码 *</Label>
<div className="flex gap-2">
<PasswordInput
id="reset-password"
className="flex-1"
placeholder="至少 6 位"
value={password}
onChange={(e) => {
setPassword(e.target.value)
setError('')
}}
autoComplete="new-password"
required
/>
<Button
type="button"
variant="outline"
aria-label="随机生成密码"
title="随机生成密码"
onClick={() => {
setPassword(randomPassword())
setError('')
}}
>
<Dice5 className="w-4 h-4" />
</Button>
</div>
{error && <p className="text-sm text-destructive">{error}</p>}
</div>
<div className="flex justify-end gap-2">
<Button type="button" variant="outline" onClick={onClose} disabled={submitting}>
取消
</Button>
<Button type="submit" disabled={submitting || password.length < 6}>
{submitting ? '重置中...' : '重置密码'}
</Button>
</div>
</form>
</DialogContent>
</Dialog>
)
})
@@ -0,0 +1,174 @@
import { memo, useEffect, useState } from 'react'
import { useForm } from 'react-hook-form'
import { zodResolver } from '@hookform/resolvers/zod'
import { z } from 'zod'
import { Button } from '@/components/ui/button'
import { Input } from '@/components/ui/input'
import {
Dialog,
DialogContent,
DialogHeader,
DialogTitle,
} from '@/components/ui/dialog'
import {
Form,
FormControl,
FormField,
FormItem,
FormLabel,
FormMessage,
} from '@/components/ui/form'
import {
Select,
SelectContent,
SelectItem,
SelectTrigger,
SelectValue,
} from '@/components/ui/select'
import { PasswordInput } from '@/components/PasswordInput'
import { userApi } from '@/api'
import { toast } from 'sonner'
const userFormSchema = z.object({
username: z
.string()
.min(2, '用户名至少 2 个字符')
.max(32, '用户名最多 32 个字符'),
nickname: z.string().optional(),
password: z.string().min(6, '密码至少需要 6 位'),
role: z.enum(['admin', 'user']),
})
export type UserFormValues = z.infer<typeof userFormSchema>
const DEFAULT_VALUES: UserFormValues = {
username: '',
nickname: '',
password: '',
role: 'user',
}
interface UserFormDialogProps {
open: boolean
onOpenChange: (open: boolean) => void
onCreated: () => void
}
/** 创建用户弹窗 — admin 专用,RHF + zod */
export const UserFormDialog = memo(function UserFormDialog({
open,
onOpenChange,
onCreated,
}: UserFormDialogProps) {
const [submitting, setSubmitting] = useState(false)
const form = useForm<UserFormValues>({
resolver: zodResolver(userFormSchema),
defaultValues: DEFAULT_VALUES,
})
useEffect(() => {
if (open) {
form.reset(DEFAULT_VALUES)
}
}, [open, form])
const onSubmit = form.handleSubmit(async (values) => {
setSubmitting(true)
try {
await userApi.create({
username: values.username,
nickname: values.nickname || undefined,
password: values.password,
role: values.role,
})
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-md">
<DialogHeader>
<DialogTitle>创建用户</DialogTitle>
</DialogHeader>
<Form {...form}>
<form onSubmit={onSubmit} className="space-y-4">
<FormField
control={form.control}
name="username"
render={({ field }) => (
<FormItem>
<FormLabel>用户名 *</FormLabel>
<FormControl>
<Input placeholder="登录用户名" autoComplete="off" {...field} />
</FormControl>
<FormMessage />
</FormItem>
)}
/>
<FormField
control={form.control}
name="nickname"
render={({ field }) => (
<FormItem>
<FormLabel>昵称</FormLabel>
<FormControl>
<Input placeholder="显示昵称(可选)" {...field} />
</FormControl>
<FormMessage />
</FormItem>
)}
/>
<FormField
control={form.control}
name="password"
render={({ field }) => (
<FormItem>
<FormLabel>初始密码 *</FormLabel>
<FormControl>
<PasswordInput
placeholder="至少 6 位"
autoComplete="new-password"
{...field}
/>
</FormControl>
<FormMessage />
</FormItem>
)}
/>
<FormField
control={form.control}
name="role"
render={({ field }) => (
<FormItem>
<FormLabel>角色 *</FormLabel>
<Select value={field.value} onValueChange={field.onChange}>
<FormControl>
<SelectTrigger>
<SelectValue placeholder="选择角色" />
</SelectTrigger>
</FormControl>
<SelectContent>
<SelectItem value="user">普通用户</SelectItem>
<SelectItem value="admin">管理员</SelectItem>
</SelectContent>
</Select>
<FormMessage />
</FormItem>
)}
/>
<Button type="submit" className="w-full" disabled={submitting}>
{submitting ? '创建中...' : '创建用户'}
</Button>
</form>
</Form>
</DialogContent>
</Dialog>
)
})
+223
View File
@@ -0,0 +1,223 @@
import { memo, useCallback, useEffect, useState } from 'react'
import { Users, UserRound, UsersRound, Plus, KeyRound, Trash2, ShieldCheck } from 'lucide-react'
import { Button } from '@/components/ui/button'
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card'
import { userApi } from '@/api'
import { PageContainer } from '@/components/PageContainer'
import { LoadingSpinner } from '@/components/LoadingSpinner'
import { EmptyState } from '@/components/EmptyState'
import { ErrorState } from '@/components/ErrorState'
import { ConfirmDialog } from '@/components/ConfirmDialog'
import { useListQuery } from '@/hooks/useListQuery'
import { ldapApi, type LdapConfig } from '@/api/ldap'
import { LdapImportDialog } from './components/LdapImportDialog'
import { getUser } from '@/lib/auth-storage'
import { toast } from 'sonner'
import type { User } from '@/types'
import { UserFormDialog } from './components/UserFormDialog'
import { ResetPasswordDialog } from './components/ResetPasswordDialog'
/** 角色徽章 */
function SourceBadge({ source }: { source?: string }) {
return (
<span className="inline-flex items-center px-2 py-0.5 rounded-full bg-info/10 text-info text-xs font-medium">
{source === 'ldap' ? 'LDAP 导入' : '本地账号'}
</span>
)
}
function RoleBadge({ role }: { role: string }) {
return role === 'admin' ? (
<span className="inline-flex items-center gap-1 px-2 py-0.5 rounded-full bg-success/10 text-success text-xs font-medium">
<ShieldCheck className="w-3 h-3" />
管理员
</span>
) : (
<span className="inline-flex items-center gap-1 px-2 py-0.5 rounded-full bg-muted text-muted-foreground text-xs font-medium">
普通用户
</span>
)
}
/**
* 用户管理页(admin 专用,无 RBAC — 用户仅 admin/user 两级)
* - 非 admin 直访时显示权限提示空态(后端 AdminAuth 403 兜底)
* - 单卡片行列表 + 创建/重置密码/删除;成功操作静默(反馈分级)
*/
const UsersPage = memo(function UsersPage() {
const currentUser = getUser()
const isAdmin = currentUser?.role === 'admin'
const query = useListQuery<User>((params, signal) =>
userApi.list(params, { signal })
)
const [formOpen, setFormOpen] = useState(false)
const [ldapImportOpen, setLdapImportOpen] = useState(false)
// LDAP 已启用且配置齐全才显示「从 LDAP 导入」(用户要求的联动)
const [ldapReady, setLdapReady] = useState(false)
useEffect(() => {
ldapApi
.getConfig()
.then((c: LdapConfig) => setLdapReady(!!(c.enabled && c.configured)))
.catch(() => setLdapReady(false))
}, [])
const [resetTarget, setResetTarget] = useState<User | null>(null)
const [deleteTarget, setDeleteTarget] = useState<User | null>(null)
const [deleting, setDeleting] = useState(false)
const handleDelete = useCallback(async () => {
const id = deleteTarget?.id
if (!id) return
setDeleting(true)
try {
await userApi.remove(id)
setDeleteTarget(null)
query.refresh()
} catch (err) {
toast.error(err instanceof Error ? err.message : '删除用户失败')
} finally {
setDeleting(false)
}
}, [deleteTarget, query])
// 非管理员:菜单不可见,直访时给明确提示
if (!isAdmin) {
return (
<PageContainer title="用户管理">
<EmptyState
icon={UserRound}
title="需要管理员权限"
description="用户管理仅管理员可用,请联系管理员处理账号事宜"
/>
</PageContainer>
)
}
return (
<PageContainer
title="用户管理"
description="管理平台登录账号(仅管理员)"
action={
<div className="flex items-center gap-2">
{ldapReady && (
<Button variant="outline" onClick={() => setLdapImportOpen(true)}>
<UsersRound className="w-4 h-4 mr-1" />
从 LDAP 导入
</Button>
)}
<Button onClick={() => setFormOpen(true)}>
<Plus className="w-4 h-4 mr-1" />
创建用户
</Button>
</div>
}
>
{query.loading ? (
<LoadingSpinner className="h-64" />
) : query.error ? (
<ErrorState message={query.error} onRetry={query.refresh} />
) : query.list.length === 0 ? (
<EmptyState icon={Users} title="暂无用户" description="创建第一个用户账号" />
) : (
<Card className="border-border">
<CardHeader className="pb-3">
<CardTitle className="text-base flex items-center gap-2">
<Users className="w-4 h-4" />
用户列表(共 {query.total} 个)
</CardTitle>
</CardHeader>
<CardContent className="pt-0">
<div className="divide-y divide-border">
{query.list.map((user) => (
<div
key={user.id}
className="flex items-center justify-between gap-3 py-3 first:pt-0 last:pb-0"
>
<div className="flex items-center gap-3 min-w-0">
<div className="w-9 h-9 rounded-full bg-muted flex items-center justify-center flex-shrink-0">
<UserRound className="w-4 h-4 text-muted-foreground" />
</div>
<div className="min-w-0">
<div className="flex items-center gap-2">
<span className="font-medium truncate">{user.username}</span>
<RoleBadge role={user.role} />
<SourceBadge source={user.authSource} />
{user.id === currentUser?.id && (
<span className="text-xs text-muted-foreground">(当前登录)</span>
)}
</div>
<p className="text-xs text-muted-foreground truncate mt-0.5">
{user.nickname || '未设置昵称'}
{user.createdAt &&
` · 创建于 ${new Date(user.createdAt).toLocaleDateString()}`}
</p>
</div>
</div>
<div className="flex items-center gap-2 flex-shrink-0">
{user.authSource !== 'ldap' && (
<Button variant="outline" size="sm" onClick={() => setResetTarget(user)}>
<KeyRound className="w-3.5 h-3.5 mr-1" />
重置密码
</Button>
)}
<Button
variant="outline"
size="sm"
aria-label={`删除用户 ${user.username}`}
className="text-destructive hover:bg-destructive/10"
disabled={user.id === currentUser?.id}
title={
user.id === currentUser?.id ? '不能删除当前登录账号' : undefined
}
onClick={() => setDeleteTarget(user)}
>
<Trash2 className="w-3.5 h-3.5" />
</Button>
</div>
</div>
))}
</div>
</CardContent>
</Card>
)}
<UserFormDialog
open={formOpen}
onOpenChange={setFormOpen}
onCreated={query.reload}
/>
<LdapImportDialog
open={ldapImportOpen}
onOpenChange={setLdapImportOpen}
localUsers={query.list}
onImported={query.refresh}
/>
<ResetPasswordDialog
key={resetTarget?.id ?? 'none'}
user={resetTarget}
onClose={() => setResetTarget(null)}
onReset={() => {
toast.info(`已重置「${resetTarget?.username}」的密码,其所有会话已失效`)
setResetTarget(null)
}}
/>
<ConfirmDialog
open={deleteTarget !== null}
onOpenChange={(open) => {
if (!open) setDeleteTarget(null)
}}
name={deleteTarget?.username}
title="确认删除用户"
onConfirm={handleDelete}
loading={deleting}
/>
</PageContainer>
)
})
export default UsersPage
@@ -0,0 +1,143 @@
import { memo, useState } from 'react'
import { Plus, Rocket, ExternalLink } from 'lucide-react'
import { Link } from 'react-router'
import { Button } from '@/components/ui/button'
import { Card, CardContent } from '@/components/ui/card'
import { StatusBadge } from '@/components/StatusBadge'
import { deploymentApi } from '@/api'
import { toast } from 'sonner'
import { DeploymentFormDialog } from '@/pages/deployments/components/DeploymentFormDialog'
import type { Cluster, Host, StorageConfig } from '@/types'
interface StepDeployProps {
runningLoki: {
id: number
name: string
mode: string
endpoint: string
namespace: string
grafana: boolean
grafanaEndpoint?: string
} | null
clusters: Cluster[]
hosts: Host[]
storages: StorageConfig[]
onChanged: () => void
}
/**
* 步骤③ 部署 Loki(与 Grafana)— 创建后自动触发部署;
* 已有运行实例则展示状态卡(无需重复部署,可直接进入下一步)。
*/
export const StepDeploy = memo(function StepDeploy({
runningLoki,
clusters,
hosts,
storages,
onChanged,
}: StepDeployProps) {
const [open, setOpen] = useState(false)
const [deploying, setDeploying] = useState<number | null>(null)
const handleCreated = async () => {
onChanged()
// 创建成功即自动触发部署,向导内完成闭环
try {
const list = await deploymentApi.list({ page: 1, pageSize: 5 })
const latest = list.list[0]
if (latest && latest.status === 'pending') {
setDeploying(latest.id)
await deploymentApi.deploy(latest.id)
toast.info(`已触发「${latest.name}」部署,可在部署页查看日志与进度`)
}
} catch {
// 列表/触发失败不打断向导,用户可到部署页手动触发
} finally {
setDeploying(null)
}
}
return (
<Card className="border-border">
<CardContent className="p-5 space-y-3">
{runningLoki ? (
<div className="flex items-center justify-between gap-3 flex-wrap">
<div className="flex items-center gap-3 min-w-0">
<Rocket className="w-5 h-5 text-success flex-shrink-0" />
<div className="min-w-0">
<div className="flex items-center gap-2">
<span className="font-medium truncate">{runningLoki.name}</span>
<StatusBadge status="running" />
{runningLoki.grafana && (
<span className="px-2 py-0.5 rounded-full bg-info/10 text-info text-xs">
Grafana ✓
</span>
)}
</div>
<p className="text-xs text-muted-foreground truncate mt-0.5">
{runningLoki.mode} · 命名空间 {runningLoki.namespace || '-'} ·{' '}
{runningLoki.endpoint || 'endpoint 待部署完成生成'}
</p>
{runningLoki.grafanaEndpoint && (
<a
href={runningLoki.grafanaEndpoint}
target="_blank"
rel="noopener noreferrer"
className="text-xs text-primary hover:underline inline-flex items-center gap-1 mt-1"
>
<ExternalLink className="w-3 h-3" />
打开 Grafana({runningLoki.grafanaEndpoint.replace(/^https?:\/\//, '')} · admin/admin)
</a>
)}
</div>
</div>
<div className="flex items-center gap-2">
{runningLoki.endpoint && (
<Button variant="outline" size="sm" asChild>
<a
href={runningLoki.mode === 'host-binary' ? runningLoki.endpoint : undefined}
target="_blank"
rel="noopener noreferrer"
className={
runningLoki.mode === 'k8s-helm' || runningLoki.mode === 'k8s-yaml'
? 'pointer-events-none opacity-50'
: undefined
}
>
<ExternalLink className="w-3.5 h-3.5 mr-1" />
打开 Loki
</a>
</Button>
)}
<Button variant="outline" size="sm" asChild>
<Link to="/deployments">部署详情</Link>
</Button>
</div>
</div>
) : (
<div className="flex items-center justify-between">
<p className="text-sm text-muted-foreground">
尚无运行中的 Loki —— 选择目标与模式(k8s 副本 / 主机二进制),可同时部署 Grafana
</p>
<Button size="sm" onClick={() => setOpen(true)}>
<Plus className="w-4 h-4 mr-1" />
创建部署
</Button>
</div>
)}
{deploying !== null && (
<p className="text-xs text-info">正在触发部署…</p>
)}
<DeploymentFormDialog
open={open}
onOpenChange={setOpen}
onCreated={handleCreated}
clusters={clusters}
hosts={hosts}
storages={storages}
/>
</CardContent>
</Card>
)
})
@@ -0,0 +1,136 @@
import { memo, useState } from 'react'
import { Boxes, Server, Plus, CheckCircle2 } from 'lucide-react'
import { Button } from '@/components/ui/button'
import { Card, CardContent } from '@/components/ui/card'
import { cn } from '@/lib/utils'
import { ClusterFormDialog } from '@/pages/clusters/components/ClusterFormDialog'
import { HostFormDialog } from '@/pages/hosts/components/HostFormDialog'
type EnvKind = 'k8s' | 'host'
interface StepEnvProps {
hasActiveCluster: boolean
hasActiveHost: boolean
clusterNames: string[]
hostNames: string[]
onChanged: () => void
}
/**
* 步骤① 选择部署环境与接入目标 —— 首步先定形态(K8s 集群 / 裸金属主机),
* 该选择分支决定后续所有步骤(Loki 模式、采集类型、Grafana 形态)。
*/
export const StepEnv = memo(function StepEnv({
hasActiveCluster,
hasActiveHost,
clusterNames,
hostNames,
onChanged,
}: StepEnvProps) {
const [selected, setSelected] = useState<EnvKind | null>(null)
const [clusterOpen, setClusterOpen] = useState(false)
const [hostOpen, setHostOpen] = useState(false)
const envs: Array<{
kind: EnvKind
icon: typeof Boxes
title: string
desc: string
ready: boolean
names: string[]
}> = [
{
kind: 'k8s',
icon: Boxes,
title: 'Kubernetes 集群',
desc: '以 StatefulSet/Helm 部署 Loki 与 Grafana 副本,DaemonSet 采集容器日志',
ready: hasActiveCluster,
names: clusterNames,
},
{
kind: 'host',
icon: Server,
title: '裸金属主机',
desc: '以二进制 + systemd 部署 Loki 与 Grafana,采集指定日志文件',
ready: hasActiveHost,
names: hostNames,
},
]
return (
<Card className="border-border">
<CardContent className="p-5 space-y-4">
<div className="grid grid-cols-1 md:grid-cols-2 gap-3">
{envs.map((env) => {
const Icon = env.icon
const isSel = selected === env.kind
return (
<button
key={env.kind}
type="button"
onClick={() => setSelected(env.kind)}
className={cn(
'text-left p-4 rounded-xl border-2 transition-all',
isSel
? 'border-primary bg-primary/5'
: 'border-border hover:border-input bg-card'
)}
aria-pressed={isSel}
>
<div className="flex items-center justify-between mb-2">
<div className="flex items-center gap-2">
<Icon className={cn('w-5 h-5', isSel ? 'text-primary' : 'text-muted-foreground')} />
<span className="font-semibold">{env.title}</span>
</div>
{env.ready && (
<span className="inline-flex items-center gap-1 text-xs text-success">
<CheckCircle2 className="w-3.5 h-3.5" />
已就绪
</span>
)}
</div>
<p className="text-xs text-muted-foreground leading-4">{env.desc}</p>
{env.names.length > 0 && (
<p className="text-xs text-muted-foreground mt-2 truncate">
已接入:{env.names.join('、')}
</p>
)}
</button>
)
})}
</div>
{selected === 'k8s' && (
<div className="flex items-center justify-between rounded-lg bg-muted/50 p-3">
<p className="text-sm text-muted-foreground">
通过 kubeconfig 或 ServiceAccount Token 接入集群,创建后自动验证连通性
</p>
<Button size="sm" onClick={() => setClusterOpen(true)}>
<Plus className="w-4 h-4 mr-1" />
添加集群
</Button>
</div>
)}
{selected === 'host' && (
<div className="flex items-center justify-between rounded-lg bg-muted/50 p-3">
<p className="text-sm text-muted-foreground">
SSH 密钥或密码接入主机(用于部署与后续采集器安装)
</p>
<Button size="sm" onClick={() => setHostOpen(true)}>
<Plus className="w-4 h-4 mr-1" />
添加主机
</Button>
</div>
)}
{!selected && (
<p className="text-sm text-muted-foreground text-center py-1">
↑ 选择部署环境后,此处提供对应的目标接入表单
</p>
)}
<ClusterFormDialog open={clusterOpen} onOpenChange={setClusterOpen} onCreated={onChanged} />
<HostFormDialog open={hostOpen} onOpenChange={setHostOpen} onCreated={onChanged} />
</CardContent>
</Card>
)
})
@@ -0,0 +1,66 @@
import { memo, useState } from 'react'
import { Plus, CheckCircle2, Database } from 'lucide-react'
import { Button } from '@/components/ui/button'
import { Card, CardContent } from '@/components/ui/card'
import { StorageFormDialog } from '@/pages/storage/components/StorageFormDialog'
import { Link } from 'react-router'
interface StepStorageProps {
hasStorage: boolean
defaultStorage: string
onChanged: () => void
}
/**
* 步骤② 准备存储 —— k8s 多副本强烈建议对象存储(本地磁盘亦可运行);
* 表单内置连接测试与「桶不存在自动创建」。
*/
export const StepStorage = memo(function StepStorage({
hasStorage,
defaultStorage,
onChanged,
}: StepStorageProps) {
const [open, setOpen] = useState(false)
return (
<Card className="border-border">
<CardContent className="p-5 space-y-3">
<div className="flex items-center justify-between">
<div className="flex items-center gap-2 text-sm">
<Database className="w-4 h-4 text-muted-foreground" />
{hasStorage ? (
<span>
默认存储:<span className="font-medium text-foreground">{defaultStorage}</span>
</span>
) : (
<span className="text-muted-foreground">
尚未配置存储 —— 可选本地 MinIO / RustFS,或 AWS / 阿里云对象存储
</span>
)}
</div>
<div className="flex items-center gap-2">
{hasStorage && (
<Button variant="outline" size="sm" asChild>
<Link to="/storage">管理存储</Link>
</Button>
)}
<Button size="sm" onClick={() => setOpen(true)}>
<Plus className="w-4 h-4 mr-1" />
{hasStorage ? '添加存储' : '配置存储'}
</Button>
</div>
</div>
<div className="flex items-start gap-2 rounded-lg bg-muted/50 p-3 text-xs text-muted-foreground leading-5">
<CheckCircle2 className="w-4 h-4 mt-0.5 text-success flex-shrink-0" />
<p>
推荐对象存储(MinIO / RustFS / S3 / OSS):多副本与数据保留更可靠。
添加时可用「测试连接」验证凭证,并自动创建不存在的桶;跳过则使用本地磁盘。
</p>
</div>
<StorageFormDialog open={open} onOpenChange={setOpen} onCreated={onChanged} />
</CardContent>
</Card>
)
})
@@ -0,0 +1,62 @@
import { memo } from 'react'
import { Check } from 'lucide-react'
import { cn } from '@/lib/utils'
export interface WizardStepInfo {
title: string
desc: string
done: boolean
}
/**
* 向导步骤地图 — 状态推导式(opsx-sec 范式):完成态由真实数据计算,
* 非用户点击;active = 第一个未完成步骤。可任意顺序操作,刷新不丢。
*/
export const WizardSteps = memo(function WizardSteps({ steps }: { steps: WizardStepInfo[] }) {
const activeIndex = steps.findIndex((s) => !s.done)
return (
<div className="flex items-start gap-0 overflow-x-auto pb-2" aria-label="部署流程">
{steps.map((step, i) => {
const isActive = i === activeIndex
const isDone = step.done
return (
<div key={step.title} className="flex items-start min-w-[150px] flex-1">
<div className="flex flex-col items-center gap-1.5 flex-1">
<div
className={cn(
'w-9 h-9 rounded-full flex items-center justify-center flex-shrink-0 border-2 transition-colors',
isDone && 'bg-success border-success text-success-foreground',
isActive && !isDone && 'bg-primary/10 border-primary text-primary animate-pulse',
!isActive && !isDone && 'bg-muted border-border text-muted-foreground'
)}
aria-label={isDone ? `${step.title} 已完成` : `${step.title} 待完成`}
>
{isDone ? <Check className="w-4 h-4" /> : <span className="text-sm font-semibold">{i + 1}</span>}
</div>
<p
className={cn(
'text-sm font-medium text-center',
isDone && 'text-success',
isActive && !isDone && 'text-primary',
!isActive && !isDone && 'text-muted-foreground'
)}
>
{step.title}
</p>
<p className="text-xs text-muted-foreground text-center leading-4">{step.desc}</p>
</div>
{i < steps.length - 1 && (
<div
className={cn(
'h-0.5 mt-[18px] -ml-1 -mr-1 flex-1 rounded min-w-[16px]',
steps[i].done ? 'bg-success' : 'bg-border'
)}
/>
)}
</div>
)
})}
</div>
)
})
+195
View File
@@ -0,0 +1,195 @@
import { memo, useCallback, useEffect, useState } from 'react'
import { Link } from 'react-router'
import { RadioTower, ArrowRight, Plus } from 'lucide-react'
import { Card, CardContent } from '@/components/ui/card'
import { LoadingSpinner } from '@/components/LoadingSpinner'
import { ErrorState } from '@/components/ErrorState'
import { PageContainer } from '@/components/PageContainer'
import { deploymentApi, clusterApi, hostApi, storageApi } from '@/api'
import { Button } from '@/components/ui/button'
import type { Cluster, Host, StorageConfig, LokiDeployment } from '@/types'
import { WizardSteps, type WizardStepInfo } from './components/WizardSteps'
import { StepEnv } from './components/StepEnv'
import { StepStorage } from './components/StepStorage'
import { StepDeploy } from './components/StepDeploy'
import { CollectorFormDialog } from '@/pages/collectors/components/CollectorFormDialog'
interface Preflight {
hasStorage: boolean
defaultStorage: string
hasActiveCluster: boolean
clusterNames: string[]
hasActiveHost: boolean
hostNames: string[]
runningLoki: null | {
id: number
name: string
mode: string
endpoint: string
namespace: string
grafana: boolean
grafanaEndpoint?: string
}
activeCollectors: number
grafanaReady: boolean
}
/**
* 部署向导 — 状态推导式流程地图(步骤完成态由真实数据计算,可任意顺序/中断续走):
* ①环境与目标 → ②存储 → ③Loki(+Grafana)→ ④采集
*/
const WizardPage = memo(function WizardPage() {
const [pre, setPre] = useState<Preflight | null>(null)
const [error, setError] = useState<string | null>(null)
const [clusters, setClusters] = useState<Cluster[]>([])
const [hosts, setHosts] = useState<Host[]>([])
const [storages, setStorages] = useState<StorageConfig[]>([])
const [runningDeployments, setRunningDeployments] = useState<LokiDeployment[]>([])
const [collectorOpen, setCollectorOpen] = useState(false)
const refresh = useCallback(async () => {
try {
const [p, c, h, s, ds] = await Promise.all([
deploymentApi.preflight(),
clusterApi.list({ page: 1, pageSize: 50 }),
hostApi.list({ page: 1, pageSize: 50 }),
storageApi.list({ page: 1, pageSize: 50 }),
deploymentApi.list({ page: 1, pageSize: 50 }),
])
setPre(p)
setClusters(c.list)
setHosts(h.list)
setStorages(s.list)
setRunningDeployments(ds.list.filter((x) => x.status === 'running'))
setError(null)
} catch (err) {
setError(err instanceof Error ? err.message : '加载向导状态失败')
}
}, [])
useEffect(() => {
// refresh 为 async,setState 均发生在 await 之后(规则静态分析无法推断)
// eslint-disable-next-line react-hooks/set-state-in-effect
void refresh()
}, [refresh])
if (error) {
return (
<PageContainer title="部署向导">
<ErrorState message={error} onRetry={refresh} />
</PageContainer>
)
}
if (!pre) {
return <LoadingSpinner className="h-64" />
}
const steps: WizardStepInfo[] = [
{
title: '环境与目标',
desc: 'K8s 集群或裸金属主机',
done: pre.hasActiveCluster || pre.hasActiveHost,
},
{ title: '准备存储', desc: '对象存储或本地磁盘', done: pre.hasStorage },
{ title: '部署 Loki', desc: '日志查询平台内置', done: pre.runningLoki !== null },
{ title: '配置采集', desc: '主机文件 / 集群 DaemonSet', done: pre.activeCollectors > 0 },
]
const firstUndone = steps.findIndex((s) => !s.done)
const hints: string[] = []
if (firstUndone === 0) hints.push('先选择部署环境并接入集群或主机')
if (firstUndone === 1) hints.push('环境已就绪,建议先配置对象存储')
if (firstUndone === 2) hints.push('目标与存储已就绪,创建 Loki 部署吧')
if (firstUndone === 3) hints.push('Loki 已运行,添加采集策略开始收集日志')
if (firstUndone === -1) hints.push('全部就绪:日志正在收集,可到部署页查看与 Grafana 分析')
return (
<PageContainer
title="部署向导"
description="四步完成日志平台:环境 → 存储 → 部署 → 采集(步骤可按任意顺序完成)"
>
<Card className="border-border">
<CardContent className="p-5">
<WizardSteps steps={steps} />
<p className="text-sm text-muted-foreground text-center mt-3">
{hints.join(' · ')}
</p>
</CardContent>
</Card>
<StepEnv
hasActiveCluster={pre.hasActiveCluster}
hasActiveHost={pre.hasActiveHost}
clusterNames={pre.clusterNames}
hostNames={pre.hostNames}
onChanged={refresh}
/>
<StepStorage
hasStorage={pre.hasStorage}
defaultStorage={pre.defaultStorage}
onChanged={refresh}
/>
<StepDeploy
runningLoki={pre.runningLoki}
clusters={clusters}
hosts={hosts}
storages={storages}
onChanged={refresh}
/>
{/* 步骤④ 采集引导 */}
<Card className="border-border">
<CardContent className="p-5">
<div className="flex items-center justify-between flex-wrap gap-3">
<div className="flex items-center gap-3">
<RadioTower className="w-5 h-5 text-muted-foreground" />
<div>
<p className="text-sm font-medium">
日志采集策略
{pre.activeCollectors > 0 && (
<span className="ml-2 text-xs text-success">
{pre.activeCollectors} 个采集中
</span>
)}
</p>
<p className="text-xs text-muted-foreground mt-0.5">
主机:指定日志文件路径 · 集群:DaemonSet 全量容器日志(部署到关联 Loki 的命名空间)
</p>
</div>
</div>
<div className="flex items-center gap-2">
{runningDeployments.length > 0 && (
<Button
variant={pre.activeCollectors > 0 ? 'outline' : 'default'}
size="sm"
onClick={() => setCollectorOpen(true)}
>
<Plus className="w-3.5 h-3.5 mr-1" />
添加采集策略
</Button>
)}
<Button variant="outline" size="sm" asChild>
<Link to="/collectors">
管理采集
<ArrowRight className="w-3.5 h-3.5 ml-1" />
</Link>
</Button>
</div>
</div>
</CardContent>
</Card>
<CollectorFormDialog
open={collectorOpen}
onOpenChange={setCollectorOpen}
onCreated={refresh}
deployments={runningDeployments}
clusters={clusters}
hosts={hosts}
/>
</PageContainer>
)
})
export default WizardPage