Files
upload/templates/monitor.html
T
zzy 84f8516c37 feat(upload): 分片断点续传 + 前端静态资源去 CDN 化
1) 分片上传(routes/chunked.py)
   - POST /api/upload/init  建会话,校验表单/字段/扩展名/体积
   - POST /api/upload/chunk 单片上传,幂等可重传,http body 直写磁盘
   - GET  /api/upload/status 查询已收分片
   - POST /api/upload/complete 按序合并 + sha256 校验 + 清理分片
   - /api/submit 新增 field fileTokens 挂载已上传文件(零拷贝 os.replace)
   - 过期会话(24h)由定时任务清理

2) 弱网下的样式可靠性
   - Tailwind Play CDN / GSAP 改为本地自托管(static/js/vendor/)
   - vendor 资源 1 年 immutable 缓存,自家 css/js 1 小时
   - CSS link 失败自动带 ?r= 重试一次
   - status 页加关键内联样式兜底,极端情况下仍可读

3) 大文件落盘沿用流式写入(无 400MB 内存峰值)
2026-11-13 12:06:32 +08:00

1099 lines
44 KiB
HTML
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
<!DOCTYPE html>
<html lang="zh-CN" class="light">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
<title>系统监控</title>
<!-- Tailwind CSS -->
<script src="/static/js/vendor/tailwind-play.js"></script>
<script>
tailwind.config = {
darkMode: 'class',
theme: {
extend: {
colors: {
neutral: {
50: '#fafafa', 100: '#f5f5f5', 200: '#e5e5e5', 300: '#d4d4d4',
400: '#a3a3a3', 500: '#737373', 600: '#525252', 700: '#404040',
800: '#262626', 900: '#171717',
}
}
}
}
}
</script>
<!-- ECharts -->
<script src="/static/js/echart.js"></script>
<!-- GSAP -->
<script src="/static/js/vendor/gsap.min.js"></script>
<script src="/static/js/particles.js"></script>
<link rel="stylesheet" href="/static/css/toast.css" onerror="this.onerror=null;this.href='/static/css/toast.css?r='+Date.now()">
<script src="/static/js/toast.js"></script>
<link rel="stylesheet" href="/static/css/basic.css" onerror="this.onerror=null;this.href='/static/css/basic.css?r='+Date.now()">
<link rel="stylesheet" href="/static/css/common.css" onerror="this.onerror=null;this.href='/static/css/common.css?r='+Date.now()">
<script src="/static/js/common.js"></script>
<style>
/* ── monitor 页面专属样式 ── */
/* ===== Metric Cards ===== */
.metric-card {
background: var(--glass-bg);
backdrop-filter: blur(20px);
-webkit-backdrop-filter: blur(20px);
border: 1px solid var(--glass-border);
border-radius: 20px;
padding: 20px;
/* 只过渡 box-shadow 和 background,不包含 transform/opacity
避免与 GSAP 入场动画冲突 */
transition: box-shadow 0.4s cubic-bezier(0.2,0,0,1),
background 0.4s cubic-bezier(0.2,0,0,1);
}
.metric-card:hover {
transform: translateY(-3px);
box-shadow: 0 16px 32px -12px var(--shadow-color);
background: var(--glass-hover);
}
/* ===== Progress Bar ===== */
.progress-track {
height: 6px;
border-radius: 3px;
background: var(--border-color);
overflow: hidden;
margin-top: 8px;
}
.progress-fill {
height: 100%;
border-radius: 3px;
transition: width 0.6s ease;
}
.progress-green { background: linear-gradient(90deg, #4ade80, #22d3ee); }
.progress-yellow { background: linear-gradient(90deg, #fbbf24, #f97316); }
.progress-red { background: linear-gradient(90deg, #f87171, #ec4899); }
.progress-blue { background: linear-gradient(90deg, #60a5fa, #818cf8); }
/* ===== Status Dot ===== */
.status-dot {
width: 8px; height: 8px;
border-radius: 50%;
background: #4ade80;
animation: pulse-green 2s infinite;
}
@keyframes pulse-green {
0%, 100% { box-shadow: 0 0 0 0 rgba(74,222,128,0.4); }
50% { box-shadow: 0 0 0 6px rgba(74,222,128,0); }
}
/* ===== Chart Containers ===== */
.chart-card {
background: var(--glass-bg);
border: 1px solid var(--glass-border);
border-radius: 20px;
padding: 20px;
}
.chart-box {
height: 200px;
}
@media (min-width: 640px) {
.chart-box { height: 240px; }
}
@media (min-width: 1024px) {
.chart-box { height: 220px; }
}
/* ===== Granularity Buttons(模仿 status 页面)===== */
.granularity-btn {
background: var(--bg-secondary);
color: var(--text-secondary);
border: 1px solid var(--border-color);
padding: 6px 12px;
border-radius: 8px;
font-size: 12px;
font-weight: 500;
cursor: pointer;
transition: all 0.2s;
}
.granularity-btn:hover {
background: var(--bg-primary);
border-color: var(--text-muted);
transform: translateY(-1px);
}
.granularity-btn.active {
background: var(--accent-bg);
color: var(--accent-text);
border-color: var(--accent-bg);
box-shadow: 0 4px 12px rgba(0,0,0,0.15);
}
/* ===== Monitor Modal(与通用 modal 结构不同,保留)===== */
.modal-overlay {
position: fixed; inset: 0;
background: rgba(0,0,0,0.5);
backdrop-filter: blur(4px);
z-index: 1000;
display: flex; align-items: center; justify-content: center;
opacity: 0; pointer-events: none;
transition: opacity 0.3s;
}
.modal-overlay.open { opacity: 1; pointer-events: auto; }
.modal-box {
background: var(--bg-secondary);
border: 1px solid var(--border-color);
border-radius: 20px;
padding: 32px;
width: 420px;
max-width: 90vw;
transform: scale(0.92);
transition: transform 0.3s;
}
.modal-overlay.open .modal-box { transform: scale(1); }
/* ===== Big Number ===== */
.big-num {
font-size: 28px;
font-weight: 700;
font-variant-numeric: tabular-nums;
letter-spacing: -0.5px;
transition: color 0.3s;
}
/* ===== Inline stat items ===== */
.inline-stat {
display: flex; align-items: center; gap: 8px;
padding: 10px 16px;
border-radius: 12px;
background: var(--bg-secondary);
border: 1px solid var(--border-color);
}
.section-title {
font-size: 13px;
font-weight: 600;
letter-spacing: 0.08em;
text-transform: uppercase;
color: var(--text-muted);
}
input[type="datetime-local"] {
background: var(--input-bg);
border: 1px solid var(--input-border);
color: var(--input-text);
border-radius: 10px;
padding: 8px 12px;
font-size: 14px;
width: 100%;
outline: none;
transition: border-color 0.2s;
}
input[type="datetime-local"]:focus { border-color: var(--border-focus); }
.loading-spin {
width: 20px; height: 20px;
border: 2px solid var(--border-color);
border-top-color: var(--text-primary);
border-radius: 50%;
animation: spin 0.8s linear infinite;
display: inline-block;
}
</style>
</head>
<body>
<!-- Scroll Progress Bar -->
<div id="scrollProgress" class="fixed top-0 left-0 h-0.5 z-50 transition-all duration-150" style="width:0%"></div>
<!-- Navbar -->
<header class="glass sticky top-0 z-40 px-4 sm:px-6 py-4 sm:py-5 theme-transition border-b">
<div class="max-w-7xl mx-auto flex items-center justify-between">
<!-- 左侧:面包屑 -->
<div class="flex items-center gap-2">
<a href="/admin" class="nav-link flex items-center gap-1.5">
<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none"
stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
<rect x="3" y="3" width="7" height="7"/><rect x="14" y="3" width="7" height="7"/>
<rect x="14" y="14" width="7" height="7"/><rect x="3" y="14" width="7" height="7"/>
</svg>
<span class="hidden sm:inline text-sm">管理后台</span>
</a>
<svg xmlns="http://www.w3.org/2000/svg" width="13" height="13" viewBox="0 0 24 24" fill="none"
stroke="currentColor" stroke-width="2" style="color:var(--text-muted);opacity:0.4">
<path d="m9 18 6-6-6-6"/>
</svg>
<span class="text-sm font-medium" style="color:var(--text-primary)">系统监控</span>
</div>
<!-- 右侧 -->
<div class="flex items-center gap-2 sm:gap-3">
<!-- Live dot -->
<div class="flex items-center gap-2 text-sm" style="color:var(--text-muted)">
<div class="status-dot"></div>
<span id="liveLabel" class="hidden sm:inline">实时</span>
</div>
<!-- 返回 -->
<a href="/admin" class="btn btn-secondary px-4 py-2.5 rounded-full text-xs sm:text-sm font-medium tracking-wide flex items-center gap-2">
<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
<path d="M19 12H5M12 19l-7-7 7-7"/>
</svg>
<span class="hidden sm:inline">返回</span>
</a>
</div>
</div>
</header>
<div class="max-w-7xl mx-auto px-4 sm:px-6 py-8 space-y-8">
<!-- ===== Section 1: 实时指标 ===== -->
<section>
<div class="flex items-center justify-between mb-4">
<div class="flex items-center gap-3">
<span class="section-title">实时数据</span>
<span class="text-xs px-2 py-0.5 rounded-full" style="background:var(--success-bg);color:var(--success-text)">每秒刷新 · 5s均值</span>
</div>
<span id="lastUpdateTime" class="text-xs" style="color:var(--text-muted)">--</span>
</div>
<!-- 主要指标卡片 (4列) -->
<div class="grid grid-cols-2 lg:grid-cols-4 gap-4">
<!-- CPU -->
<div class="metric-card">
<div class="flex items-center justify-between mb-2">
<span class="text-xs font-medium" style="color:var(--text-muted)">进程 CPU</span>
<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none"
stroke="currentColor" stroke-width="2" style="color:var(--text-muted)">
<rect x="4" y="4" width="16" height="16" rx="2"/><rect x="9" y="9" width="6" height="6"/>
<path d="M15 2v2M9 2v2M2 15h2M2 9h2M22 15h-2M22 9h-2M15 22v-2M9 22v-2"/>
</svg>
</div>
<div class="big-num" id="cpuValue">--</div>
<div class="text-xs mt-1" style="color:var(--text-muted)">Python 进程占用</div>
<div class="progress-track">
<div class="progress-fill progress-blue" id="cpuBar" style="width:0%"></div>
</div>
</div>
<!-- 内存 -->
<div class="metric-card">
<div class="flex items-center justify-between mb-2">
<span class="text-xs font-medium" style="color:var(--text-muted)">进程内存</span>
<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none"
stroke="currentColor" stroke-width="2" style="color:var(--text-muted)">
<path d="M6 19v-3"/><path d="M10 19v-3"/><path d="M14 19v-3"/><path d="M18 19v-3"/>
<rect x="2" y="9" width="20" height="7" rx="1"/>
<path d="M2 12h20"/>
</svg>
</div>
<div class="big-num" id="memValue">--</div>
<div class="text-xs mt-1" style="color:var(--text-muted)" id="memDetail">RSS 内存占用</div>
<div class="progress-track">
<div class="progress-fill progress-green" id="memBar" style="width:0%"></div>
</div>
</div>
<!-- 磁盘 IO -->
<div class="metric-card">
<div class="flex items-center justify-between mb-2">
<span class="text-xs font-medium" style="color:var(--text-muted)">磁盘 IO(进程)</span>
<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none"
stroke="currentColor" stroke-width="2" style="color:var(--text-muted)">
<ellipse cx="12" cy="5" rx="9" ry="3"/><path d="M21 12c0 1.66-4 3-9 3s-9-1.34-9-3"/>
<path d="M3 5v14c0 1.66 4 3 9 3s9-1.34 9-3V5"/>
</svg>
</div>
<div class="big-num" id="diskReadValue">--</div>
<div class="text-xs mt-1" style="color:var(--text-muted)">读取速率</div>
<div class="flex items-center gap-2 mt-2">
<span class="text-xs px-2 py-0.5 rounded-md" style="background:var(--bg-primary);color:var(--text-muted);border:1px solid var(--border-color)">
写入: <span id="diskWriteValue">--</span>
</span>
</div>
</div>
<!-- 网络 -->
<div class="metric-card">
<div class="flex items-center justify-between mb-2">
<span class="text-xs font-medium" style="color:var(--text-muted)">网络速率</span>
<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none"
stroke="currentColor" stroke-width="2" style="color:var(--text-muted)">
<path d="M12 2L2 7l10 5 10-5-10-5zM2 17l10 5 10-5M2 12l10 5 10-5"/>
</svg>
</div>
<div class="space-y-2">
<div class="flex items-center justify-between">
<span class="text-xs" style="color:var(--success-text)">↑ 上传</span>
<span class="text-sm font-semibold" id="netSent">--</span>
</div>
<div class="flex items-center justify-between">
<span class="text-xs" style="color:var(--info-text)">↓ 下载</span>
<span class="text-sm font-semibold" id="netRecv">--</span>
</div>
</div>
<div class="mt-2 pt-2" style="border-top:1px solid var(--border-color)">
<div class="flex items-center justify-between text-xs" style="color:var(--text-muted)">
<span>单位: KB/s</span>
</div>
</div>
</div>
</div>
<!-- 活跃请求 & 在线用户 -->
<div class="flex flex-wrap gap-3 mt-4">
<div class="inline-stat">
<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none"
stroke="currentColor" stroke-width="2" style="color:var(--warning-text)">
<polyline points="22 12 18 12 15 21 9 3 6 12 2 12"/>
</svg>
<span class="text-sm" style="color:var(--text-muted)">活跃请求</span>
<span class="text-sm font-bold" id="activeReqs">--</span>
</div>
<div class="inline-stat">
<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none"
stroke="currentColor" stroke-width="2" style="color:var(--info-text)">
<path d="M17 21v-2a4 4 0 0 0-4-4H5a4 4 0 0 0-4 4v2"/>
<circle cx="9" cy="7" r="4"/>
<path d="M23 21v-2a4 4 0 0 0-3-3.87"/>
<path d="M16 3.13a4 4 0 0 1 0 7.75"/>
</svg>
<span class="text-sm" style="color:var(--text-muted)">在线用户</span>
<span class="text-sm font-bold" id="onlineUsers">--</span>
</div>
<div class="inline-stat ml-auto">
<span class="text-xs" style="color:var(--text-muted)">刷新间隔</span>
<span class="text-xs font-semibold">1s</span>
</div>
</div>
</section>
<!-- ===== Section 2: 历史趋势 ===== -->
<section>
<!-- 标题行 -->
<div class="flex flex-wrap items-center justify-between gap-3 mb-3">
<span class="section-title">历史趋势</span>
<div class="flex items-center gap-2 flex-wrap">
<!-- 刷新 -->
<button onclick="loadHistory()" class="btn btn-secondary rounded-xl px-3 py-2 text-sm flex items-center gap-2">
<svg xmlns="http://www.w3.org/2000/svg" width="14" height="14" viewBox="0 0 24 24" fill="none"
stroke="currentColor" stroke-width="2"><path d="M21 12a9 9 0 1 1-9-9c2.52 0 4.93 1 6.74 2.74L21 8"/>
<path d="M21 3v5h-5"/></svg>
刷新
</button>
<!-- 清理数据 -->
<button onclick="openCleanupModal()" class="btn btn-danger rounded-xl px-3 py-2 text-sm flex items-center gap-2">
<svg xmlns="http://www.w3.org/2000/svg" width="14" height="14" viewBox="0 0 24 24" fill="none"
stroke="currentColor" stroke-width="2">
<polyline points="3 6 5 6 21 6"/>
<path d="M19 6l-1 14a2 2 0 0 1-2 2H8a2 2 0 0 1-2-2L5 6"/>
<path d="M10 11v6M14 11v6"/>
<path d="M9 6V4h6v2"/>
</svg>
清理历史数据
</button>
</div>
</div>
<!-- 粒度选择器面板(模仿 status 页面) -->
<div class="glass rounded-2xl p-4 flex flex-wrap items-center gap-4 mb-4">
<span class="text-sm font-medium" style="color:var(--text-secondary)">时间范围:</span>
<div class="flex flex-wrap gap-2" id="granularityBtns">
<button class="granularity-btn active" data-gran="1h" onclick="selectGranularity(this)">1 小时</button>
<button class="granularity-btn" data-gran="6h" onclick="selectGranularity(this)">6 小时</button>
<button class="granularity-btn" data-gran="24h" onclick="selectGranularity(this)">24 小时</button>
<button class="granularity-btn" data-gran="7d" onclick="selectGranularity(this)">7 天</button>
<button class="granularity-btn" data-gran="30d" onclick="selectGranularity(this)">30 天</button>
</div>
</div>
<!-- 图表加载状态 -->
<div id="chartLoading" class="flex items-center justify-center py-20 gap-3" style="color:var(--text-muted)">
<div class="loading-spin"></div>
<span class="text-sm">加载图表数据...</span>
</div>
<!-- 图表区域 -->
<div id="chartArea" class="hidden">
<!-- 系统指标:桌面 2 列,移动 1 列 -->
<div class="grid grid-cols-1 lg:grid-cols-2 gap-4 mb-4">
<!-- CPU & 内存 -->
<div class="chart-card">
<div class="flex items-center justify-between mb-3">
<div>
<span class="text-sm font-semibold">CPU / 内存</span>
<span class="text-xs ml-2" style="color:var(--text-muted)">进程自身</span>
</div>
<div class="flex items-center gap-3 text-xs" style="color:var(--text-muted)">
<span class="flex items-center gap-1"><span class="w-3 h-0.5 inline-block rounded" style="background:#60a5fa"></span>CPU %</span>
<span class="flex items-center gap-1"><span class="w-3 h-0.5 inline-block rounded" style="background:#34d399"></span>内存 MB</span>
</div>
</div>
<div class="chart-box" id="chartCpuMem"></div>
</div>
<!-- 网络流量 -->
<div class="chart-card">
<div class="flex items-center justify-between mb-3">
<div>
<span class="text-sm font-semibold">网络流量</span>
<span class="text-xs ml-2" style="color:var(--text-muted)">KB/s</span>
</div>
<div class="flex items-center gap-3 text-xs" style="color:var(--text-muted)">
<span class="flex items-center gap-1"><span class="w-3 h-0.5 inline-block rounded" style="background:#818cf8"></span>上传</span>
<span class="flex items-center gap-1"><span class="w-3 h-0.5 inline-block rounded" style="background:#f472b6"></span>下载</span>
</div>
</div>
<div class="chart-box" id="chartNetwork"></div>
</div>
<!-- 磁盘 IO -->
<div class="chart-card">
<div class="flex items-center justify-between mb-3">
<div>
<span class="text-sm font-semibold">磁盘 IO</span>
<span class="text-xs ml-2" style="color:var(--text-muted)">进程级 KB/s</span>
</div>
<div class="flex items-center gap-3 text-xs" style="color:var(--text-muted)">
<span class="flex items-center gap-1"><span class="w-3 h-0.5 inline-block rounded" style="background:#fb923c"></span>读取</span>
<span class="flex items-center gap-1"><span class="w-3 h-0.5 inline-block rounded" style="background:#a78bfa"></span>写入</span>
</div>
</div>
<div class="chart-box" id="chartDiskIO"></div>
</div>
<!-- API 调用次数 -->
<div class="chart-card">
<div class="flex items-center justify-between mb-3">
<span class="text-sm font-semibold">API 调用次数</span>
<span class="text-xs" style="color:var(--text-muted)">次/周期</span>
</div>
<div class="chart-box" id="chartApiCalls"></div>
</div>
</div>
<!-- 业务活动:单独一行全宽 -->
<div class="chart-card">
<div class="flex items-center justify-between mb-3">
<span class="text-sm font-semibold">业务活动</span>
<span class="text-xs" style="color:var(--text-muted)">创建 / 提交 / 下载 / 导出 / 登录</span>
</div>
<div class="chart-box" id="chartBusiness"></div>
</div>
</div>
<!-- 无数据提示 -->
<div id="chartEmpty" class="hidden text-center py-20">
<svg xmlns="http://www.w3.org/2000/svg" width="40" height="40" viewBox="0 0 24 24" fill="none"
stroke="currentColor" stroke-width="1.5" class="mx-auto mb-3" style="color:var(--text-muted)">
<path d="M3 3v18h18"/><path d="m19 9-5 5-4-4-3 3"/>
</svg>
<p class="text-sm" style="color:var(--text-muted)">暂无历史数据</p>
<p class="text-xs mt-1" style="color:var(--text-muted)">系统每分钟采集一次指标,稍后再来查看</p>
</div>
</section>
<!-- ===== Section 3: 本周期统计 ===== -->
<section>
<div class="mb-4">
<span class="section-title">当前周期汇总</span>
<span class="text-xs ml-2" style="color:var(--text-muted)" id="periodLabel">(当前时间段内)</span>
</div>
<div class="grid grid-cols-2 lg:grid-cols-4 gap-4">
<div class="metric-card text-center">
<div class="text-3xl font-bold mb-1" id="sumForms">--</div>
<div class="text-xs" style="color:var(--text-muted)">表单创建</div>
</div>
<div class="metric-card text-center">
<div class="text-3xl font-bold mb-1" id="sumSubmissions">--</div>
<div class="text-xs" style="color:var(--text-muted)">表单提交</div>
</div>
<div class="metric-card text-center">
<div class="text-3xl font-bold mb-1" id="sumFiles">--</div>
<div class="text-xs" style="color:var(--text-muted)">文件上传量</div>
</div>
<div class="metric-card text-center">
<div class="text-3xl font-bold mb-1" id="sumDownloads">--</div>
<div class="text-xs" style="color:var(--text-muted)">文件下载</div>
</div>
<div class="metric-card text-center">
<div class="text-3xl font-bold mb-1" id="sumExports">--</div>
<div class="text-xs" style="color:var(--text-muted)">数据导出</div>
</div>
<div class="metric-card text-center">
<div class="text-3xl font-bold mb-1" id="sumLogins">--</div>
<div class="text-xs" style="color:var(--text-muted)">用户登录</div>
</div>
<div class="metric-card text-center">
<div class="text-3xl font-bold mb-1" id="sumApiCalls">--</div>
<div class="text-xs" style="color:var(--text-muted)">API 调用</div>
</div>
</div>
</section>
</div><!-- end container -->
<!-- ===== 清理数据 Modal ===== -->
<div id="cleanupModal" class="modal-overlay" onclick="closeCleanupModal(event)">
<div class="modal-box" onclick="event.stopPropagation()">
<h3 class="text-lg font-semibold mb-1">清理历史监控数据</h3>
<p class="text-sm mb-4" style="color:var(--text-muted)">选择日期,删除该日期之前的所有系统指标数据。此操作不可撤销。</p>
<label class="block text-xs font-medium mb-2" style="color:var(--text-secondary)">删除该日期之前的数据</label>
<input type="datetime-local" id="cleanupDate" />
<div id="cleanupCountHint" class="mt-2 text-xs hidden" style="color:var(--warning-text)">
该日期前共有 <strong id="cleanupCount">0</strong> 条数据
</div>
<div class="flex justify-end gap-3 mt-6">
<button onclick="closeCleanupModal()" class="btn btn-secondary rounded-xl px-4 py-2 text-sm">取消</button>
<button onclick="doCleanup()" id="cleanupConfirmBtn" class="btn btn-danger rounded-xl px-4 py-2 text-sm flex items-center gap-2">
<svg xmlns="http://www.w3.org/2000/svg" width="14" height="14" viewBox="0 0 24 24" fill="none"
stroke="currentColor" stroke-width="2">
<polyline points="3 6 5 6 21 6"/>
<path d="M19 6l-1 14a2 2 0 0 1-2 2H8a2 2 0 0 1-2-2L5 6"/>
</svg>
确认删除
</button>
</div>
</div>
</div>
<script>
// ============================================================
// Utility helpers
// ============================================================
function fmtBytes(bytes) {
if (bytes == null || bytes < 0) return '--';
if (bytes >= 1073741824) return (bytes / 1073741824).toFixed(2) + ' GB';
if (bytes >= 1048576) return (bytes / 1048576).toFixed(1) + ' MB';
if (bytes >= 1024) return (bytes / 1024).toFixed(1) + ' KB';
return bytes + ' B';
}
function fmtSpeed(bps) {
// bps = bytes per second → KB/s
if (bps == null) return '--';
const kbps = bps / 1024;
if (kbps >= 1024) return (kbps / 1024).toFixed(1) + ' MB/s';
return kbps.toFixed(1) + ' KB/s';
}
function colorForPct(pct) {
if (pct >= 90) return 'progress-red';
if (pct >= 70) return 'progress-yellow';
return 'progress-blue';
}
// ============================================================
// Realtime polling — 1s 采样 + 5点滑动窗口均值(≈5s平均)
// ============================================================
let realtimeTimer = null;
// 滑动窗口:最近 5 个采样点(1s × 5 = 5s 均值)
const WINDOW_SIZE = 5;
const _rtBuf = {
cpu: [],
memUsed: [],
diskRead: [],
diskWrite: [],
netSent: [],
netRecv: [],
};
function _pushBuf(key, val) {
_rtBuf[key].push(val);
if (_rtBuf[key].length > WINDOW_SIZE) _rtBuf[key].shift();
}
function _avg(arr) {
if (!arr.length) return 0;
return arr.reduce((a, b) => a + b, 0) / arr.length;
}
async function fetchRealtime() {
try {
const res = await fetch('/api/monitor/realtime');
if (!res.ok) return;
const d = await res.json();
// 采样入队
_pushBuf('cpu', d.cpu_percent || 0);
_pushBuf('memUsed', (d.memory || {}).used || 0);
_pushBuf('diskRead', (d.disk || {}).read_speed || 0);
_pushBuf('diskWrite', (d.disk || {}).write_speed || 0);
_pushBuf('netSent', (d.network || {}).sent_speed || 0);
_pushBuf('netRecv', (d.network || {}).recv_speed || 0);
// 均值
const cpu = _avg(_rtBuf.cpu);
const memUsed = _avg(_rtBuf.memUsed);
const diskR = _avg(_rtBuf.diskRead);
const diskW = _avg(_rtBuf.diskWrite);
const netS = _avg(_rtBuf.netSent);
const netRv = _avg(_rtBuf.netRecv);
// CPU
document.getElementById('cpuValue').textContent = cpu.toFixed(1) + '%';
const cpuBar = document.getElementById('cpuBar');
cpuBar.style.width = cpu + '%';
cpuBar.className = 'progress-fill ' + colorForPct(cpu);
// Memory
document.getElementById('memValue').textContent = fmtBytes(memUsed);
document.getElementById('memDetail').textContent = 'RSS 内存占用';
const memBar = document.getElementById('memBar');
memBar.style.width = Math.min(memUsed / (500 * 1024 * 1024) * 100, 100) + '%';
memBar.className = 'progress-fill ' + (memUsed > 500*1024*1024 ? 'progress-red' : memUsed > 200*1024*1024 ? 'progress-yellow' : 'progress-green');
// Disk IO
document.getElementById('diskReadValue').textContent = fmtBytes(diskR) + '/s';
document.getElementById('diskWriteValue').textContent = fmtBytes(diskW) + '/s';
// Network
document.getElementById('netSent').textContent = fmtSpeed(netS);
document.getElementById('netRecv').textContent = fmtSpeed(netRv);
// Requests & Users(瞬时值,不均值)
document.getElementById('activeReqs').textContent = d.active_requests ?? '--';
document.getElementById('onlineUsers').textContent = d.online_users ?? '--';
// Update time
const now = new Date();
document.getElementById('lastUpdateTime').textContent =
'更新于 ' + now.toLocaleTimeString('zh-CN');
} catch (e) {
// silent
}
}
function startRealtime() {
fetchRealtime();
realtimeTimer = setInterval(fetchRealtime, 1000); // 1s 轮询
}
// ============================================================
// Charts
// ============================================================
let charts = {};
let currentGranularity = '1h';
let historyTimer = null;
let _forceFullRender = false; // 主题切换时置 true,强制全量重绘
function getChartTheme() {
const isDark = document.documentElement.classList.contains('dark');
return {
bg: isDark ? 'transparent' : 'transparent',
text: isDark ? '#a3a3a3' : '#737373',
grid: isDark ? 'rgba(255,255,255,0.06)' : 'rgba(0,0,0,0.06)',
tooltip: isDark ? '#171717' : '#ffffff',
tooltipBorder: isDark ? '#262626' : '#e5e5e5',
};
}
function buildBaseOption(title, xData, series) {
const t = getChartTheme();
return {
tooltip: {
trigger: 'axis',
backgroundColor: t.tooltip,
borderColor: t.tooltipBorder,
borderWidth: 1,
textStyle: { color: t.text, fontSize: 12 },
axisPointer: { type: 'cross', crossStyle: { color: t.grid } }
},
legend: {
show: false
},
grid: { top: 12, left: 40, right: 20, bottom: 30, containLabel: false },
xAxis: {
type: 'category',
data: xData,
axisLine: { lineStyle: { color: t.grid } },
axisTick: { show: false },
axisLabel: {
color: t.text, fontSize: 11,
interval: Math.max(0, Math.floor(xData.length / 8) - 1),
rotate: xData.length > 20 ? 30 : 0
},
splitLine: { show: false }
},
yAxis: {
type: 'value',
axisLabel: { color: t.text, fontSize: 11 },
axisLine: { show: false },
axisTick: { show: false },
splitLine: { lineStyle: { color: t.grid, type: 'dashed' } }
},
series
};
}
function makeAreaSeries(name, data, color, yMax) {
return {
name,
type: 'line',
data,
smooth: true,
symbol: 'none',
lineStyle: { color, width: 2 },
areaStyle: {
color: {
type: 'linear', x: 0, y: 0, x2: 0, y2: 1,
colorStops: [
{ offset: 0, color: color + '40' },
{ offset: 1, color: color + '05' }
]
}
},
itemStyle: { color }
};
}
// 纯折线(无面积填充),用于多系列叠加时避免颜色混淆
function makeLineSeries(name, data, color) {
return {
name,
type: 'line',
data,
smooth: true,
symbol: 'none',
lineStyle: { color, width: 2 },
itemStyle: { color }
};
}
function makeBarSeries(name, data, color) {
return {
name,
type: 'bar',
data,
barMaxWidth: 20,
itemStyle: {
color,
borderRadius: [3, 3, 0, 0]
}
};
}
function initChart(id) {
// 复用已有实例,不 dispose,避免每次更新触发入场动画
if (!charts[id]) {
charts[id] = echarts.init(document.getElementById(id));
}
return charts[id];
}
function updateChartOption(id, option) {
const chart = initChart(id);
// 主题切换时全量重绘(notMerge:true),普通数据刷新增量更新(notMerge:false)
chart.setOption(option, { notMerge: !!_forceFullRender, lazyUpdate: false, silent: false });
}
function renderCharts(data) {
const ts = data.timestamps || [];
if (ts.length === 0) {
document.getElementById('chartLoading').classList.add('hidden');
document.getElementById('chartArea').classList.add('hidden');
document.getElementById('chartEmpty').classList.remove('hidden');
return;
}
document.getElementById('chartLoading').classList.add('hidden');
document.getElementById('chartEmpty').classList.add('hidden');
document.getElementById('chartArea').classList.remove('hidden');
// CPU & Memory — 双 Y 轴(CPU 左轴 %,内存 右轴 MB)
const t = getChartTheme();
updateChartOption('chartCpuMem', {
tooltip: {
trigger: 'axis',
backgroundColor: t.tooltip,
borderColor: t.tooltipBorder,
borderWidth: 1,
textStyle: { color: t.text, fontSize: 12 },
axisPointer: { type: 'cross', crossStyle: { color: t.grid } },
formatter: function(params) {
let html = `<div style="font-weight:600;margin-bottom:4px">${params[0].axisValue}</div>`;
params.forEach(p => {
const unit = p.seriesName.indexOf('CPU') !== -1 ? '%' : ' MB';
html += `<div>${p.marker}${p.seriesName}:<b>${p.value}${unit}</b></div>`;
});
return html;
}
},
legend: { show: false },
grid: { top: 12, left: 50, right: 55, bottom: 30, containLabel: false },
xAxis: {
type: 'category',
data: ts,
axisLine: { lineStyle: { color: t.grid } },
axisTick: { show: false },
axisLabel: {
color: t.text, fontSize: 11,
interval: Math.max(0, Math.floor(ts.length / 8) - 1),
rotate: ts.length > 20 ? 30 : 0
},
splitLine: { show: false }
},
yAxis: [
{
type: 'value',
name: 'CPU %',
nameTextStyle: { color: t.text, fontSize: 10 },
min: 0, max: 100,
axisLabel: { color: '#60a5fa', fontSize: 11, formatter: '{value}%' },
axisLine: { show: true, lineStyle: { color: '#60a5fa' } },
axisTick: { show: false },
splitLine: { lineStyle: { color: t.grid, type: 'dashed' } }
},
{
type: 'value',
name: 'MB',
nameTextStyle: { color: t.text, fontSize: 10 },
axisLabel: { color: '#34d399', fontSize: 11, formatter: '{value}' },
axisLine: { show: true, lineStyle: { color: '#34d399' } },
axisTick: { show: false },
splitLine: { show: false }
}
],
series: [
{
name: 'CPU %',
type: 'line',
yAxisIndex: 0,
data: data.cpu,
smooth: true,
symbol: 'none',
lineStyle: { color: '#60a5fa', width: 2 },
areaStyle: {
color: { type: 'linear', x: 0, y: 0, x2: 0, y2: 1,
colorStops: [{ offset: 0, color: '#60a5fa40' }, { offset: 1, color: '#60a5fa05' }] }
},
itemStyle: { color: '#60a5fa' }
},
{
name: '内存 MB',
type: 'line',
yAxisIndex: 1,
data: data.memory,
smooth: true,
symbol: 'none',
lineStyle: { color: '#34d399', width: 2 },
areaStyle: {
color: { type: 'linear', x: 0, y: 0, x2: 0, y2: 1,
colorStops: [{ offset: 0, color: '#34d39940' }, { offset: 1, color: '#34d39905' }] }
},
itemStyle: { color: '#34d399' }
}
]
});
// Network
updateChartOption('chartNetwork', buildBaseOption('网络', ts, [
makeLineSeries('上传 KB/s', data.net_sent, '#818cf8'),
makeLineSeries('下载 KB/s', data.net_recv, '#f472b6'),
]));
// Disk IO
updateChartOption('chartDiskIO', buildBaseOption('磁盘IO', ts, [
makeLineSeries('读取 KB/s', data.disk_read, '#fb923c'),
makeLineSeries('写入 KB/s', data.disk_write, '#a78bfa'),
]));
// API calls
const biz = data.business || {};
updateChartOption('chartApiCalls', buildBaseOption('API调用', ts, [
makeBarSeries('API调用', biz.api_calls, '#60a5fa'),
]));
// Business
updateChartOption('chartBusiness', buildBaseOption('业务', ts, [
makeBarSeries('表单创建', biz.forms_created, '#34d399'),
makeBarSeries('表单提交', biz.form_submissions, '#60a5fa'),
makeBarSeries('文件下载', biz.file_downloads, '#fb923c'),
makeBarSeries('数据导出', biz.data_exports, '#a78bfa'),
makeBarSeries('登录次数', biz.user_logins, '#fbbf24'),
makeAreaSeries('上传MB', biz.files_uploaded_mb, '#f472b6'),
]));
// 周期汇总
const sumArr = arr => (arr || []).reduce((s, v) => s + (parseFloat(v) || 0), 0);
document.getElementById('sumForms').textContent = sumArr(biz.forms_created);
document.getElementById('sumSubmissions').textContent = sumArr(biz.form_submissions);
document.getElementById('sumFiles').textContent = (sumArr(biz.files_uploaded_mb)).toFixed(1) + ' MB';
document.getElementById('sumDownloads').textContent = sumArr(biz.file_downloads);
document.getElementById('sumExports').textContent = sumArr(biz.data_exports);
document.getElementById('sumLogins').textContent = sumArr(biz.user_logins);
document.getElementById('sumApiCalls').textContent = sumArr(biz.api_calls);
// 周期描述
const labels = { '1h': '最近1小时', '6h': '最近6小时', '24h': '最近24小时', '7d': '最近7天', '30d': '最近30天' };
document.getElementById('periodLabel').textContent = '(' + (labels[currentGranularity] || '') + '内)';
}
async function loadHistory() {
document.getElementById('chartLoading').classList.remove('hidden');
document.getElementById('chartArea').classList.add('hidden');
document.getElementById('chartEmpty').classList.add('hidden');
try {
const res = await fetch(`/api/monitor/history?granularity=${currentGranularity}`);
if (!res.ok) throw new Error('请求失败');
const data = await res.json();
renderCharts(data);
} catch (e) {
document.getElementById('chartLoading').classList.add('hidden');
document.getElementById('chartEmpty').classList.remove('hidden');
showToast('获取历史数据失败: ' + e.message, 'error');
} finally {
_forceFullRender = false; // 刷新完毕后复位
}
}
function selectGranularity(btn) {
document.querySelectorAll('#granularityBtns .granularity-btn').forEach(t => t.classList.remove('active'));
btn.classList.add('active');
currentGranularity = btn.dataset.gran;
loadHistory();
}
// Auto-refresh charts every 5 min
function startHistoryAutoRefresh() {
clearInterval(historyTimer);
historyTimer = setInterval(loadHistory, 5 * 60 * 1000);
}
// Resize handler
window.addEventListener('resize', () => {
Object.values(charts).forEach(c => { try { c.resize(); } catch(e) {} });
});
// Theme change → re-render(全量重绘,确保颜色正确)
const themeObserver = new MutationObserver(() => {
if (document.getElementById('chartArea').classList.contains('hidden')) return;
_forceFullRender = true;
loadHistory();
});
themeObserver.observe(document.documentElement, { attributes: true, attributeFilter: ['class'] });
// ============================================================
// Cleanup Modal
// ============================================================
let cleanupCountTimer = null;
function openCleanupModal() {
const modal = document.getElementById('cleanupModal');
// 默认设为30天前
const d = new Date();
d.setDate(d.getDate() - 30);
const iso = d.toISOString().slice(0, 16);
document.getElementById('cleanupDate').value = iso;
document.getElementById('cleanupCountHint').classList.add('hidden');
modal.classList.add('open');
// 查询条数
queryCleanupCount(iso);
}
function closeCleanupModal(event) {
if (event && event.target !== document.getElementById('cleanupModal')) return;
document.getElementById('cleanupModal').classList.remove('open');
}
document.getElementById('cleanupDate').addEventListener('change', function () {
queryCleanupCount(this.value);
});
async function queryCleanupCount(dtVal) {
if (!dtVal) return;
try {
const res = await fetch(`/api/monitor/count_before?before_date=${encodeURIComponent(dtVal)}`);
const d = await res.json();
document.getElementById('cleanupCount').textContent = d.count || 0;
document.getElementById('cleanupCountHint').classList.remove('hidden');
} catch (e) {}
}
async function doCleanup() {
const dtVal = document.getElementById('cleanupDate').value;
if (!dtVal) {
showToast('请选择日期', 'warning');
return;
}
const count = parseInt(document.getElementById('cleanupCount').textContent || '0');
const dateStr = dtVal.replace('T', ' ');
const btn = document.getElementById('cleanupConfirmBtn');
btn.disabled = true;
btn.innerHTML = '<div class="loading-spin" style="width:14px;height:14px;border-width:2px"></div> 删除中...';
try {
const res = await fetch('/api/monitor/cleanup', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ before_date: dtVal + ':00' })
});
const d = await res.json();
if (d.success) {
showToast(`已成功删除 ${d.deleted_count} 条监控数据`, 'success');
document.getElementById('cleanupModal').classList.remove('open');
loadHistory();
} else {
showToast('删除失败: ' + (d.error || '未知错误'), 'error');
}
} catch (e) {
showToast('请求失败: ' + e.message, 'error');
} finally {
btn.disabled = false;
btn.innerHTML = `<svg xmlns="http://www.w3.org/2000/svg" width="14" height="14" viewBox="0 0 24 24" fill="none"
stroke="currentColor" stroke-width="2">
<polyline points="3 6 5 6 21 6"/>
<path d="M19 6l-1 14a2 2 0 0 1-2 2H8a2 2 0 0 1-2-2L5 6"/>
</svg>确认删除`;
}
}
// ============================================================
// Init
// ============================================================
document.addEventListener('DOMContentLoaded', () => {
startRealtime();
loadHistory();
startHistoryAutoRefresh();
// GSAP entrance animation
// CSS transition 已移除 transform/opacity,由 GSAP 独占控制,避免冲突
if (typeof gsap !== 'undefined') {
const cards = document.querySelectorAll('.metric-card');
// 入场前先把 opacity 设为 0,防止 GSAP 初始化延迟造成闪现
gsap.set(cards, { opacity: 0, y: 20 });
gsap.to(cards, {
duration: 0.6,
y: 0, opacity: 1,
stagger: 0.07,
ease: 'power2.out',
onComplete: function() {
// 动画结束后清理 gsap 内联样式,还权给 CSS(hover transform 才能正常工作)
cards.forEach(el => {
el.style.removeProperty('transform');
el.style.removeProperty('opacity');
});
}
});
}
});
// Cleanup on page unload
window.addEventListener('beforeunload', () => {
clearInterval(realtimeTimer);
clearInterval(historyTimer);
});
</script>
</body>
</html>