1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351
| const express = require("express"); const { exec } = require("child_process"); const fs = require("fs"); const path = require("path"); const os = require("os"); const { createProxyMiddleware } = require("http-proxy-middleware"); // 引入代理插件 const app = express();
// ================== 配置区域 ================== const port = process.env.PORT || 3000; const USER = "username"; const TARGET_PORT = "30345"; const WORK_DIR = `/home/${USER}/gpt-load`; const CMD = `./gpt-load-server`; const PROCESS_NAME = "gpt-load-server";
// 系统资源配额(根据您的实际环境配置) const RESOURCE_QUOTAS = { disk: { total: 3.00 * 1024 * 1024 * 1024, // 3GB in bytes unit: 'GB' }, processes: { max: 20 }, memory: { total: 512, // MB unit: 'MB' } };
// 日志文件 const LOG_FILE = path.join(__dirname, 'keeper.log'); // 暂停开关 const STOP_FILE = path.join(__dirname, 'stop.txt'); // ============================================
function log(message) { const time = new Date().toLocaleString(); const logMsg = `[${time}] ${message}\n`; try { fs.appendFileSync(LOG_FILE, logMsg); } catch (e) {} console.log(logMsg.trim()); }
// 缓存系统信息以减少重复计算 let systemInfoCache = null; let lastSystemInfoTime = 0; const CACHE_DURATION = 30000; // 30秒缓存
// 获取系统资源信息(适用于 serv00 容器环境) function getSystemInfo() { const now = Date.now();
// 如果缓存有效,直接返回 if (systemInfoCache && (now - lastSystemInfoTime) < CACHE_DURATION) { return systemInfoCache; }
try { // 获取配置的总内存配额 const quotaTotal = RESOURCE_QUOTAS.memory.total * 1024 * 1024; // 转换为字节 let actualUsed = 0; let detectionMethod = '估算';
// 方法1: 尝试通过 ps 命令获取当前用户所有进程的内存总和(FreeBSD) // RSS 字段表示常驻内存大小 exec(`ps -U ${process.env.USER || USER} -o rss= 2>/dev/null | awk '{s+=$1} END {print s}'`, (err, stdout) => { if (!err && stdout && !isNaN(parseFloat(stdout))) { // ps 返回的是 KB,转换为字节 const psMem = parseFloat(stdout.trim()) * 1024; if (psMem > 0) { actualUsed = psMem; detectionMethod = 'ps 进程汇总'; } }
// 如果 ps 方法失败,回退到当前进程 + 预估 if (actualUsed === 0) { const processMem = process.memoryUsage(); actualUsed = processMem.rss; detectionMethod = '当前进程估算'; }
// 转换为 MB const usedMemMB = actualUsed / 1024 / 1024; const totalMemMB = quotaTotal / 1024 / 1024; const freeMemMB = Math.max(0, totalMemMB - usedMemMB); const usagePercent = ((usedMemMB / totalMemMB) * 100).toFixed(1);
const sysInfo = { timestamp: new Date().toLocaleString(), memory: { total: totalMemMB.toFixed(1) + ' MB', used: usedMemMB.toFixed(1) + ' MB', free: freeMemMB.toFixed(1) + ' MB', quotaUsagePercent: usagePercent + '%', quota: `${usedMemMB.toFixed(1)}/${RESOURCE_QUOTAS.memory.total} ${RESOURCE_QUOTAS.memory.unit} (${detectionMethod})` } };
// 更新缓存 systemInfoCache = sysInfo; lastSystemInfoTime = now;
return sysInfo; });
// 同步返回(首次调用可能为空) const processMem = process.memoryUsage(); actualUsed = processMem.rss * 2; // 临时估算,下次缓存会有准确值
const usedMemMB = actualUsed / 1024 / 1024; const totalMemMB = quotaTotal / 1024 / 1024; const usagePercent = ((usedMemMB / totalMemMB) * 100).toFixed(1);
const sysInfo = { timestamp: new Date().toLocaleString(), memory: { total: totalMemMB.toFixed(1) + ' MB', used: usedMemMB.toFixed(1) + ' MB', free: (totalMemMB - usedMemMB).toFixed(1) + ' MB', quotaUsagePercent: usagePercent + '%', quota: `${usedMemMB.toFixed(1)}/${RESOURCE_QUOTAS.memory.total} ${RESOURCE_QUOTAS.memory.unit} (初始化中...)` } };
systemInfoCache = sysInfo; lastSystemInfoTime = now;
return sysInfo; } catch (error) { return { error: 'Memory detection failed: ' + error.message, timestamp: new Date().toLocaleString() }; } }
// 读取最近的 keeper.log 内容(限制行数以节省资源) function getRecentLogs(maxLines = 50) { try { if (!fs.existsSync(LOG_FILE)) { return ['Log file not found']; } const content = fs.readFileSync(LOG_FILE, 'utf8'); const lines = content.split('\n').filter(line => line.trim() !== ''); // 返回最后 maxLines 行 return lines.slice(-maxLines); } catch (error) { return [`Error reading log: ${error.message}`]; } }
function keepAlive() { if (fs.existsSync(STOP_FILE)) { log("🛑 Maintenance Mode Active (stop.txt found). Skipping checks."); return; }
exec(`sockstat -4 -l -P tcp | grep ${TARGET_PORT}`, (err, stdout) => { if (stdout && stdout.includes(TARGET_PORT)) { log(`Port ${TARGET_PORT} is UP. Service is healthy.`); } else { log(`Port ${TARGET_PORT} is DOWN. Initiating restart sequence...`); log(`Cleaning up any stuck '${PROCESS_NAME}' processes...`); exec(`pkill -f "${PROCESS_NAME}"`, () => { log(`Starting new instance...`); exec(`cd ${WORK_DIR} && ${CMD} > gpt-load.log 2>&1 &`, (startErr) => { if (startErr) log(`Start failed: ${startErr}`); else log(`Start command sent successfully.`); }); }); } }); }
// 启动保活逻辑 log("Keeper Service Started."); keepAlive(); setInterval(keepAlive, 60 * 1000);
// ================== 路由配置 ==================
// 1. 特殊页面:查看保活状态 (访问 /keeper-status) app.get("/keeper-status", (req, res) => { const sysInfo = getSystemInfo(); const logs = getRecentLogs(30); // 显示最近30行日志 let html = ` <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Keeper Status Dashboard</title> <style> body { font-family: Arial, sans-serif; margin: 20px; background-color: #f5f5f5; } .container { max-width: 1200px; margin: 0 auto; } .card { background: white; border-radius: 8px; padding: 20px; margin-bottom: 20px; box-shadow: 0 2px 4px rgba(0,0,0,0.1); } .status-header { text-align: center; color: #333; } .status-indicator { display: inline-block; padding: 10px 20px; border-radius: 20px; font-weight: bold; margin: 10px 0; } .status-active { background-color: #d4edda; color: #155724; } .status-maintenance { background-color: #fff3cd; color: #856404; } .grid { display: grid; grid-template-columns: repeat(auto-fit, minmax(300px, 1fr)); gap: 20px; } .resource-card { background: #f8f9fa; border-left: 4px solid #007bff; } .log-container { background: #2d2d2d; color: #f8f8f2; padding: 15px; border-radius: 5px; font-family: 'Courier New', monospace; font-size: 12px; max-height: 400px; overflow-y: auto; } .log-entry { margin: 2px 0; } .log-error { color: #ff6b6b; } .log-success { color: #51cf66; } .log-warning { color: #ffd43b; } .refresh-btn { background: #007bff; color: white; border: none; padding: 10px 20px; border-radius: 5px; cursor: pointer; margin: 10px 5px; } .refresh-btn:hover { background: #0056b3; } h2 { color: #333; border-bottom: 2px solid #007bff; padding-bottom: 10px; } .metric { margin: 10px 0; } .metric-label { font-weight: bold; color: #555; } .metric-value { color: #007bff; font-family: 'Courier New', monospace; } .quota-info { font-size: 12px; color: #666; margin-top: 5px; } .usage-bar { height: 8px; background-color: #e9ecef; border-radius: 4px; margin: 8px 0; overflow: hidden; } .usage-fill { height: 100%; background-color: #28a745; transition: width 0.3s ease; } .usage-warning { background-color: #ffc107; } .usage-danger { background-color: #dc3545; } </style> </head> <body> <div class="container"> <div class="card"> <h1 class="status-header">keeper Status Dashboard</h1> <div class="status-indicator ${fs.existsSync(STOP_FILE) ? 'status-maintenance' : 'status-active'}"> ${fs.existsSync(STOP_FILE) ? '🛑 MAINTENANCE MODE' : '✅ ACTIVE MODE'} </div> <p>Monitoring port: <strong>${TARGET_PORT}</strong></p> <p>Last updated: <strong>${sysInfo.timestamp}</strong></p> <button class="refresh-btn" onclick="location.reload()">Refresh Status</button> <button class="refresh-btn" onclick="window.location.href='/'">Go to Main Site</button> </div> `;
// 系统资源信息(仅显示内存) if (!sysInfo.error) { html += ` <div class="grid"> <div class="card resource-card"> <h2>💾 Memory Information</h2> <div class="metric"> <span class="metric-label">Total Memory:</span> <span class="metric-value">${sysInfo.memory.total}</span> </div> <div class="metric"> <span class="metric-label">Used Memory:</span> <span class="metric-value">${sysInfo.memory.used}</span> </div> <div class="metric"> <span class="metric-label">Free Memory:</span> <span class="metric-value">${sysInfo.memory.free}</span> </div> <div class="metric"> <span class="metric-label">Quota Usage:</span> <span class="metric-value">${sysInfo.memory.quotaUsagePercent}</span> <div class="quota-info">Quota: ${sysInfo.memory.quota}</div> </div> <div class="usage-bar"> <div class="usage-fill ${parseFloat(sysInfo.memory.quotaUsagePercent) > 80 ? 'usage-warning' : parseFloat(sysInfo.memory.quotaUsagePercent) > 90 ? 'usage-danger' : ''}" style="width: ${parseFloat(sysInfo.memory.quotaUsagePercent)}%"></div> </div> </div> </div> `; } else { html += ` <div class="card"> <h2>⚠️ Memory Information Error</h2> <p>${sysInfo.error}</p> </div> `; }
// 日志显示 html += ` <div class="card"> <h2>📝 Recent Keeper Logs</h2> <div class="log-container"> `; logs.forEach(logEntry => { if (logEntry.trim()) { // 为不同类型的日志添加颜色 let logClass = 'log-entry'; if (logEntry.includes('ERROR') || logEntry.includes('FAILED')) { logClass += ' log-error'; } else if (logEntry.includes('SUCCESS') || logEntry.includes('UP') || logEntry.includes('healthy')) { logClass += ' log-success'; } else if (logEntry.includes('MAINTENANCE') || logEntry.includes('STOP')) { logClass += ' log-warning'; } html += `<div class="${logClass}">${logEntry}</div>`; } });
html += ` </div> </div> </div> </body> </html> `;
res.send(html); });
// 2. 反向代理:把所有其他请求转发给 gpt-load (30345) // 这样你直接访问域名,就等于访问了 30345,但不用担心代理节点屏蔽端口 app.use("/", createProxyMiddleware({ target: `http://127.0.0.1:${TARGET_PORT}`, changeOrigin: true, ws: true, // 支持 WebSocket (如果 gpt-load 需要) onError: (err, req, res) => { res.status(502).send(` <h1>502 Bad Gateway</h1> <p>Keeper is running, but gpt-load-server (Port ${TARGET_PORT}) seems down or starting.</p> <p>Check <a href="/keeper-status">/keeper-status</a> for details.</p> `); } }));
app.listen(port, () => log(`Keeper & Proxy listening on port ${port}`));
|