3 Commits

2 changed files with 317 additions and 28 deletions

289
app.py
View File

@@ -799,6 +799,58 @@ def api_system_stats():
return jsonify({'error': str(e), 'available': False})
@app.route('/api/system/processes')
def api_system_processes():
"""获取CPU占用最高的进程列表"""
if not HAS_PSUTIL:
return jsonify({'error': 'psutil未安装', 'available': False})
try:
limit = int(request.args.get('limit', 10))
limit = max(1, min(50, limit)) # 限制1-50
processes = []
for proc in psutil.process_iter(['pid', 'name', 'memory_percent', 'status', 'create_time', 'exe', 'cmdline']):
try:
pinfo = proc.info
# 获取实时CPU占用需要单独调用
cpu_percent = proc.cpu_percent(interval=0.1)
# 格式化命令行
cmdline = pinfo.get('cmdline', [])
cmdline_str = ' '.join(cmdline) if cmdline else pinfo['name']
if len(cmdline_str) > 60:
cmdline_str = cmdline_str[:60] + '...'
# 启动时间
create_time = datetime.fromtimestamp(pinfo['create_time']).strftime('%m-%d %H:%M')
processes.append({
'pid': pinfo['pid'],
'name': pinfo['name'],
'cpu': cpu_percent,
'memory': pinfo['memory_percent'] or 0,
'status': pinfo['status'],
'create_time': create_time,
'exe': pinfo.get('exe', '') or '',
'cmdline': cmdline_str
})
except (psutil.NoSuchProcess, psutil.AccessDenied):
continue
# 按CPU占用排序取前N个
processes.sort(key=lambda x: x['cpu'], reverse=True)
top_processes = processes[:limit]
return jsonify({
'available': True,
'processes': top_processes,
'count': len(top_processes)
})
except Exception as e:
return jsonify({'error': str(e), 'available': False})
def guess_cron_name(command):
"""从命令推断任务名称"""
keywords = {
@@ -1103,7 +1155,7 @@ HTML_TEMPLATE = '''<!DOCTYPE html>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>项目服务管理面板 v3.1</title>
<title>项目服务管理面板 v3.3</title>
<link rel="icon" href="data:image/svg+xml,<svg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 100 100'><text y='.9em' font-size='90'>📊</text></svg>">
<script src="https://cdn.tailwindcss.com"></script>
<link href="https://cdn.jsdelivr.net/npm/remixicon@3.5.0/fonts/remixicon.css" rel="stylesheet">
@@ -1465,6 +1517,28 @@ HTML_TEMPLATE = '''<!DOCTYPE html>
<span id="realtimeIndicator" class="text-xs text-green-400 ml-1 hidden">●</span>
</div>
</div>
<!-- 进程列表(实时监控时显示) -->
<div id="processListSection" class="hidden mt-6">
<div class="flex items-center justify-between mb-3">
<h3 class="font-bold text-gray-200 flex items-center gap-2">
<i class="ri-bar-chart-horizontal text-purple-400"></i> CPU占用最高的进程
</h3>
<div class="flex items-center gap-2">
<span class="text-gray-400 text-xs">显示数量:</span>
<select id="processLimitSelect" class="bg-gray-700 text-gray-200 px-2 py-1 rounded text-xs" onchange="loadTopProcesses()">
<option value="5">5</option>
<option value="10" selected>10</option>
<option value="15">15</option>
<option value="20">20</option>
<option value="30">30</option>
</select>
</div>
</div>
<div id="processList" class="space-y-2">
<div class="text-gray-500 text-center py-4"><i class="ri-loader-4-line animate-spin"></i> 加载中...</div>
</div>
</div>
</div>
<!-- Cron 管理 Tab -->
@@ -1738,6 +1812,25 @@ HTML_TEMPLATE = '''<!DOCTYPE html>
</div>
</div>
<div class="mb-3">
<label class="block text-gray-400 text-sm mb-1">触发机制 *</label>
<select id="emailRuleTriggerType" class="w-full bg-gray-700 text-gray-200 px-3 py-2 rounded-lg" onchange="updateTriggerParams()">
<option value="single">一次性触发 - 超过阈值立即通知</option>
<option value="continuous">连续触发 - 连续超过阈值N次</option>
<option value="duration">持续时间触发 - 累计超过阈值N秒</option>
<option value="average">平均值触发 - 最近N次平均值超过阈值</option>
</select>
</div>
<div class="mb-3" id="triggerParamsDiv" style="display:none;">
<label class="block text-gray-400 text-sm mb-1" id="triggerParamsLabel">触发参数</label>
<div class="flex items-center gap-2">
<input type="number" id="emailRuleTriggerParam" min="1" max="100" value="3" class="w-20 bg-gray-700 text-gray-200 px-3 py-2 rounded-lg">
<span class="text-gray-400" id="triggerParamUnit">次</span>
</div>
<p class="text-gray-500 text-xs mt-1" id="triggerParamHint">连续超过阈值多少次才触发</p>
</div>
<div class="mb-3">
<label class="block text-gray-400 text-sm mb-1">收件邮箱 *</label>
<input type="email" id="emailRuleAddress" required class="w-full bg-gray-700 text-gray-200 px-3 py-2 rounded-lg" placeholder="alert@example.com">
@@ -1817,6 +1910,7 @@ HTML_TEMPLATE = '''<!DOCTYPE html>
document.getElementById('realtimeCheck').checked = false;
document.getElementById('realtimeToggle').classList.remove('active');
document.getElementById('realtimeIndicator').classList.add('hidden');
document.getElementById('processListSection').classList.add('hidden');
}
if (tab === 'cron') {
@@ -2040,26 +2134,82 @@ HTML_TEMPLATE = '''<!DOCTYPE html>
// 检查阈值
checkThresholds(data);
// 如果实时监控开启,加载进程列表
if (document.getElementById('realtimeCheck').checked) {
loadTopProcesses();
}
} catch (e) {
console.error('系统资源加载失败:', e);
}
}
// 加载CPU占用最高的进程
async function loadTopProcesses() {
try {
const limit = document.getElementById('processLimitSelect').value;
const res = await fetch(`/api/system/processes?limit=${limit}`);
const data = await res.json();
if (!data.available) {
document.getElementById('processList').innerHTML = '<div class="text-red-400 text-center py-4">无法获取进程信息</div>';
return;
}
const list = document.getElementById('processList');
if (data.processes.length === 0) {
list.innerHTML = '<div class="text-gray-500 text-center py-4">暂无进程数据</div>';
return;
}
list.innerHTML = data.processes.map(proc => `
<div class="card rounded-lg p-3 hover:border-gray-500 transition-colors">
<div class="flex items-center justify-between">
<div class="flex items-center gap-3 min-w-0">
<span class="text-purple-400 font-mono text-sm">${proc.pid}</span>
<div class="min-w-0 flex-1">
<div class="text-gray-200 truncate">${proc.name}</div>
<div class="text-gray-500 text-xs truncate">${proc.cmdline || proc.exe}</div>
</div>
</div>
<div class="flex items-center gap-4 text-xs shrink-0">
<div class="text-right">
<span class="text-blue-400 font-bold">${proc.cpu.toFixed(1)}%</span>
<span class="text-gray-500 ml-1">CPU</span>
</div>
<div class="text-right">
<span class="text-green-400 font-bold">${proc.memory.toFixed(1)}%</span>
<span class="text-gray-500 ml-1">内存</span>
</div>
<div class="text-gray-400">${proc.create_time}</div>
</div>
</div>
</div>
`).join('');
} catch (e) {
console.error('进程列表加载失败:', e);
}
}
function toggleRealtime() {
const checked = document.getElementById('realtimeCheck').checked;
const toggle = document.getElementById('realtimeToggle');
const indicator = document.getElementById('realtimeIndicator');
const processSection = document.getElementById('processListSection');
if (checked) {
toggle.classList.add('active');
indicator.classList.remove('hidden');
processSection.classList.remove('hidden');
// 立即加载一次
loadSystemStats();
loadTopProcesses();
// 启动定时器
realtimeTimer = setInterval(loadSystemStats, realtimeInterval * 1000);
} else {
toggle.classList.remove('active');
indicator.classList.add('hidden');
processSection.classList.add('hidden');
// 停止定时器
if (realtimeTimer) {
clearInterval(realtimeTimer);
@@ -2410,12 +2560,20 @@ HTML_TEMPLATE = '''<!DOCTYPE html>
list.innerHTML = rules.map(rule => {
const silentInfo = rule.silentEnabled ? `静默:${rule.silentStart}-${rule.silentEnd}` : '';
const triggerType = rule.triggerType || 'single';
const triggerParam = rule.triggerParam || 3;
let triggerDisplay = '一次性';
if (triggerType === 'continuous') triggerDisplay = `连续${triggerParam}次`;
else if (triggerType === 'duration') triggerDisplay = `持续${triggerParam}秒`;
else if (triggerType === 'average') triggerDisplay = `平均${triggerParam}次`;
return `
<div class="flex items-center justify-between bg-gray-700/50 px-3 py-2 rounded-lg">
<div class="flex items-center gap-3 flex-wrap">
<span class="px-2 py-0.5 rounded text-xs ${rule.enabled ? 'bg-green-500/20 text-green-400' : 'bg-gray-500/20 text-gray-400'}">${rule.enabled ? '启用' : '禁用'}</span>
<span class="text-gray-200">${rule.name}</span>
<span class="text-gray-400 text-xs">${resourceNames[rule.resource]} ≥ ${rule.threshold}%</span>
<span class="text-blue-400/70 text-xs"><i class="ri-flashlight-line"></i> ${triggerDisplay}</span>
<span class="text-gray-400 text-xs">→ ${rule.email}</span>
${silentInfo ? `<span class="text-yellow-400/70 text-xs"><i class="ri-moon-line"></i> ${silentInfo}</span>` : ''}
</div>
@@ -2434,6 +2592,9 @@ HTML_TEMPLATE = '''<!DOCTYPE html>
document.getElementById('emailRuleName').value = '';
document.getElementById('emailRuleResource').value = 'cpu';
document.getElementById('emailRuleThreshold').value = 80;
document.getElementById('emailRuleTriggerType').value = 'single';
document.getElementById('emailRuleTriggerParam').value = 3;
document.getElementById('triggerParamsDiv').style.display = 'none';
document.getElementById('emailRuleAddress').value = '';
document.getElementById('emailRuleInterval').value = 300;
document.getElementById('emailRuleSilentStart').value = '23:00';
@@ -2447,6 +2608,46 @@ HTML_TEMPLATE = '''<!DOCTYPE html>
document.getElementById('emailRuleModal').classList.add('hidden');
}
function updateTriggerParams() {
const triggerType = document.getElementById('emailRuleTriggerType').value;
const paramsDiv = document.getElementById('triggerParamsDiv');
const labelEl = document.getElementById('triggerParamsLabel');
const unitEl = document.getElementById('triggerParamUnit');
const hintEl = document.getElementById('triggerParamHint');
const paramInput = document.getElementById('emailRuleTriggerParam');
// 根据触发类型设置不同的参数
switch (triggerType) {
case 'single':
paramsDiv.style.display = 'none';
break;
case 'continuous':
paramsDiv.style.display = 'flex';
labelEl.textContent = '连续次数';
unitEl.textContent = '';
hintEl.textContent = '连续超过阈值多少次才触发';
paramInput.max = 100;
paramInput.value = 3;
break;
case 'duration':
paramsDiv.style.display = 'flex';
labelEl.textContent = '持续时间';
unitEl.textContent = '';
hintEl.textContent = '累计超过阈值多少秒才触发';
paramInput.max = 3600;
paramInput.value = 60;
break;
case 'average':
paramsDiv.style.display = 'flex';
labelEl.textContent = '采样次数';
unitEl.textContent = '';
hintEl.textContent = '最近N次采样的平均值超过阈值才触发';
paramInput.max = 100;
paramInput.value = 5;
break;
}
}
function editEmailRule(ruleId) {
const rules = getEmailRules();
const rule = rules.find(r => r.id === ruleId);
@@ -2457,6 +2658,9 @@ HTML_TEMPLATE = '''<!DOCTYPE html>
document.getElementById('emailRuleName').value = rule.name;
document.getElementById('emailRuleResource').value = rule.resource;
document.getElementById('emailRuleThreshold').value = rule.threshold;
document.getElementById('emailRuleTriggerType').value = rule.triggerType || 'single';
document.getElementById('emailRuleTriggerParam').value = rule.triggerParam || 3;
updateTriggerParams();
document.getElementById('emailRuleAddress').value = rule.email;
document.getElementById('emailRuleInterval').value = rule.interval;
document.getElementById('emailRuleSilentStart').value = rule.silentStart || '23:00';
@@ -2473,6 +2677,8 @@ HTML_TEMPLATE = '''<!DOCTYPE html>
const name = document.getElementById('emailRuleName').value.trim();
const resource = document.getElementById('emailRuleResource').value;
const threshold = parseInt(document.getElementById('emailRuleThreshold').value);
const triggerType = document.getElementById('emailRuleTriggerType').value;
const triggerParam = parseInt(document.getElementById('emailRuleTriggerParam').value) || 3;
const email = document.getElementById('emailRuleAddress').value.trim();
const interval = parseInt(document.getElementById('emailRuleInterval').value) || 300;
const silentStart = document.getElementById('emailRuleSilentStart').value;
@@ -2491,14 +2697,17 @@ HTML_TEMPLATE = '''<!DOCTYPE html>
// 编辑
const idx = rules.findIndex(r => r.id === ruleId);
if (idx >= 0) {
rules[idx] = { ...rules[idx], name, resource, threshold, email, interval, silentStart, silentEnd, silentEnabled, enabled };
rules[idx] = { ...rules[idx], name, resource, threshold, triggerType, triggerParam, email, interval, silentStart, silentEnd, silentEnabled, enabled };
}
} else {
// 新增
rules.push({
id: 'rule_' + Date.now(),
name, resource, threshold, email, interval, silentStart, silentEnd, silentEnabled, enabled,
lastSent: 0
name, resource, threshold, triggerType, triggerParam, email, interval, silentStart, silentEnd, silentEnabled, enabled,
lastSent: 0,
exceedCount: 0, // 连续超过次数
exceedDuration: 0, // 累计超过时间
recentValues: [] // 最近采样值
});
}
@@ -2548,9 +2757,77 @@ HTML_TEMPLATE = '''<!DOCTYPE html>
}
}
// 检查阈值
// 检查阈值和触发机制
const value = data[rule.resource]?.percent;
if (value === undefined || value < rule.threshold) continue;
if (value === undefined) continue;
// 初始化触发相关数据
if (!rule.exceedCount) rule.exceedCount = 0;
if (!rule.exceedDuration) rule.exceedDuration = 0;
if (!rule.recentValues) rule.recentValues = [];
if (!rule.triggerType) rule.triggerType = 'single';
if (!rule.triggerParam) rule.triggerParam = 3;
const triggerType = rule.triggerType;
const triggerParam = rule.triggerParam;
const isExceedThreshold = value >= rule.threshold;
let shouldTrigger = false;
// 根据触发类型判断
switch (triggerType) {
case 'single':
// 一次性触发:超过阈值立即触发
if (isExceedThreshold) shouldTrigger = true;
break;
case 'continuous':
// 连续触发连续超过阈值N次
if (isExceedThreshold) {
rule.exceedCount++;
if (rule.exceedCount >= triggerParam) {
shouldTrigger = true;
rule.exceedCount = 0; // 触发后重置计数
}
} else {
rule.exceedCount = 0; // 未超过阈值时重置计数
}
break;
case 'duration':
// 持续时间触发累计超过阈值N秒
if (isExceedThreshold) {
// 增加累计时间假设实时监控间隔为2秒
const intervalSeconds = realtimeInterval || 2;
rule.exceedDuration += intervalSeconds;
if (rule.exceedDuration >= triggerParam) {
shouldTrigger = true;
rule.exceedDuration = 0; // 触发后重置
}
} else {
rule.exceedDuration = 0; // 未超过阈值时重置累计时间
}
break;
case 'average':
// 平均值触发最近N次平均值超过阈值
rule.recentValues.push(value);
if (rule.recentValues.length > triggerParam) {
rule.recentValues.shift(); // 保持最近N个值
}
if (rule.recentValues.length >= triggerParam) {
const avg = rule.recentValues.reduce((a, b) => a + b, 0) / rule.recentValues.length;
if (avg >= rule.threshold) {
shouldTrigger = true;
}
}
break;
}
// 保存更新的规则数据
saveEmailRules(getEmailRules().map(r => r.id === rule.id ? rule : r));
if (!shouldTrigger) continue;
// 发送邮件
try {

View File

@@ -1,8 +1,8 @@
[2026-04-23 23:25:57] ==================================================
[2026-04-23 23:25:57] 项目服务管理面板 v2.0.0 启动
[2026-04-23 23:25:57] 访问地址: http://localhost:19013
[2026-04-23 23:25:57] 进程PID: 1262750
[2026-04-23 23:25:57] ==================================================
[2026-04-23 23:57:38] ==================================================
[2026-04-23 23:57:38] 项目服务管理面板 v2.0.0 启动
[2026-04-23 23:57:38] 访问地址: http://localhost:19013
[2026-04-23 23:57:38] 进程PID: 1274690
[2026-04-23 23:57:38] ==================================================
* Serving Flask app 'app'
* Debug mode: off
WARNING: This is a development server. Do not use it in a production deployment. Use a production WSGI server instead.
@@ -10,20 +10,32 @@ WARNING: This is a development server. Do not use it in a production deployment.
* Running on http://127.0.0.1:19013
* Running on http://192.168.2.17:19013
Press CTRL+C to quit
127.0.0.1 - - [23/Apr/2026 23:26:02] "GET / HTTP/1.1" 200 -
127.0.0.1 - - [23/Apr/2026 23:26:03] "GET / HTTP/1.1" 200 -
192.168.2.14 - - [23/Apr/2026 23:26:04] "GET /api/projects HTTP/1.1" 200 -
127.0.0.1 - - [23/Apr/2026 23:26:06] "GET / HTTP/1.1" 200 -
192.168.2.8 - - [23/Apr/2026 23:26:08] "GET /api/projects HTTP/1.1" 200 -
127.0.0.1 - - [23/Apr/2026 23:26:13] "GET / HTTP/1.1" 200 -
192.168.2.14 - - [23/Apr/2026 23:26:14] "GET /api/projects HTTP/1.1" 200 -
127.0.0.1 - - [23/Apr/2026 23:26:16] "GET / HTTP/1.1" 200 -
192.168.2.8 - - [23/Apr/2026 23:26:18] "GET /api/projects HTTP/1.1" 200 -
127.0.0.1 - - [23/Apr/2026 23:26:23] "GET / HTTP/1.1" 200 -
192.168.2.14 - - [23/Apr/2026 23:26:24] "GET /api/projects HTTP/1.1" 200 -
127.0.0.1 - - [23/Apr/2026 23:26:26] "GET / HTTP/1.1" 200 -
192.168.2.8 - - [23/Apr/2026 23:26:28] "GET /api/projects HTTP/1.1" 200 -
127.0.0.1 - - [23/Apr/2026 23:26:28] "GET / HTTP/1.1" 200 -
192.168.2.8 - - [23/Apr/2026 23:26:30] "GET /api/projects HTTP/1.1" 200 -
127.0.0.1 - - [23/Apr/2026 23:26:33] "GET / HTTP/1.1" 200 -
192.168.2.14 - - [23/Apr/2026 23:26:34] "GET /api/projects HTTP/1.1" 200 -
127.0.0.1 - - [23/Apr/2026 23:57:42] "GET / HTTP/1.1" 200 -
192.168.2.14 - - [23/Apr/2026 23:57:43] "GET /api/projects HTTP/1.1" 200 -
127.0.0.1 - - [23/Apr/2026 23:57:45] "GET / HTTP/1.1" 200 -
192.168.2.8 - - [23/Apr/2026 23:57:47] "GET /api/projects HTTP/1.1" 200 -
127.0.0.1 - - [23/Apr/2026 23:57:52] "GET / HTTP/1.1" 200 -
192.168.2.14 - - [23/Apr/2026 23:57:53] "GET /api/projects HTTP/1.1" 200 -
127.0.0.1 - - [23/Apr/2026 23:57:55] "GET / HTTP/1.1" 200 -
192.168.2.8 - - [23/Apr/2026 23:57:57] "GET /api/projects HTTP/1.1" 200 -
127.0.0.1 - - [23/Apr/2026 23:58:02] "GET / HTTP/1.1" 200 -
127.0.0.1 - - [23/Apr/2026 23:58:02] "GET / HTTP/1.1" 200 -
192.168.2.14 - - [23/Apr/2026 23:58:03] "GET /api/projects HTTP/1.1" 200 -
192.168.2.8 - - [23/Apr/2026 23:58:04] "GET /api/projects HTTP/1.1" 200 -
127.0.0.1 - - [23/Apr/2026 23:58:05] "GET / HTTP/1.1" 200 -
192.168.2.8 - - [23/Apr/2026 23:58:07] "GET /api/projects HTTP/1.1" 200 -
127.0.0.1 - - [23/Apr/2026 23:58:12] "GET / HTTP/1.1" 200 -
192.168.2.14 - - [23/Apr/2026 23:58:13] "GET /api/projects HTTP/1.1" 200 -
127.0.0.1 - - [23/Apr/2026 23:58:15] "GET / HTTP/1.1" 200 -
192.168.2.8 - - [23/Apr/2026 23:58:17] "GET /api/projects HTTP/1.1" 200 -
127.0.0.1 - - [23/Apr/2026 23:58:19] "GET /api/system/processes?limit=5 HTTP/1.1" 200 -
127.0.0.1 - - [23/Apr/2026 23:58:22] "GET / HTTP/1.1" 200 -
192.168.2.14 - - [23/Apr/2026 23:58:23] "GET /api/projects HTTP/1.1" 200 -
127.0.0.1 - - [23/Apr/2026 23:58:25] "GET / HTTP/1.1" 200 -
192.168.2.8 - - [23/Apr/2026 23:58:27] "GET /api/projects HTTP/1.1" 200 -
127.0.0.1 - - [23/Apr/2026 23:58:32] "GET / HTTP/1.1" 200 -
127.0.0.1 - - [23/Apr/2026 23:58:32] "GET / HTTP/1.1" 200 -
192.168.2.14 - - [23/Apr/2026 23:58:33] "GET /api/projects HTTP/1.1" 200 -
192.168.2.8 - - [23/Apr/2026 23:58:34] "GET /api/projects HTTP/1.1" 200 -
127.0.0.1 - - [23/Apr/2026 23:58:35] "GET / HTTP/1.1" 200 -
192.168.2.8 - - [23/Apr/2026 23:58:37] "GET /api/projects HTTP/1.1" 200 -