Files
aiops/frontend/src/components/kubernetes/DeploymentEditStorage.tsx
T
attacker 5364d93ed7 fix(q1): 修复 tsc -b 构建中断 — 回退不安全的 unknown→any + 移除 Ansible 残留引用
- 781处 tsc -b 错误清零(unknown 属性访问/隐式any返回类型/类型转换不匹配)
- 移除 App.tsx 中已删除的 AnsibleManager/AnsibleWorkflow 导入和路由
- 修复 DeploymentView 中 _prefix 解构导致的属性不存在错误
- 修复 Header/Sidebar/PipelineEditor 中无效的类型断言
- asList() 返回类型 unknown[]→any[], 恢复 AgentMonitor 正常工作
- 放宽 noImplicitAny(临时), 待 types/ 定义完善后逐步恢复
- ESLint: unused=0, console=0, any=1041(Q1 后续降低)
- npm run build: ✅ 0 errors
2026-06-25 07:17:47 +08:00

420 lines
21 KiB
TypeScript

// DeploymentEditStorage.tsx — 编辑器「存储挂载」Tab
// Kuboard 风格:左侧定义数据卷 / 右侧挂载到容器
// 支持 6 种卷类型:PVC / EmptyDir / HostPath / NFS / ConfigMap / Secret
import { useState, useEffect } from 'react';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Badge } from '@/components/ui/badge';
import { Select, SelectContent, SelectItem, SelectTrigger} from '@/components/ui/select';
import {
Plus, Trash2, Save, Loader2, HardDrive, Database, Folder, Lock, File, Disc, Server,
} from 'lucide-react';
import { useToast } from '@/hooks/use-toast';
import { kubernetesApi } from '@/services/api';
interface Props {
clusterCode: string;
namespace: string;
deploymentName: string;
manifest: any | null;
onSaved: () => void;
onCancel: () => void;
}
/** 数据卷定义 */
interface VolumeForm {
name: string;
type: 'persistentVolumeClaim' | 'emptyDir' | 'hostPath' | 'nfs' | 'configMap' | 'secret';
// PVC
pvcName?: string; pvcReadOnly?: boolean;
// EmptyDir
medium?: string; sizeLimit?: string;
// HostPath
path?: string; pathType?: string;
// NFS
nfsServer?: string; nfsPath?: string; nfsReadOnly?: boolean;
// ConfigMap
configMapName?: string; cmItems?: string;
// Secret
secretName?: string; secItems?: string;
}
/** 容器挂载点 */
interface MountForm {
containerName: string;
volumeName: string;
mountPath: string;
subPath: string;
readOnly: boolean;
}
const VOLUME_TYPES: { key: VolumeForm['type']; label: string; icon: typeof HardDrive; color: string; desc: string }[] = [
{ key: 'persistentVolumeClaim', label: '存储卷声明', icon: Database, color: 'text-emerald-400', desc: 'PVC' },
{ key: 'emptyDir', label: '临时目录', icon: Disc, color: 'text-slate-400', desc: 'EmptyDir' },
{ key: 'hostPath', label: 'HostPath', icon: HardDrive, color: 'text-amber-400', desc: '主机路径' },
{ key: 'nfs', label: 'NFS', icon: Server, color: 'text-purple-400', desc: '网络存储' },
{ key: 'configMap', label: '配置字典', icon: File, color: 'text-blue-400', desc: 'ConfigMap' },
{ key: 'secret', label: '密文', icon: Lock, color: 'text-rose-400', desc: 'Secret' },
];
function volumeToForm( v: any): VolumeForm {
if (!v || typeof v !== 'object') return { name: '', type: 'emptyDir' };
const name = v.name || '';
if (v.emptyDir) return { name, type: 'emptyDir', medium: v.emptyDir.medium || '', sizeLimit: v.emptyDir.sizeLimit || '' };
if (v.hostPath) return { name, type: 'hostPath', path: v.hostPath.path || '', pathType: v.hostPath.type || 'Directory' };
if (v.configMap) return { name, type: 'configMap', configMapName: v.configMap.name || '', cmItems: v.configMap.items ? JSON.stringify(v.configMap.items) : '' };
if (v.secret) return { name, type: 'secret', secretName: v.secret.secretName || '', secItems: v.secret.items ? JSON.stringify(v.secret.items) : '' };
if (v.persistentVolumeClaim) return { name, type: 'persistentVolumeClaim', pvcName: v.persistentVolumeClaim.claimName || '', pvcReadOnly: !!v.persistentVolumeClaim.readOnly };
if (v.nfs) return { name, type: 'nfs', nfsServer: v.nfs.server || '', nfsPath: v.nfs.path || '', nfsReadOnly: !!v.nfs.readOnly };
return { name, type: 'emptyDir' };
}
function formToVolume(f: VolumeForm): any {
const v: Record<string, any> = { name: f.name.trim() };
if (!v.name) return null;
switch (f.type) {
case 'emptyDir': { const ed: Record<string, any> = {}; if (f.medium) ed.medium = f.medium; if (f.sizeLimit) ed.sizeLimit = f.sizeLimit; v.emptyDir = ed; break; }
case 'hostPath': v.hostPath = { path: f.path || '', type: f.pathType || 'Directory' }; break;
case 'configMap': { v.configMap = { name: f.configMapName || '' }; if (f.cmItems) try { v.configMap.items = JSON.parse(f.cmItems); } catch {} break; }
case 'secret': { v.secret = { secretName: f.secretName || '' }; if (f.secItems) try { v.secret.items = JSON.parse(f.secItems); } catch {} break; }
case 'persistentVolumeClaim': v.persistentVolumeClaim = { claimName: f.pvcName || '', ...(f.pvcReadOnly ? { readOnly: true } : {}) }; break;
case 'nfs': v.nfs = { server: f.nfsServer || '', path: f.nfsPath || '', ...(f.nfsReadOnly ? { readOnly: true } : {}) }; break;
}
return v;
}
export function DeploymentEditStorage({ clusterCode, namespace, deploymentName, manifest, onSaved, onCancel }: Props) {
const { toast } = useToast();
const [saving, setSaving] = useState(false);
const [loading, setLoading] = useState(!manifest);
const [rawManifest, setRawManifest] = useState<any>(manifest || {});
const [volumes, setVolumes] = useState<VolumeForm[]>([]);
const [mounts, setMounts] = useState<MountForm[]>([]);
const [containers, setContainers] = useState<string[]>([]);
useEffect(() => {
const m = manifest;
if (!m) { setLoading(false); return; }
setRawManifest(m);
const podSpec = m?.spec?.template?.spec || {};
// 数据卷
const vols: Record<string, any>[] = Array.isArray(podSpec.volumes) ? podSpec.volumes : [];
setVolumes(vols.map(volumeToForm));
// 容器列表
const allContainers = [
...(podSpec.containers || []),
...(podSpec.initContainers || []),
];
const containerNames = allContainers.map(( c: any) => c.name || '(unnamed)');
setContainers(containerNames);
// 挂载点
const allMounts: MountForm[] = [];
for (const c of allContainers) {
const cName = c.name || '(unnamed)';
const vms: Record<string, any>[] = Array.isArray(c.volumeMounts) ? c.volumeMounts : [];
for (const vm of vms) {
allMounts.push({
containerName: cName,
volumeName: vm.name || '',
mountPath: vm.mountPath || '',
subPath: vm.subPath || '',
readOnly: !!vm.readOnly,
});
}
}
setMounts(allMounts);
setLoading(false);
}, [manifest]);
// Volume operations
const addVolume = () => setVolumes(prev => [...prev, { name: '', type: 'emptyDir' }]);
const removeVolume = (i: number) => {
const name = volumes[i]?.name;
setVolumes(prev => prev.filter((_, idx) => idx !== i));
if (name) setMounts(prev => prev.filter(m => m.volumeName !== name));
};
const updateVolume = (i: number, patch: Partial<VolumeForm>) =>
setVolumes(prev => prev.map((v, idx) => (idx === i ? { ...v, ...patch } : v)));
// Mount operations
const addMount = () => setMounts(prev => [...prev, { containerName: containers[0] || '', volumeName: '', mountPath: '', subPath: '', readOnly: false }]);
const removeMount = (i: number) => setMounts(prev => prev.filter((_, idx) => idx !== i));
const updateMount = (i: number, patch: Partial<MountForm>) =>
setMounts(prev => prev.map((m, idx) => (idx === i ? { ...m, ...patch } : m)));
const save = async () => {
setSaving(true);
try {
const base = JSON.parse(JSON.stringify(rawManifest));
base.spec = base.spec || {};
base.spec.template = base.spec.template || {};
base.spec.template.spec = base.spec.template.spec || {};
const podSpec = base.spec.template.spec;
// Save volumes
const k8sVols = volumes.map(formToVolume).filter(Boolean);
if (k8sVols.length > 0) podSpec.volumes = k8sVols;
else delete podSpec.volumes;
// Save volumeMounts to each container
const allContainers = [...(podSpec.containers || []), ...(podSpec.initContainers || [])];
for (const c of allContainers) {
const cName = c.name || '(unnamed)';
const cMounts = mounts
.filter(m => m.containerName === cName && m.volumeName && m.mountPath)
.map(m => {
const vm: Record<string, any> = { name: m.volumeName, mountPath: m.mountPath, readOnly: m.readOnly };
if (m.subPath) vm.subPath = m.subPath;
return vm;
});
if (cMounts.length > 0) c.volumeMounts = cMounts;
else delete c.volumeMounts;
}
// Rebuild containers arrays
podSpec.containers = allContainers.filter(( c: any) => !(podSpec.initContainers || []).includes(c));
podSpec.initContainers = (podSpec.initContainers || []);
const json = JSON.stringify(base, null, 2);
await kubernetesApi.updateResourceYaml(clusterCode, namespace, 'deployments', deploymentName, json);
toast({ title: '存储配置已保存', description: `${deploymentName} 更新已提交` });
onSaved();
} catch (e: any) {
toast({ title: '保存失败', description: e?.message || String(e), variant: 'destructive' });
} finally { setSaving(false); }
};
if (loading) {
return (
<Card className="bg-slate-900 border-slate-800">
<CardContent className="p-12 text-center">
<Loader2 className="h-6 w-6 animate-spin mx-auto text-slate-500" />
<p className="text-slate-500 mt-3 text-sm">加载中...</p>
</CardContent>
</Card>
);
}
if (!manifest) {
return (
<Card className="bg-slate-900 border-slate-800">
<CardContent className="p-8 text-center text-slate-500">
未获取到 manifest 数据,请使用 YAML 编辑模式直接修改。
</CardContent>
</Card>
);
}
const volumeNames = volumes.map(v => v.name).filter(Boolean);
return (
<div className="space-y-4">
{/* ══════════ 定义数据卷 ══════════ */}
<Card className="bg-slate-900 border-slate-800">
<CardHeader className="pb-3">
<div className="flex items-center justify-between">
<CardTitle className="text-sm text-slate-200 flex items-center gap-2">
<Database className="h-4 w-4 text-emerald-400" />定义数据卷
<Badge variant="outline" className="border-slate-700 text-slate-400">{volumes.length}</Badge>
</CardTitle>
<Button size="sm" variant="outline" className="h-7 border-slate-700 text-slate-300 text-xs" onClick={addVolume}>
<Plus className="h-3 w-3 mr-1" />添加数据卷
</Button>
</div>
</CardHeader>
<CardContent className="pt-0 space-y-3">
{volumes.length === 0 ? (
<div className="text-center py-8 text-slate-500 text-sm border border-dashed border-slate-800 rounded-lg">
<Database className="h-8 w-8 mx-auto mb-2 text-slate-700" />
未配置数据卷
</div>
) : volumes.map((vol, i) => {
const vtype = VOLUME_TYPES.find(t => t.key === vol.type);
const VIcon = vtype?.icon || Folder;
return (
<div key={i} className="bg-slate-950/50 border border-slate-800 rounded-lg p-3 space-y-2.5">
{/* 卷名 + 类型 */}
<div className="flex items-center gap-2">
<VIcon className={`h-4 w-4 ${vtype?.color || 'text-slate-400'}`} />
<span className="text-[10px] text-slate-500 w-16 shrink-0">数据卷名称</span>
<Input value={vol.name} onChange={e => updateVolume(i, { name: e.target.value })}
placeholder="volume-name"
className="h-7 flex-1 bg-slate-800 border-slate-700 text-slate-300 text-xs font-mono" />
<Select value={vol.type} onValueChange={v => updateVolume(i, { type: v as VolumeForm['type'] })}>
<SelectTrigger className="h-7 w-[120px] bg-slate-800 border-slate-700 text-xs text-slate-300">
<div className="flex items-center gap-1.5">
<VIcon className="h-3 w-3" />{vtype?.label || vol.type}
</div>
</SelectTrigger>
<SelectContent>
{VOLUME_TYPES.map(t => {
const TI = t.icon;
return (
<SelectItem key={t.key} value={t.key}>
<span className="flex items-center gap-1.5 text-xs">
<TI className="h-3 w-3" />{t.label}
</span>
</SelectItem>
);
})}
</SelectContent>
</Select>
<Button size="icon" variant="ghost" className="h-7 w-7 text-red-400" onClick={() => removeVolume(i)}>
<Trash2 className="h-3.5 w-3.5" />
</Button>
</div>
{/* 类型指定字段 */}
{vol.type === 'persistentVolumeClaim' && (
<div className="flex items-center gap-2 pl-[88px]">
<Input value={vol.pvcName || ''} onChange={e => updateVolume(i, { pvcName: e.target.value })}
placeholder="PVC 名称" className="h-7 flex-1 bg-slate-800 border-slate-700 text-slate-300 text-xs font-mono" />
<label className="flex items-center gap-1.5 text-xs text-slate-400 cursor-pointer whitespace-nowrap">
<input type="checkbox" checked={!!vol.pvcReadOnly}
onChange={e => updateVolume(i, { pvcReadOnly: e.target.checked })}
className="accent-blue-500" />只读
</label>
</div>
)}
{vol.type === 'emptyDir' && (
<div className="flex items-center gap-2 pl-[88px]">
<Input value={vol.sizeLimit || ''} onChange={e => updateVolume(i, { sizeLimit: e.target.value })}
placeholder="sizeLimit (如 512Mi, 可为空)"
className="h-7 flex-1 bg-slate-800 border-slate-700 text-slate-300 text-xs font-mono" />
</div>
)}
{vol.type === 'hostPath' && (
<div className="flex items-center gap-2 pl-[88px]">
<Input value={vol.path || ''} onChange={e => updateVolume(i, { path: e.target.value })}
placeholder="主机路径 /data/app"
className="h-7 flex-1 bg-slate-800 border-slate-700 text-slate-300 text-xs font-mono" />
<select value={vol.pathType || 'Directory'} onChange={e => updateVolume(i, { pathType: e.target.value })}
className="h-7 w-28 bg-slate-800 border border-slate-700 rounded text-xs text-slate-300 px-1.5">
<option value="Directory">Directory</option>
<option value="File">File</option>
<option value="">(默认)</option>
</select>
</div>
)}
{vol.type === 'nfs' && (
<div className="flex items-center gap-2 pl-[88px]">
<Input value={vol.nfsServer || ''} onChange={e => updateVolume(i, { nfsServer: e.target.value })}
placeholder="NFS Server IP"
className="h-7 w-40 bg-slate-800 border-slate-700 text-slate-300 text-xs font-mono" />
<span className="text-slate-600 text-xs">:</span>
<Input value={vol.nfsPath || ''} onChange={e => updateVolume(i, { nfsPath: e.target.value })}
placeholder="/export/path"
className="h-7 flex-1 bg-slate-800 border-slate-700 text-slate-300 text-xs font-mono" />
<label className="flex items-center gap-1.5 text-xs text-slate-400 cursor-pointer whitespace-nowrap">
<input type="checkbox" checked={!!vol.nfsReadOnly}
onChange={e => updateVolume(i, { nfsReadOnly: e.target.checked })}
className="accent-blue-500" />只读
</label>
</div>
)}
{vol.type === 'configMap' && (
<div className="flex items-center gap-2 pl-[88px]">
<span className="text-[10px] text-slate-500 whitespace-nowrap">ConfigMap</span>
<Input value={vol.configMapName || ''} onChange={e => updateVolume(i, { configMapName: e.target.value })}
placeholder="ConfigMap 名称"
className="h-7 flex-1 bg-slate-800 border-slate-700 text-slate-300 text-xs font-mono" />
<Input value={vol.cmItems || ''} onChange={e => updateVolume(i, { cmItems: e.target.value })}
placeholder="KeyToPath (可为空)"
className="h-7 w-40 bg-slate-800 border-slate-700 text-slate-300 text-xs font-mono" />
</div>
)}
{vol.type === 'secret' && (
<div className="flex items-center gap-2 pl-[88px]">
<span className="text-[10px] text-slate-500 whitespace-nowrap">密文</span>
<Input value={vol.secretName || ''} onChange={e => updateVolume(i, { secretName: e.target.value })}
placeholder="Secret 名称"
className="h-7 flex-1 bg-slate-800 border-slate-700 text-slate-300 text-xs font-mono" />
<Input value={vol.secItems || ''} onChange={e => updateVolume(i, { secItems: e.target.value })}
placeholder="KeyToPath (可为空)"
className="h-7 w-40 bg-slate-800 border-slate-700 text-slate-300 text-xs font-mono" />
</div>
)}
</div>
);
})}
</CardContent>
</Card>
{/* ══════════ 挂载到容器 ══════════ */}
<Card className="bg-slate-900 border-slate-800">
<CardHeader className="pb-3">
<div className="flex items-center justify-between">
<CardTitle className="text-sm text-slate-200 flex items-center gap-2">
<Folder className="h-4 w-4 text-blue-400" />将数据卷挂载到容器
<Badge variant="outline" className="border-slate-700 text-slate-400">{mounts.length}</Badge>
</CardTitle>
<Button size="sm" variant="outline" className="h-7 border-slate-700 text-slate-300 text-xs" onClick={addMount}
disabled={volumeNames.length === 0 || containers.length === 0}>
<Plus className="h-3 w-3 mr-1" />添加挂载
</Button>
</div>
</CardHeader>
<CardContent className="pt-0 space-y-2">
{mounts.length === 0 ? (
<div className="text-center py-8 text-slate-500 text-sm border border-dashed border-slate-800 rounded-lg">
<Folder className="h-8 w-8 mx-auto mb-2 text-slate-700" />
{volumeNames.length === 0 ? '请先定义数据卷' : '未配置挂载点'}
</div>
) : mounts.map((m, i) => (
<div key={i} className="flex items-center gap-2 bg-slate-950/50 border border-slate-800 rounded-lg p-2.5">
{/* 容器选择 */}
<span className="text-[10px] text-slate-500 whitespace-nowrap">容器:</span>
<select value={m.containerName} onChange={e => updateMount(i, { containerName: e.target.value })}
className="h-7 bg-slate-800 border border-slate-700 rounded text-xs text-slate-300 px-1.5 min-w-[120px]">
{containers.length === 0 && <option value="">(无容器)</option>}
{containers.map(cn => <option key={cn} value={cn}>{cn}</option>)}
</select>
{/* 数据卷选择 */}
<select value={m.volumeName} onChange={e => updateMount(i, { volumeName: e.target.value })}
className="h-7 bg-slate-800 border border-slate-700 rounded text-xs text-slate-300 px-1.5 min-w-[100px]">
<option value="">选择数据卷</option>
{volumeNames.map(vn => <option key={vn} value={vn}>{vn}</option>)}
</select>
{/* 挂载路径 */}
<Input value={m.mountPath} onChange={e => updateMount(i, { mountPath: e.target.value })}
placeholder="挂载路径 /app/data"
className="h-7 flex-1 bg-slate-800 border-slate-700 text-slate-300 text-xs font-mono" />
{/* 只读/读写 */}
<div className="flex items-center gap-1 bg-slate-800 rounded-lg p-0.5 border border-slate-700">
<button onClick={() => updateMount(i, { readOnly: false })}
className={`px-2 py-0.5 rounded text-[10px] font-medium transition-all ${!m.readOnly ? 'bg-blue-500/20 text-blue-300' : 'text-slate-500'}`}>
读写
</button>
<button onClick={() => updateMount(i, { readOnly: true })}
className={`px-2 py-0.5 rounded text-[10px] font-medium transition-all ${m.readOnly ? 'bg-amber-500/20 text-amber-300' : 'text-slate-500'}`}>
只读
</button>
</div>
<Button size="icon" variant="ghost" className="h-7 w-7 text-red-400" onClick={() => removeMount(i)}>
<Trash2 className="h-3.5 w-3.5" />
</Button>
</div>
))}
</CardContent>
</Card>
{/* 操作栏 */}
<div className="flex justify-end gap-2 pt-2">
<Button variant="outline" className="border-slate-700 text-slate-400" onClick={onCancel}>取消</Button>
<Button className="bg-blue-600 hover:bg-blue-700" disabled={saving} onClick={save}>
{saving ? <Loader2 className="h-4 w-4 animate-spin mr-1" /> : <Save className="h-4 w-4 mr-1" />}保存
</Button>
</div>
</div>
);
}