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 依赖
This commit is contained in:
attacker committed 2026-06-13 23:34:23 +08:00
1 parent 7d6674bddd
commit 97c4207ff8
132 files changed
+1572 -34

No files matched your search

@@ -0,0 +1,715 @@
import React, { useState, useEffect } from 'react';
import {
Monitor, Settings, Plus, Edit, Trash2, Copy, Eye, Download, RefreshCw,
Maximize2, Minimize2, Save, X, ChevronDown, BarChart3, LineChart, PieChart,
Activity, Cpu, Database, Server, Globe, Zap, AlertTriangle, TrendingUp,
TrendingDown, Clock, Calendar, Filter, Search, GripVertical, Move
} from 'lucide-react';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Badge } from '@/components/ui/badge';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import {
Dialog, DialogContent, DialogHeader, DialogTitle, DialogDescription, DialogFooter
} from '@/components/ui/dialog';
import {
Select, SelectContent, SelectItem, SelectTrigger, SelectValue
} from '@/components/ui/select';
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs';
import { Label } from '@/components/ui/label';
import { Switch } from '@/components/ui/switch';
import { Separator } from '@/components/ui/separator';
import { toast } from 'sonner';
import { dashboardApi } from '@/services/api';
interface Dashboard {
id: string;
name: string;
description: string;
datasource: 'prometheus' | 'zabbix' | 'skywalking' | 'custom';
datasourceUrl: string;
panels: Panel[];
createdAt: string;
updatedAt: string;
createdBy: string;
isDefault: boolean;
}
interface Panel {
id: string;
title: string;
type: 'graph' | 'stat' | 'gauge' | 'table' | 'pie' | 'heatmap' | 'text';
query: string;
datasource: string;
width: number;
height: number;
x: number;
y: number;
options: PanelOptions;
}
interface PanelOptions {
unit?: string;
min?: number;
max?: number;
thresholds?: Threshold[];
legend?: boolean;
tooltip?: boolean;
refreshInterval?: number;
}
interface Threshold {
value: number;
color: string;
name: string;
}
interface Datasource {
id: string;
name: string;
type: 'prometheus' | 'zabbix' | 'skywalking' | 'influxdb' | 'elasticsearch';
url: string;
status: 'connected' | 'disconnected' | 'error';
}
const GrafanaDashboard: React.FC = () => {
const [dashboards, setDashboards] = useState<Dashboard[]>([]);
const [datasources, setDatasources] = useState<Datasource[]>([]);
const [activeDashboard, setActiveDashboard] = useState<Dashboard | null>(null);
const [loading, setLoading] = useState(false);
const [editMode, setEditMode] = useState(false);
const [fullscreen, setFullscreen] = useState(false);
const [createOpen, setCreateOpen] = useState(false);
const [addPanelOpen, setAddPanelOpen] = useState(false);
const [datasourceOpen, setDatasourceOpen] = useState(false);
const [newDashboard, setNewDashboard] = useState({
name: '',
description: '',
datasource: 'prometheus' as const,
datasourceUrl: ''
});
const [newPanel, setNewPanel] = useState({
title: '',
type: 'graph' as const,
query: '',
width: 6,
height: 4
});
const [newDatasource, setNewDatasource] = useState({
name: '',
type: 'prometheus' as const,
url: ''
});
useEffect(() => {
fetchDashboards();
fetchDatasources();
}, []);
const fetchDashboards = async () => {
setLoading(true);
try {
const res = await dashboardApi.getDashboards();
setDashboards(res.data || []);
if (res.data?.length > 0 && !activeDashboard) {
setActiveDashboard(res.data[0]);
}
} catch (error) {
toast.error('获取仪表盘失败');
} finally {
setLoading(false);
}
};
const fetchDatasources = async () => {
try {
const res = await dashboardApi.getDatasources();
setDatasources(res.data || []);
} catch (error) {
toast.error('获取数据源失败');
}
};
const handleCreateDashboard = async () => {
if (!newDashboard.name) {
toast.error('请输入仪表盘名称');
return;
}
try {
await dashboardApi.createDashboard({
...newDashboard,
panels: []
});
toast.success('仪表盘创建成功');
setCreateOpen(false);
setNewDashboard({ name: '', description: '', datasource: 'prometheus', datasourceUrl: '' });
fetchDashboards();
} catch (error) {
toast.error('创建失败');
}
};
const handleAddPanel = async () => {
if (!newPanel.title || !newPanel.query || !activeDashboard) {
toast.error('请填写完整信息');
return;
}
try {
const panel: Panel = {
id: Date.now().toString(),
...newPanel,
datasource: activeDashboard.datasource,
x: 0,
y: 0,
options: {
unit: '',
legend: true,
tooltip: true,
refreshInterval: 30
}
};
await dashboardApi.updateDashboard(activeDashboard.id, {
...activeDashboard,
panels: [...activeDashboard.panels, panel]
});
toast.success('面板添加成功');
setAddPanelOpen(false);
setNewPanel({ title: '', type: 'graph', query: '', width: 6, height: 4 });
fetchDashboards();
} catch (error) {
toast.error('添加失败');
}
};
const handleAddDatasource = async () => {
if (!newDatasource.name || !newDatasource.url) {
toast.error('请填写完整信息');
return;
}
try {
await dashboardApi.createDatasource(newDatasource);
toast.success('数据源添加成功');
setDatasourceOpen(false);
setNewDatasource({ name: '', type: 'prometheus', url: '' });
fetchDatasources();
} catch (error) {
toast.error('添加失败');
}
};
const handleDeleteDashboard = async (id: string) => {
if (!confirm('确定删除此仪表盘吗?')) return;
try {
await dashboardApi.deleteDashboard(id);
toast.success('删除成功');
if (activeDashboard?.id === id) {
setActiveDashboard(null);
}
fetchDashboards();
} catch (error) {
toast.error('删除失败');
}
};
const getDatasourceIcon = (type: string) => {
switch (type) {
case 'prometheus': return <Activity className="w-4 h-4" />;
case 'zabbix': return <Server className="w-4 h-4" />;
case 'skywalking': return <Globe className="w-4 h-4" />;
case 'influxdb': return <Database className="w-4 h-4" />;
default: return <Database className="w-4 h-4" />;
}
};
const getPanelIcon = (type: string) => {
switch (type) {
case 'graph': return <LineChart className="w-4 h-4" />;
case 'stat': return <Activity className="w-4 h-4" />;
case 'gauge': return <Cpu className="w-4 h-4" />;
case 'pie': return <PieChart className="w-4 h-4" />;
case 'table': return <BarChart3 className="w-4 h-4" />;
default: return <BarChart3 className="w-4 h-4" />;
}
};
const getDatasourceStatusBadge = (status: string) => {
switch (status) {
case 'connected':
return <Badge variant="default" className="bg-green-500">已连接</Badge>;
case 'disconnected':
return <Badge variant="secondary">已断开</Badge>;
case 'error':
return <Badge variant="destructive">错误</Badge>;
default:
return <Badge variant="outline">未知</Badge>;
}
};
// 模拟图表数据
const generateChartData = (panel: Panel) => {
const dataPoints = 24;
const data = [];
for (let i = 0; i < dataPoints; i++) {
data.push({
time: new Date(Date.now() - (dataPoints - i) * 3600000).toLocaleTimeString(),
value: Math.random() * 100
});
}
return data;
};
// 渲染面板内容
const renderPanelContent = (panel: Panel) => {
const data = generateChartData(panel);
switch (panel.type) {
case 'stat':
return (
<div className="flex flex-col items-center justify-center h-full">
<span className="text-4xl font-bold text-blue-500">{Math.floor(Math.random() * 1000)}</span>
<span className="text-sm text-muted-foreground mt-2">{panel.options?.unit || 'requests/s'}</span>
<div className="flex items-center gap-1 mt-2 text-green-500 text-sm">
<TrendingUp className="w-4 h-4" />
<span>+12.5%</span>
</div>
</div>
);
case 'gauge':
return (
<div className="flex flex-col items-center justify-center h-full">
<div className="relative w-24 h-24">
<svg className="w-full h-full" viewBox="0 0 100 100">
<circle cx="50" cy="50" r="40" fill="none" stroke="#e5e7eb" strokeWidth="10" />
<circle
cx="50"
cy="50"
r="40"
fill="none"
stroke="#3b82f6"
strokeWidth="10"
strokeDasharray={`${Math.random() * 251} 251`}
transform="rotate(-90 50 50)"
/>
</svg>
<div className="absolute inset-0 flex items-center justify-center">
<span className="text-xl font-bold">{Math.floor(Math.random() * 100)}%</span>
</div>
</div>
<span className="text-sm text-muted-foreground mt-2">CPU使用率</span>
</div>
);
case 'graph':
default:
return (
<div className="h-full flex flex-col">
<div className="flex-1 flex items-end gap-1 px-2">
{data.map((d, i) => (
<div
key={i}
className="flex-1 bg-blue-500 rounded-t"
style={{ height: `${d.value}%`, opacity: 0.3 + (i / data.length) * 0.7 }}
/>
))}
</div>
<div className="flex justify-between text-xs text-muted-foreground px-2 pt-2">
<span>{data[0].time}</span>
<span>{data[data.length - 1].time}</span>
</div>
</div>
);
}
};
return (
<div className={`space-y-4 ${fullscreen ? 'fixed inset-0 z-50 bg-background p-4' : ''}`}>
{/* 顶部工具栏 */}
<div className="flex items-center justify-between">
<div className="flex items-center gap-4">
<Select
value={activeDashboard?.id}
onValueChange={(id) => {
const dashboard = dashboards.find(d => d.id === id);
if (dashboard) setActiveDashboard(dashboard);
}}
>
<SelectTrigger className="w-[250px]">
<SelectValue placeholder="选择仪表盘" />
</SelectTrigger>
<SelectContent>
{dashboards.map(d => (
<SelectItem key={d.id} value={d.id}>
<div className="flex items-center gap-2">
{getDatasourceIcon(d.datasource)}
{d.name}
{d.isDefault && <Badge variant="outline" className="text-xs">默认</Badge>}
</div>
</SelectItem>
))}
</SelectContent>
</Select>
{activeDashboard && (
<div className="flex items-center gap-2 text-sm text-muted-foreground">
<Clock className="w-4 h-4" />
<span>更新于 {activeDashboard.updatedAt}</span>
</div>
)}
</div>
<div className="flex items-center gap-2">
<Button variant="outline" size="sm" onClick={fetchDashboards}>
<RefreshCw className="w-4 h-4 mr-2" />
刷新
</Button>
{activeDashboard && (
<>
<Button
variant={editMode ? 'default' : 'outline'}
size="sm"
onClick={() => setEditMode(!editMode)}
>
<Edit className="w-4 h-4 mr-2" />
{editMode ? '完成' : '编辑'}
</Button>
<Button variant="outline" size="sm" onClick={() => setAddPanelOpen(true)}>
<Plus className="w-4 h-4 mr-2" />
添加面板
</Button>
</>
)}
<Button variant="outline" size="sm" onClick={() => setFullscreen(!fullscreen)}>
{fullscreen ? <Minimize2 className="w-4 h-4" /> : <Maximize2 className="w-4 h-4" />}
</Button>
<Button variant="outline" size="sm" onClick={() => setDatasourceOpen(true)}>
<Database className="w-4 h-4 mr-2" />
数据源
</Button>
<Button size="sm" onClick={() => setCreateOpen(true)}>
<Plus className="w-4 h-4 mr-2" />
新建仪表盘
</Button>
</div>
</div>
{/* 仪表盘内容 */}
{activeDashboard ? (
<div className="space-y-4">
{/* 仪表盘信息 */}
<div className="flex items-center justify-between">
<div>
<h2 className="text-xl font-bold">{activeDashboard.name}</h2>
<p className="text-sm text-muted-foreground">{activeDashboard.description}</p>
</div>
<div className="flex items-center gap-2">
<Badge variant="outline" className="gap-1">
{getDatasourceIcon(activeDashboard.datasource)}
{activeDashboard.datasource}
</Badge>
</div>
</div>
{/* 面板网格 */}
<div className="grid grid-cols-12 gap-4">
{activeDashboard.panels.map((panel) => (
<Card
key={panel.id}
className={`col-span-${panel.width} ${editMode ? 'ring-2 ring-blue-500 ring-offset-2' : ''}`}
style={{ gridColumn: `span ${panel.width}`, minHeight: `${panel.height * 80}px` }}
>
<CardHeader className="py-3 px-4">
<div className="flex items-center justify-between">
<CardTitle className="text-sm font-medium flex items-center gap-2">
{getPanelIcon(panel.type)}
{panel.title}
</CardTitle>
{editMode && (
<div className="flex items-center gap-1">
<Button variant="ghost" size="sm" className="h-6 w-6 p-0">
<GripVertical className="w-4 h-4" />
</Button>
<Button variant="ghost" size="sm" className="h-6 w-6 p-0">
<Edit className="w-4 h-4" />
</Button>
<Button variant="ghost" size="sm" className="h-6 w-6 p-0 text-red-500">
<Trash2 className="w-4 h-4" />
</Button>
</div>
)}
</div>
</CardHeader>
<CardContent className="p-4 pt-0 flex-1">
{renderPanelContent(panel)}
</CardContent>
</Card>
))}
{activeDashboard.panels.length === 0 && (
<div className="col-span-12 py-16 text-center text-muted-foreground">
<BarChart3 className="w-16 h-16 mx-auto mb-4 opacity-50" />
<p>暂无面板,点击"添加面板"开始创建</p>
</div>
)}
</div>
</div>
) : (
<div className="py-16 text-center text-muted-foreground">
<Monitor className="w-16 h-16 mx-auto mb-4 opacity-50" />
<p>请选择一个仪表盘或创建新的仪表盘</p>
<Button className="mt-4" onClick={() => setCreateOpen(true)}>
<Plus className="w-4 h-4 mr-2" />
新建仪表盘
</Button>
</div>
)}
{/* 新建仪表盘对话框 */}
<Dialog open={createOpen} onOpenChange={setCreateOpen}>
<DialogContent>
<DialogHeader>
<DialogTitle>新建仪表盘</DialogTitle>
<DialogDescription>创建一个新的监控仪表盘</DialogDescription>
</DialogHeader>
<div className="space-y-4">
<div>
<Label>名称</Label>
<Input
value={newDashboard.name}
onChange={(e) => setNewDashboard({ ...newDashboard, name: e.target.value })}
placeholder="仪表盘名称"
/>
</div>
<div>
<Label>描述</Label>
<Input
value={newDashboard.description}
onChange={(e) => setNewDashboard({ ...newDashboard, description: e.target.value })}
placeholder="仪表盘描述"
/>
</div>
<div>
<Label>数据源类型</Label>
<Select
value={newDashboard.datasource}
onValueChange={(v) => setNewDashboard({ ...newDashboard, datasource: v as any })}
>
<SelectTrigger>
<SelectValue />
</SelectTrigger>
<SelectContent>
<SelectItem value="prometheus">Prometheus</SelectItem>
<SelectItem value="zabbix">Zabbix</SelectItem>
<SelectItem value="skywalking">SkyWalking</SelectItem>
<SelectItem value="custom">自定义</SelectItem>
</SelectContent>
</Select>
</div>
<div>
<Label>数据源地址</Label>
<Input
value={newDashboard.datasourceUrl}
onChange={(e) => setNewDashboard({ ...newDashboard, datasourceUrl: e.target.value })}
placeholder="http://localhost:9090"
/>
</div>
</div>
<DialogFooter>
<Button variant="outline" onClick={() => setCreateOpen(false)}>取消</Button>
<Button onClick={handleCreateDashboard}>
<Save className="w-4 h-4 mr-2" />
创建
</Button>
</DialogFooter>
</DialogContent>
</Dialog>
{/* 添加面板对话框 */}
<Dialog open={addPanelOpen} onOpenChange={setAddPanelOpen}>
<DialogContent>
<DialogHeader>
<DialogTitle>添加面板</DialogTitle>
<DialogDescription>添加一个新的监控面板</DialogDescription>
</DialogHeader>
<div className="space-y-4">
<div>
<Label>标题</Label>
<Input
value={newPanel.title}
onChange={(e) => setNewPanel({ ...newPanel, title: e.target.value })}
placeholder="面板标题"
/>
</div>
<div>
<Label>类型</Label>
<Select
value={newPanel.type}
onValueChange={(v) => setNewPanel({ ...newPanel, type: v as any })}
>
<SelectTrigger>
<SelectValue />
</SelectTrigger>
<SelectContent>
<SelectItem value="graph">折线图</SelectItem>
<SelectItem value="stat">统计值</SelectItem>
<SelectItem value="gauge">仪表盘</SelectItem>
<SelectItem value="pie">饼图</SelectItem>
<SelectItem value="table">表格</SelectItem>
<SelectItem value="heatmap">热力图</SelectItem>
</SelectContent>
</Select>
</div>
<div>
<Label>查询语句</Label>
<textarea
value={newPanel.query}
onChange={(e) => setNewPanel({ ...newPanel, query: e.target.value })}
placeholder={newPanel.type === 'graph' ? 'sum(rate(http_requests_total[5m]))' : 'up'}
className="w-full min-h-[100px] p-2 border rounded-md font-mono text-sm"
/>
</div>
<div className="grid grid-cols-2 gap-4">
<div>
<Label>宽度 (列)</Label>
<Select
value={newPanel.width.toString()}
onValueChange={(v) => setNewPanel({ ...newPanel, width: parseInt(v) })}
>
<SelectTrigger>
<SelectValue />
</SelectTrigger>
<SelectContent>
<SelectItem value="3">3列 (25%)</SelectItem>
<SelectItem value="4">4列 (33%)</SelectItem>
<SelectItem value="6">6列 (50%)</SelectItem>
<SelectItem value="8">8列 (66%)</SelectItem>
<SelectItem value="12">12列 (100%)</SelectItem>
</SelectContent>
</Select>
</div>
<div>
<Label>高度 (行)</Label>
<Select
value={newPanel.height.toString()}
onValueChange={(v) => setNewPanel({ ...newPanel, height: parseInt(v) })}
>
<SelectTrigger>
<SelectValue />
</SelectTrigger>
<SelectContent>
<SelectItem value="3">3行 (短)</SelectItem>
<SelectItem value="4">4行 (中)</SelectItem>
<SelectItem value="6">6行 (长)</SelectItem>
<SelectItem value="8">8行 (超长)</SelectItem>
</SelectContent>
</Select>
</div>
</div>
</div>
<DialogFooter>
<Button variant="outline" onClick={() => setAddPanelOpen(false)}>取消</Button>
<Button onClick={handleAddPanel}>
<Plus className="w-4 h-4 mr-2" />
添加
</Button>
</DialogFooter>
</DialogContent>
</Dialog>
{/* 数据源管理对话框 */}
<Dialog open={datasourceOpen} onOpenChange={setDatasourceOpen}>
<DialogContent className="max-w-3xl">
<DialogHeader>
<DialogTitle>数据源管理</DialogTitle>
<DialogDescription>管理监控数据源配置</DialogDescription>
</DialogHeader>
<Tabs defaultValue="list">
<TabsList className="grid w-full grid-cols-2">
<TabsTrigger value="list">数据源列表</TabsTrigger>
<TabsTrigger value="add">添加数据源</TabsTrigger>
</TabsList>
<TabsContent value="list" className="space-y-4">
<div className="grid grid-cols-1 gap-4">
{datasources.map((ds) => (
<Card key={ds.id}>
<CardContent className="p-4">
<div className="flex items-center justify-between">
<div className="flex items-center gap-3">
{getDatasourceIcon(ds.type)}
<div>
<p className="font-medium">{ds.name}</p>
<p className="text-sm text-muted-foreground">{ds.url}</p>
</div>
</div>
<div className="flex items-center gap-2">
{getDatasourceStatusBadge(ds.status)}
<Button variant="ghost" size="sm">
<Settings className="w-4 h-4" />
</Button>
<Button variant="ghost" size="sm" className="text-red-500">
<Trash2 className="w-4 h-4" />
</Button>
</div>
</div>
</CardContent>
</Card>
))}
</div>
</TabsContent>
<TabsContent value="add" className="space-y-4">
<div>
<Label>名称</Label>
<Input
value={newDatasource.name}
onChange={(e) => setNewDatasource({ ...newDatasource, name: e.target.value })}
placeholder="数据源名称"
/>
</div>
<div>
<Label>类型</Label>
<Select
value={newDatasource.type}
onValueChange={(v) => setNewDatasource({ ...newDatasource, type: v as any })}
>
<SelectTrigger>
<SelectValue />
</SelectTrigger>
<SelectContent>
<SelectItem value="prometheus">Prometheus</SelectItem>
<SelectItem value="zabbix">Zabbix</SelectItem>
<SelectItem value="skywalking">SkyWalking</SelectItem>
<SelectItem value="influxdb">InfluxDB</SelectItem>
<SelectItem value="elasticsearch">Elasticsearch</SelectItem>
</SelectContent>
</Select>
</div>
<div>
<Label>地址</Label>
<Input
value={newDatasource.url}
onChange={(e) => setNewDatasource({ ...newDatasource, url: e.target.value })}
placeholder="http://localhost:9090"
/>
</div>
<Button onClick={handleAddDatasource} className="w-full">
<Plus className="w-4 h-4 mr-2" />
添加数据源
</Button>
</TabsContent>
</Tabs>
</DialogContent>
</Dialog>
</div>
);
};
export default GrafanaDashboard;