Files
aiops/frontend/src/components/automation/CronJobManager.tsx
T
attacker 97c4207ff8 refactor: 标准化项目结构 frontend/ + backend/ + SQLite + run.sh
- 目录重构: app/ -> frontend/,与 backend/ 并列
- 数据库: 默认 SQLite(零配置),修复 DSN() bug
- run.sh: 一键启动前后端,支持 start/stop/restart/status
- Makefile: install/dev/build/lint/clean 快捷命令
- vite.config.ts: 配置 dev server 端口 5173 + API 代理到 8080
- config.yaml: SQLite 默认配置,开箱即用
- docs/: 完整开发文档(项目结构/API/数据库/规范/部署)
- 修复: GORM foreign key 关联声明
- 修复: go get gorm.io/driver/sqlite 依赖
2026-06-13 23:34:23 +08:00

475 lines
18 KiB
TypeScript

import { useState } 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 { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs';
import {
Dialog,
DialogContent,
DialogDescription,
DialogFooter,
DialogHeader,
DialogTitle,
} from '@/components/ui/dialog';
import {
Select,
SelectContent,
SelectItem,
SelectTrigger,
SelectValue,
} from '@/components/ui/select';
import { Textarea } from '@/components/ui/textarea';
import { Label } from '@/components/ui/label';
import {
Table,
TableBody,
TableCell,
TableHead,
TableHeader,
TableRow,
} from '@/components/ui/table';
import {
Play,
Plus,
Search,
Clock,
Pause,
RotateCw,
Edit,
Trash2,
History,
CheckCircle,
XCircle,
Loader2,
Server,
Calendar,
Terminal,
MoreHorizontal,
Eye,
Copy,
} from 'lucide-react';
import { cronJobs } from '@/mocks/data';
interface CronJob {
id: string;
name: string;
description: string;
schedule: string;
command: string;
status: 'enabled' | 'disabled';
lastRun: string;
lastStatus: 'success' | 'failed' | 'running' | 'never';
nextRun: string;
targetServers: string[];
createdAt: string;
createdBy: string;
}
const mockCronJobs: CronJob[] = [
{
id: 'cron-001',
name: '数据库备份',
description: '每日凌晨2点备份数据库',
schedule: '0 2 * * *',
command: '/scripts/backup-db.sh --type=full',
status: 'enabled',
lastRun: '2025-04-14 02:00:00',
lastStatus: 'success',
nextRun: '2025-04-15 02:00:00',
targetServers: ['db-server-01', 'db-server-02'],
createdAt: '2025-01-15',
createdBy: 'admin',
},
{
id: 'cron-002',
name: '日志清理',
description: '每周日凌晨3点清理过期日志',
schedule: '0 3 * * 0',
command: '/scripts/clean-logs.sh --days=30',
status: 'enabled',
lastRun: '2025-04-13 03:00:00',
lastStatus: 'success',
nextRun: '2025-04-20 03:00:00',
targetServers: ['all'],
createdAt: '2025-01-20',
createdBy: 'admin',
},
{
id: 'cron-003',
name: '健康检查',
description: '每5分钟执行健康检查',
schedule: '*/5 * * * *',
command: '/scripts/health-check.sh',
status: 'enabled',
lastRun: '2025-04-14 11:55:00',
lastStatus: 'running',
nextRun: '2025-04-14 12:00:00',
targetServers: ['web-server-01', 'web-server-02', 'app-server-01'],
createdAt: '2025-02-01',
createdBy: 'ops01',
},
{
id: 'cron-004',
name: '数据同步',
description: '每小时同步数据到备份服务器',
schedule: '0 * * * *',
command: '/scripts/sync-data.sh --target=backup',
status: 'disabled',
lastRun: '2025-04-14 10:00:00',
lastStatus: 'failed',
nextRun: '-',
targetServers: ['app-server-01'],
createdAt: '2025-02-15',
createdBy: 'ops02',
},
{
id: 'cron-005',
name: '生成报表',
description: '每周一上午9点生成业务报表',
schedule: '0 9 * * 1',
command: '/scripts/generate-report.sh --type=weekly',
status: 'enabled',
lastRun: '2025-04-07 09:00:00',
lastStatus: 'success',
nextRun: '2025-04-21 09:00:00',
targetServers: ['report-server'],
createdAt: '2025-03-01',
createdBy: 'admin',
},
];
const executionLogs = [
{ id: 1, jobName: '数据库备份', startTime: '2025-04-14 02:00:00', endTime: '2025-04-14 02:15:30', duration: '15m 30s', status: 'success', output: '备份完成: 15.2GB' },
{ id: 2, jobName: '健康检查', startTime: '2025-04-14 11:55:00', endTime: '2025-04-14 11:55:05', duration: '5s', status: 'success', output: '所有服务正常' },
{ id: 3, jobName: '数据同步', startTime: '2025-04-14 10:00:00', endTime: '2025-04-14 10:05:23', duration: '5m 23s', status: 'failed', output: '连接超时' },
{ id: 4, jobName: '日志清理', startTime: '2025-04-13 03:00:00', endTime: '2025-04-13 03:02:15', duration: '2m 15s', status: 'success', output: '清理完成: 2.3GB' },
];
export function CronJobManager() {
const [searchQuery, setSearchQuery] = useState('');
const [isCreateDialogOpen, setIsCreateDialogOpen] = useState(false);
const [isLogDialogOpen, setIsLogDialogOpen] = useState(false);
const [selectedJob, setSelectedJob] = useState<CronJob | null>(null);
const [newJob, setNewJob] = useState({
name: '',
description: '',
schedule: '',
command: '',
targetServers: '',
});
const filteredJobs = mockCronJobs.filter(
(job) =>
job.name.toLowerCase().includes(searchQuery.toLowerCase()) ||
job.description.toLowerCase().includes(searchQuery.toLowerCase())
);
const getStatusBadge = (status: CronJob['lastStatus']) => {
switch (status) {
case 'success':
return (
<Badge variant="outline" className="border-emerald-500/30 text-emerald-400 bg-emerald-500/10">
<CheckCircle className="h-3 w-3 mr-1" />
成功
</Badge>
);
case 'failed':
return (
<Badge variant="outline" className="border-red-500/30 text-red-400 bg-red-500/10">
<XCircle className="h-3 w-3 mr-1" />
失败
</Badge>
);
case 'running':
return (
<Badge variant="outline" className="border-blue-500/30 text-blue-400 bg-blue-500/10 animate-pulse">
<Loader2 className="h-3 w-3 mr-1 animate-spin" />
执行中
</Badge>
);
default:
return (
<Badge variant="outline" className="border-slate-500/30 text-slate-400 bg-slate-500/10">
从未执行
</Badge>
);
}
};
const parseCron = (schedule: string) => {
const patterns: Record<string, string> = {
'0 2 * * *': '每天 02:00',
'0 3 * * 0': '每周日 03:00',
'*/5 * * * *': '每 5 分钟',
'0 * * * *': '每小时',
'0 9 * * 1': '每周一 09:00',
};
return patterns[schedule] || schedule;
};
const handleCreateJob = () => {
setIsCreateDialogOpen(false);
setNewJob({ name: '', description: '', schedule: '', command: '', targetServers: '' });
};
return (
<div className="space-y-6">
{/* Header */}
<div className="flex items-center justify-between">
<div>
<h1 className="text-2xl font-bold text-slate-100">定时任务</h1>
<p className="text-sm text-slate-500 mt-1">Cron 任务管理与执行</p>
</div>
<div className="flex items-center gap-2">
<Button variant="outline" className="border-slate-700 text-slate-300" onClick={() => setIsLogDialogOpen(true)}>
<History className="h-4 w-4 mr-2" />
执行历史
</Button>
<Button className="bg-blue-600 hover:bg-blue-700" onClick={() => setIsCreateDialogOpen(true)}>
<Plus className="h-4 w-4 mr-2" />
新建任务
</Button>
</div>
</div>
{/* Stats */}
<div className="grid grid-cols-4 gap-4">
<Card className="bg-slate-800 border-slate-700">
<CardContent className="p-4">
<p className="text-slate-400 text-sm">任务总数</p>
<p className="text-2xl font-bold text-slate-100">{mockCronJobs.length}</p>
</CardContent>
</Card>
<Card className="bg-slate-800 border-slate-700">
<CardContent className="p-4">
<p className="text-slate-400 text-sm">已启用</p>
<p className="text-2xl font-bold text-emerald-400">
{mockCronJobs.filter((j) => j.status === 'enabled').length}
</p>
</CardContent>
</Card>
<Card className="bg-slate-800 border-slate-700">
<CardContent className="p-4">
<p className="text-slate-400 text-sm">执行中</p>
<p className="text-2xl font-bold text-blue-400">
{mockCronJobs.filter((j) => j.lastStatus === 'running').length}
</p>
</CardContent>
</Card>
<Card className="bg-slate-800 border-slate-700">
<CardContent className="p-4">
<p className="text-slate-400 text-sm">今日失败</p>
<p className="text-2xl font-bold text-red-400">
{mockCronJobs.filter((j) => j.lastStatus === 'failed').length}
</p>
</CardContent>
</Card>
</div>
{/* Filters */}
<div className="flex items-center gap-4">
<div className="relative flex-1 max-w-md">
<Search className="absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-slate-400" />
<Input
placeholder="搜索任务..."
value={searchQuery}
onChange={(e) => setSearchQuery(e.target.value)}
className="pl-10 bg-slate-800 border-slate-700 text-slate-100"
/>
</div>
</div>
{/* Job List */}
<div className="space-y-3">
{filteredJobs.map((job) => (
<Card key={job.id} className="bg-slate-800 border-slate-700">
<CardContent className="p-4">
<div className="flex items-start justify-between">
<div className="flex-1">
<div className="flex items-center gap-3">
<h3 className="font-medium text-slate-100">{job.name}</h3>
<Badge
variant="outline"
className={
job.status === 'enabled'
? 'border-emerald-500/30 text-emerald-400 bg-emerald-500/10'
: 'border-slate-500/30 text-slate-400 bg-slate-500/10'
}
>
{job.status === 'enabled' ? '已启用' : '已禁用'}
</Badge>
{getStatusBadge(job.lastStatus)}
</div>
<p className="text-sm text-slate-400 mt-1">{job.description}</p>
<div className="flex items-center gap-4 mt-2 text-sm">
<span className="flex items-center gap-1 text-slate-400">
<Clock className="h-3 w-3" />
{parseCron(job.schedule)}
</span>
<span className="flex items-center gap-1 text-slate-400">
<Terminal className="h-3 w-3" />
<code className="text-xs bg-slate-900 px-2 py-0.5 rounded">{job.command}</code>
</span>
</div>
<div className="flex items-center gap-4 mt-2 text-xs text-slate-500">
<span>上次执行: {job.lastRun}</span>
<span>下次执行: {job.nextRun}</span>
<span>目标: {job.targetServers.join(', ')}</span>
</div>
</div>
<div className="flex items-center gap-2">
<Button variant="outline" size="sm" className="border-emerald-600 text-emerald-400 hover:bg-emerald-600/20">
<Play className="h-4 w-4 mr-1" />
立即执行
</Button>
<Button
variant="ghost"
size="icon"
className="h-8 w-8 text-slate-400 hover:text-blue-400"
>
<Edit className="h-4 w-4" />
</Button>
<Button
variant="ghost"
size="icon"
className="h-8 w-8 text-slate-400 hover:text-red-400"
>
<Trash2 className="h-4 w-4" />
</Button>
</div>
</div>
</CardContent>
</Card>
))}
</div>
{/* Create Job Dialog */}
<Dialog open={isCreateDialogOpen} onOpenChange={setIsCreateDialogOpen}>
<DialogContent className="max-w-2xl bg-slate-900 border-slate-700 text-slate-100">
<DialogHeader>
<DialogTitle>新建定时任务</DialogTitle>
<DialogDescription className="text-slate-500">配置 Cron 定时任务</DialogDescription>
</DialogHeader>
<div className="space-y-4 py-4">
<div>
<Label className="text-slate-300">任务名称</Label>
<Input
value={newJob.name}
onChange={(e) => setNewJob({ ...newJob, name: e.target.value })}
placeholder="例如: 数据库备份"
className="bg-slate-800 border-slate-700 text-slate-100 mt-1"
/>
</div>
<div>
<Label className="text-slate-300">描述</Label>
<Textarea
value={newJob.description}
onChange={(e) => setNewJob({ ...newJob, description: e.target.value })}
placeholder="任务描述..."
className="bg-slate-800 border-slate-700 text-slate-100 mt-1"
/>
</div>
<div>
<Label className="text-slate-300">Cron 表达式</Label>
<div className="flex gap-2">
<Input
value={newJob.schedule}
onChange={(e) => setNewJob({ ...newJob, schedule: e.target.value })}
placeholder="0 2 * * *"
className="bg-slate-800 border-slate-700 text-slate-100 mt-1"
/>
<Select onValueChange={(v) => setNewJob({ ...newJob, schedule: v })}>
<SelectTrigger className="w-48 bg-slate-800 border-slate-700 text-slate-100 mt-1">
<SelectValue placeholder="快速选择" />
</SelectTrigger>
<SelectContent className="bg-slate-800 border-slate-700">
<SelectItem value="*/5 * * * *" className="text-slate-100">每 5 分钟</SelectItem>
<SelectItem value="0 * * * *" className="text-slate-100">每小时</SelectItem>
<SelectItem value="0 2 * * *" className="text-slate-100">每天 02:00</SelectItem>
<SelectItem value="0 3 * * 0" className="text-slate-100">每周日 03:00</SelectItem>
<SelectItem value="0 9 * * 1" className="text-slate-100">每周一 09:00</SelectItem>
</SelectContent>
</Select>
</div>
<p className="text-xs text-slate-500 mt-1">格式: 分 时 日 月 周</p>
</div>
<div>
<Label className="text-slate-300">执行命令</Label>
<Textarea
value={newJob.command}
onChange={(e) => setNewJob({ ...newJob, command: e.target.value })}
placeholder="/scripts/backup.sh"
className="bg-slate-800 border-slate-700 text-slate-100 mt-1 font-mono"
/>
</div>
<div>
<Label className="text-slate-300">目标服务器</Label>
<Input
value={newJob.targetServers}
onChange={(e) => setNewJob({ ...newJob, targetServers: e.target.value })}
placeholder="server1,server2 或 all"
className="bg-slate-800 border-slate-700 text-slate-100 mt-1"
/>
</div>
</div>
<DialogFooter>
<Button variant="outline" onClick={() => setIsCreateDialogOpen(false)} className="border-slate-700 text-slate-300">
取消
</Button>
<Button className="bg-blue-600 hover:bg-blue-700" onClick={handleCreateJob}>
创建任务
</Button>
</DialogFooter>
</DialogContent>
</Dialog>
{/* Execution Log Dialog */}
<Dialog open={isLogDialogOpen} onOpenChange={setIsLogDialogOpen}>
<DialogContent className="max-w-4xl bg-slate-900 border-slate-700 text-slate-100">
<DialogHeader>
<DialogTitle>执行历史</DialogTitle>
<DialogDescription className="text-slate-500">定时任务执行记录</DialogDescription>
</DialogHeader>
<div className="mt-4">
<Table>
<TableHeader>
<TableRow className="border-slate-700">
<TableHead className="text-slate-400">任务</TableHead>
<TableHead className="text-slate-400">开始时间</TableHead>
<TableHead className="text-slate-400">耗时</TableHead>
<TableHead className="text-slate-400">状态</TableHead>
<TableHead className="text-slate-400">输出</TableHead>
</TableRow>
</TableHeader>
<TableBody>
{executionLogs.map((log) => (
<TableRow key={log.id} className="border-slate-700">
<TableCell className="text-slate-200">{log.jobName}</TableCell>
<TableCell className="text-slate-400">{log.startTime}</TableCell>
<TableCell className="text-slate-400">{log.duration}</TableCell>
<TableCell>
<Badge
variant="outline"
className={
log.status === 'success'
? 'border-emerald-500/30 text-emerald-400 bg-emerald-500/10'
: 'border-red-500/30 text-red-400 bg-red-500/10'
}
>
{log.status === 'success' ? '成功' : '失败'}
</Badge>
</TableCell>
<TableCell className="text-slate-400 text-sm">{log.output}</TableCell>
</TableRow>
))}
</TableBody>
</Table>
</div>
</DialogContent>
</Dialog>
</div>
);
}