import crypto from 'node:crypto'; import http from 'node:http'; import https from 'node:https'; const panelURL = process.env.SEA_PANEL_URL?.trim(); const panelAPIKey = process.env.SEA_PANEL_API_KEY?.trim(); const insecureTLS = process.env.SEA_PANEL_TLS_INSECURE === 'true'; if (!panelURL || !panelAPIKey) process.exit(2); const base = new URL(panelURL); const client = base.protocol === 'https:' ? https : http; const agent = base.protocol === 'https:' ? new https.Agent({ rejectUnauthorized: !insecureTLS }) : undefined; const md5 = (value) => crypto.createHash('md5').update(value).digest('hex'); function panelForm(pathname, values) { const requestTime = Math.floor(Date.now() / 1000).toString(); const body = Buffer.from(new URLSearchParams({ ...values, request_time: requestTime, request_token: md5(requestTime + md5(panelAPIKey)) }).toString()); return new Promise((resolve, reject) => { const request = client.request(new URL(pathname, base), { method: 'POST', agent, timeout: 30_000, headers: { 'content-type': 'application/x-www-form-urlencoded', 'content-length': body.length } }, (response) => { let data = ''; response.setEncoding('utf8'); response.on('data', (chunk) => { data += chunk; }); response.on('end', () => { if (response.statusCode < 200 || response.statusCode > 299) return reject(new Error(`panel returned HTTP ${response.statusCode}`)); try { resolve(JSON.parse(data)); } catch { reject(new Error('panel returned non-JSON data')); } }); }); request.on('timeout', () => request.destroy(new Error('panel request timed out'))); request.on('error', reject); request.end(body); }); } const marker = `runtime-diagnose-${Date.now()}`; const shell = [ 'set -eo pipefail', "printf '%s\\n' '=== runtime directories ==='", "stat -Lc '%A %a %U:%G %n' /www/server/nodejs/vhost /www/server/nodejs/vhost/pids /www/server/nodejs/vhost/scripts /www/server/python_project /www/server/go_project /www/server/java_project 2>&1 || true", "find /www/server/nodejs/vhost/pids /www/server/nodejs/vhost/scripts -maxdepth 1 -type f -name 'sv*' -printf '%M %u:%g %p\\n' 2>/dev/null | tail -n 30 || true", "printf '%s\\n' '=== host processes ==='", "for host_dir in /www/wwwroot/seavHost/vHost/sv??????????; do test -d \"$host_dir\" || continue; host_name=\"${host_dir##*/}\"; ps -u \"$host_name\" -o user:16,pid,ppid,etimes,args --no-headers || true; done", "printf '%s\\n' '=== backend listeners ==='", "ss -lntp | grep -E ':(20[0-9]{3}|3[0-9]{4})\\b' || true", "printf '%s\\n' '=== control-plane non-PHP sites ==='", "mapfile -t control_db < <(python3 -c 'import json,re; d=json.load(open(\"/var/lib/sea-vhost/config.json\", encoding=\"utf-8\"))[\"database_dsn\"]; m=re.fullmatch(r\"([^:]+):([^@]+)@tcp\\\\(([^:]+):(\\\\d+)\\\\)/([^?]+)(?:\\\\?.*)?\", d); assert m; print(\"\\\\n\".join(m.groups()))')", "mysql_bin=\"$(command -v mysql || true)\"; if [[ -z \"$mysql_bin\" && -x /www/server/mysql/bin/mysql ]]; then mysql_bin=/www/server/mysql/bin/mysql; fi", "MYSQL_PWD=\"${control_db[1]}\" \"$mysql_bin\" --protocol=TCP --host=\"${control_db[2]}\" --port=\"${control_db[3]}\" --user=\"${control_db[0]}\" --database=\"${control_db[4]}\" --batch --skip-column-names --execute=\"SELECT id,project_id,runtime,status,backend_port,run_path,assigned_domain FROM sites WHERE runtime<>'PHP' ORDER BY id\" || true", "printf '%s\\n' '=== broker runtime registry ==='", "python3 -c 'import json; d=json.load(open(\"/var/lib/sea-vhost-panel/resources.json\")); print([(k,(v.get(\"runtime\") or {}).get(\"ProjectName\"),(v.get(\"runtime\") or {}).get(\"Runtime\")) for k,v in d.get(\"sites\",{}).items() if v.get(\"runtime\")])' 2>/dev/null || true", "printf '%s\\n' '=== recent broker messages ==='", "journalctl -u sea-vhost-panel-broker -n 10 --no-pager -o cat | tail -n 10 || true", "printf '%s\\n' '=== PHP identity state ==='", "stat -Lc '%A %a %U:%G %n' /var/lib/sea-vhost-agent /var/lib/sea-vhost-agent/php /run/sea-vhost-php /run/sea-vhost-php/* 2>&1 || true", "find /var/lib/sea-vhost-agent/php /run/sea-vhost-php -maxdepth 2 -printf '%M %u:%g %p\\n' 2>/dev/null | tail -n 80 || true", "for path in /www/wwwroot/seavHost/vHost/sv??????????/.sea-runtime/php; do test -e \"$path\" || continue; namei -l \"$path/fpm-error.log\" || true; getfacl -p \"$(dirname \"$path\")\" \"$path\" 2>/dev/null || true; done", "printf '%s\\n' '=== recent isolation-agent messages ==='", "journalctl -u sea-vhost-agent -n 25 --no-pager -o cat | tail -n 25 || true", `printf '%s\n' '${marker}'`, ].join('\n'); const task = await panelForm('/crontab', { action: 'AddCrontab', name: `Sea vHost runtime diagnose ${Date.now().toString().slice(-7)}`, type: 'month', where1: String((new Date().getUTCDate() + 6) % 28 + 1), where_hour: '0', where_minute: '0', user: 'root', urladdress: 'http://', save_local: '0', sType: 'toShell', sBody: shell, sName: 'Temporary read-only runtime diagnostics', save: '0', backupTo: 'localhost' }); const taskID = Number(task?.id); if ((task?.status !== true && task?.status !== 'true') || !Number.isSafeInteger(taskID)) throw new Error('panel rejected diagnostics task'); try { await panelForm('/crontab', { action: 'StartTask', id: String(taskID) }); let log = ''; for (let attempt = 0; attempt < 90; attempt += 1) { await new Promise((resolve) => setTimeout(resolve, 1000)); const result = await panelForm('/crontab', { action: 'GetLogs', id: String(taskID) }); log = typeof result?.msg === 'string' ? result.msg : typeof result === 'string' ? result : log; if (log.includes(marker)) break; } if (!log.includes(marker)) throw new Error('diagnostics did not complete'); console.log(log.trim()); } finally { try { await panelForm('/crontab', { action: 'DelCrontab', id: String(taskID) }); } catch { /* best effort */ } }