'use strict'; const { loadDeployConfig, quoteForBash, runSsh } = require('./deploy-lib.cjs'); const COMMANDS = new Set([ 'inspect', 'smoke', 'verify', 'cleanup-backups', 'gateway-probe' ]); /** * 解析命令行参数,返回环境名、命令及额外参数 * * @param {string[]} argv - 命令行参数数组 * @return {{ envName: string, command: string, args: string[] }} 解析后的选项对象 */ function parseArgs(argv) { const options = { envName: 'production', command: '', args: [], }; const tokens = [ ...argv ]; if (tokens.length === 0) { throw new Error('缺少命令: inspect | smoke | verify | cleanup-backups | gateway-probe'); } const first = tokens[0]; if (!COMMANDS.has(first)) { options.envName = first; tokens.shift(); } if (tokens.length === 0) { throw new Error('缺少命令: inspect | smoke | verify | cleanup-backups | gateway-probe'); } options.command = tokens[0]; options.args = tokens.slice(1); if (!COMMANDS.has(options.command)) { throw new Error(`不支持的命令: ${options.command}`); } return options; } /** * 通过 SSH 读取远端 current.md 文件,获取当前活跃端口 * v1 → 7071,v2 → 7072 * * @param {object} config - 部署配置对象 * @return {{ port: number, version: string, rawContent: string }} 活跃端口、版本标识及 current.md 原始内容 * @throws {Error} 如果读取失败或内容不是 v1/v2 */ function getActivePortInfo(config) { const currentMdPath = `${config.deployRoot}/current.md`; const remoteScript = [ 'set -euo pipefail', `cat ${quoteForBash(currentMdPath)} 2>/dev/null || true`, ].join('\n'); const output = runSsh(config, remoteScript, { stdio: 'pipe' }); const rawContent = String(output || '').trim(); if (!rawContent) { throw new Error( `无法读取远端 ${currentMdPath},内容为空或文件不存在。` ); } const version = rawContent.replace(/\r/g, '').trim(); if (version !== 'v1' && version !== 'v2') { throw new Error( `远端 current.md 内容无效: "${rawContent}",期望值为 v1 或 v2。文件路径: ${currentMdPath}` ); } const port = version === 'v1' ? 7071 : 7072; return { port, version, rawContent }; } /** * 通过 SSH 检查远端部署状态(state 目录、备份等) * * @param {object} config - 部署配置对象 * @return {string} SSH 远程执行输出 */ function inspectState(config) { const latestBackupFile = `${config.stateDir}/latest-backup.txt`; const remoteScript = [ 'set -euo pipefail', `STATE_DIR=${quoteForBash(config.stateDir)}`, `BACKUP_DIR=${quoteForBash(config.backupDir)}`, `LATEST_FILE=${quoteForBash(latestBackupFile)}`, 'printf "[STATE]\\n"', 'ls -la "$STATE_DIR" 2>/dev/null || echo EMPTY', 'printf "\\n[LATEST_BACKUP]\\n"', 'if [ -f "$LATEST_FILE" ]; then cat "$LATEST_FILE"; else echo MISSING; fi', 'printf "\\n[BACKUPS]\\n"', 'ls -1 "$BACKUP_DIR" 2>/dev/null || echo EMPTY', 'printf "\\n[INSTANCES]\\n"', 'ls -la "$DEPLOY_ROOT/v1" 2>/dev/null | head -3 || echo "v1 EMPTY"', 'ls -la "$DEPLOY_ROOT/v2" 2>/dev/null | head -3 || echo "v2 EMPTY"', 'printf "\\n[CURRENT_MD]\\n"', 'cat "$DEPLOY_ROOT/current.md" 2>/dev/null || echo MISSING', ].join('\n'); return runSsh(config, remoteScript, { stdio: 'pipe' }).trim(); } /** * 对当前活跃端口的关键路由执行冒烟探测 * * @param {object} config - 部署配置对象 * @return {string} 各路由的 HTTP 状态码输出 */ function smokeRoutes(config) { const { port } = getActivePortInfo(config); const remoteScript = [ 'set -euo pipefail', `PORT=${port}`, 'for path in /; do', ' code=$(curl -sS -o /dev/null -w "%{http_code}" "http://127.0.0.1:$PORT$path" || true)', ' printf "%s %s\\n" "$path" "$code"', 'done', ].join('\n'); return runSsh(config, remoteScript, { stdio: 'pipe' }).trim(); } /** * 清理远端备份目录中指定的备份文件 * * @param {object} config - 部署配置对象 * @param {string[]} names - 要清理的备份文件名列表 * @return {string} 清理结果输出 */ function cleanupBackups(config, names) { if (!names.length) { throw new Error('cleanup-backups 需要至少一个备份文件名'); } const remoteScript = [ 'set -euo pipefail', `BACKUP_DIR=${quoteForBash(config.backupDir)}`, ...names.map((name, index) => `FILE_${index}=${quoteForBash(name)}`), ...names.map((_, index) => `if [ -f "$BACKUP_DIR/$FILE_${index}" ]; then rm -f "$BACKUP_DIR/$FILE_${index}"; echo "REMOVED $FILE_${index}"; else echo "MISS $FILE_${index}"; fi`), ].join('\n'); return runSsh(config, remoteScript, { stdio: 'pipe' }).trim(); } /** * 对指定端口做基础连通性探测,用于故障排查 * * @param {object} config - 部署配置对象 * @param {string} probePort - 目标端口号(字符串),为空则探测当前活跃端口 * @return {string} 探测结果输出 */ function gatewayProbe(config, probePort) { let targetPort; if (probePort && /^\d+$/.test(probePort)) { targetPort = Number(probePort); } else { targetPort = getActivePortInfo(config).port; } const remoteScript = [ 'set -euo pipefail', `PORT=${targetPort}`, 'echo "[GATEWAY_PROBE] port=$PORT"', 'if curl -fsS --connect-timeout 2 --max-time 4 "http://127.0.0.1:$PORT/" >/dev/null 2>&1; then', ' echo "GATEWAY_OK"', 'else', ' echo "GATEWAY_FAIL"', 'fi', ].join('\n'); return runSsh(config, remoteScript, { stdio: 'pipe' }).trim(); } function main() { const options = parseArgs(process.argv.slice(2)); const config = loadDeployConfig(options.envName); switch (options.command) { case 'inspect': console.log(inspectState(config)); break; case 'smoke': console.log(smokeRoutes(config)); break; case 'verify': { const activeInfo = getActivePortInfo(config); console.log(`ACTIVE_VERSION=${activeInfo.version}`); console.log(`ACTIVE_PORT=${activeInfo.port}`); break; } case 'cleanup-backups': console.log(cleanupBackups(config, options.args)); break; case 'gateway-probe': console.log(gatewayProbe(config, options.args[0] || '')); break; default: throw new Error(`不支持的命令: ${options.command}`); } } main();