'use strict'; /** * 后端回滚脚本(双实例蓝绿:切回另一套版本目录,无需重新构建/上传) * * npm run rollback # 回滚到上一个版本(v1 ↔ v2) * npm run rollback -- --to=v1 # 指定切回某个版本 * * 流程:启动目标版本实例 → 健康检查通过 → 切换 Nginx upstream → 记录 current.md → 停止当前实例 * 目标版本目录不可用(未发布过)时会直接报错,当前实例不受影响。 */ const { VERSIONS, buildFreePortLines, buildHealthCheckLines, buildNginxSwitchLines, buildScopedEggStopLines, buildStartInstanceLines, ensureCommandAvailable, loadDeployConfig, otherVersion, portOf, quoteForBash, readRemoteCurrentVersion, runSsh, } = require('./deploy-lib.cjs'); /** * 解析 --to=v1|v2 参数 * @param {String[]} argv 参数数组 * @return {String} 目标版本(未指定时返回空字符串) */ function parseTargetArg(argv) { const arg = argv.find(item => item.startsWith('--to=')); if (!arg) return ''; const value = arg.slice('--to='.length).trim(); if (!VERSIONS.includes(value)) { throw new Error(`--to 取值无效: ${value}(支持 v1 / v2)`); } return value; } function main() { const envName = process.argv[2] || 'production'; const config = loadDeployConfig(envName); ensureCommandAvailable('ssh', '请先安装 OpenSSH Client 并确保 ssh 在 PATH 中。'); const currentVersion = readRemoteCurrentVersion(config); if (!currentVersion) { throw new Error(`远端 ${config.deployRoot}/current.md 不存在或为空,没有可回滚的版本(请先执行 npm run deploy)。`); } const targetVersion = parseTargetArg(process.argv.slice(3)) || otherVersion(currentVersion); if (targetVersion === currentVersion) { throw new Error(`目标版本与当前活跃版本相同(${targetVersion}),无需回滚。`); } const currentPort = portOf(config, currentVersion); const targetPort = portOf(config, targetVersion); const currentDir = `${config.deployRoot}/${currentVersion}`; const targetDir = `${config.deployRoot}/${targetVersion}`; const startLogPath = `/tmp/oms-${targetVersion}-start.log`; console.log(`当前活跃版本: ${currentVersion}(端口 ${currentPort})`); console.log(`回滚目标: ${targetVersion} → ${targetDir}(端口 ${targetPort})`); // 1. 校验目标版本可用;缺依赖时补装 runSsh(config, [ 'set -euo pipefail', `TARGET_DIR=${quoteForBash(targetDir)}`, 'if [ ! -f "$TARGET_DIR/package.json" ]; then', ' echo "目标版本目录不可用:$TARGET_DIR/package.json 不存在(该版本可能尚未发布过)" >&2', ' exit 1', 'fi', 'if [ ! -d "$TARGET_DIR/node_modules" ]; then', ' echo "目标版本缺少 node_modules,先安装依赖..."', ` ( cd "$TARGET_DIR" && ${config.installCommand} )`, 'fi', ].join('\n')); // 2. 释放目标端口并启动目标实例 runSsh(config, [ 'set -euo pipefail', ...buildFreePortLines(targetPort) ].join('\n')); runSsh(config, [ 'set -euo pipefail', ...buildStartInstanceLines(targetDir, config.startCommand, startLogPath), ].join('\n')); // 3. 健康检查(失败则清理刚启动的实例,当前实例继续服务) try { runSsh(config, [ 'set -euo pipefail', ...buildHealthCheckLines(targetPort, config.healthCheckPath, targetVersion), ].join('\n')); } catch (err) { console.error(`[ERROR] 回滚目标健康检查失败: ${err.message}`); console.error(`[ERROR] 回滚中止(未切换 Nginx),请查看启动日志 ${startLogPath}`); try { runSsh(config, [ 'set -euo pipefail', ...buildScopedEggStopLines(targetDir, 'STOP_ROLLBACK_TARGET'), ].join('\n')); } catch (killErr) { console.error(`[ERROR] 清理回滚目标实例出错: ${killErr.message}`); } console.error(`[ERROR] 当前实例(${currentVersion})仍在服务,线上不受影响`); process.exit(1); } // 4. 切换 Nginx upstream const upstreamPath = `${config.deployRoot}/nginx-upstream.conf`; try { runSsh(config, [ 'set -euo pipefail', ...buildNginxSwitchLines(upstreamPath, targetPort) ].join('\n')); } catch (err) { console.warn(`[WARN] Nginx upstream 切换失败: ${err.message}`); console.warn(`[WARN] 请人工确认 ${upstreamPath} 内容并执行 nginx -t && nginx -s reload`); } // 5. 记录 current.md 并停止原实例 runSsh(config, [ 'set -euo pipefail', `printf '%s\\n' ${quoteForBash(targetVersion)} > ${quoteForBash(`${config.deployRoot}/current.md`)}`, ...buildScopedEggStopLines(currentDir, 'STOP_ROLLED_BACK'), `echo "current.md 已更新为 ${targetVersion}"`, ].join('\n')); console.log(`回滚完成: 线上已切回 ${targetVersion}(端口 ${targetPort})`); console.log(`如需再次前进,执行 npm run rollback -- --to=${currentVersion}`); } main();