'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 → 6061,v2 → 6062 * * @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' ? 6061 : 6062; 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"', '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"', ].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 / /api/docs /internal/v1/gateway /system; do', ' if [ "$path" = "/internal/v1/gateway" ] || [ "$path" = "/system" ]; then', ' code=$(curl -sS -o /dev/null -w "%{http_code}" -X POST "http://127.0.0.1:$PORT$path" || true)', ' else', ' code=$(curl -sS -o /dev/null -w "%{http_code}" "http://127.0.0.1:$PORT$path" || true)', ' fi', ' 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} methodName - method 名称 * @param {string} payloadText - 请求体 JSON 字符串 * @return {string} 网关接口响应内容 */ function gatewayProbe(config, methodName, payloadText) { if (!methodName) { throw new Error('gateway-probe 需要 method 名称'); } const { port } = getActivePortInfo(config); const payload = payloadText && payloadText.trim() ? payloadText : '{}'; const remoteScript = [ 'set -euo pipefail', `METHOD_NAME=${quoteForBash(methodName)}`, `PAYLOAD=${quoteForBash(payload)}`, `PORT=${port}`, 'timestamp=$(date +%s)', 'curl -sS -X POST "http://127.0.0.1:$PORT/internal/v1/gateway?method=$METHOD_NAME&v=1×tamp=$timestamp" -H "Content-Type: text/plain" --data "$PAYLOAD"', ].join('\n'); return runSsh(config, remoteScript, { stdio: 'pipe' }).trim(); } /** * 显示远端 current.md 内容及当前活跃端口信息 * * @param {object} config - 部署配置对象 */ function showActiveInfo(config) { let activeInfo; try { activeInfo = getActivePortInfo(config); } catch (err) { console.log(`[CURRENT_MD] 读取失败: ${err.message}`); console.log(''); return; } console.log(`[CURRENT_MD] 内容: ${activeInfo.rawContent}`); console.log(`[ACTIVE] 端口: ${activeInfo.port} (${activeInfo.version})`); console.log(''); } function main() { const options = parseArgs(process.argv.slice(2)); const config = loadDeployConfig(options.envName); if (options.command === 'inspect') { showActiveInfo(config); console.log(inspectState(config)); return; } if (options.command === 'smoke') { showActiveInfo(config); console.log(`[SMOKE]`); console.log(smokeRoutes(config)); return; } if (options.command === 'verify') { showActiveInfo(config); console.log(inspectState(config)); console.log(''); console.log('[SMOKE]'); console.log(smokeRoutes(config)); return; } if (options.command === 'cleanup-backups') { console.log(cleanupBackups(config, options.args)); return; } if (options.command === 'gateway-probe') { const methodName = options.args[0]; const payloadText = options.args[1] || '{}'; showActiveInfo(config); console.log(`[GATEWAY_PROBE] method=${methodName}`); console.log(gatewayProbe(config, methodName, payloadText)); return; } throw new Error(`不支持的命令: ${options.command}`); } main();