'use strict'; const fs = require('node:fs'); const path = require('node:path'); const { ROOT, buildArchive, buildPinnedConfigGuardLines, buildRemoteCleanupGuard, ensureCommandAvailable, getNowStamp, loadDeployConfig, quoteForBash, runCommand, runScp, runSsh, } = require('./deploy-lib.cjs'); /** * 通过 SSH 读取远端 current.md 文件,获取当前活跃版本标识(v1 或 v2) * * @param {object} config - 部署配置对象 * @param {string} deployRoot - 远端部署根目录,如 /www/wwwroot/qimen * @return {string} 当前活跃版本标识,如 'v1' 或 'v2' * @throws {Error} 如果读取失败或内容无效 */ function readRemoteCurrentVersion(config, deployRoot) { const currentMdPath = `${deployRoot}/current.md`; const script = `cat ${quoteForBash(currentMdPath)} 2>/dev/null || true`; const output = runSsh(config, script, { stdio: 'pipe' }); const rawVersion = String(output || '').trim(); if (!rawVersion) { throw new Error( `无法读取远端当前版本文件: ${currentMdPath}。请确保远端已存在 /www/wwwroot/qimen/current.md 且内容为 v1 或 v2。` ); } const normalized = rawVersion.replace(/\r/g, '').trim(); if (normalized !== 'v1' && normalized !== 'v2') { throw new Error( `远端 current.md 内容无效: "${rawVersion}",期望值为 v1 或 v2。文件路径: ${currentMdPath}` ); } return normalized; } /** * 根据当前活跃版本确定目标部署目录(另一个实例目录) * * @param {string} currentVersion - 当前活跃版本,'v1' 或 'v2' * @param {string} deployRoot - 远端部署根目录,如 /www/wwwroot/qimen * @return {string} 目标部署目录,如 /www/wwwroot/qimen/v2 */ function resolveTargetDir(currentVersion, deployRoot) { if (currentVersion === 'v1') { return `${deployRoot}/v2`; } return `${deployRoot}/v1`; } /** * 根据当前活跃版本推导目标版本标识(v1 ↔ v2 互换) * * @param {string} currentVersion - 当前活跃版本,'v1' 或 'v2' * @return {string} 目标版本标识,'v1' 或 'v2' */ function resolveTargetVersion(currentVersion) { if (currentVersion === 'v1') { return 'v2'; } return 'v1'; } /** * 根据版本标识返回对应监听端口(v1 → 6061,v2 → 6062) * * @param {string} targetVersion - 目标版本标识,'v1' 或 'v2' * @return {number} 对应端口号 */ function getTargetPort(targetVersion) { if (targetVersion === 'v1') { return 6061; } return 6062; } function main() { const envName = process.argv[2] || 'production'; const config = loadDeployConfig(envName); ensureCommandAvailable('git', '请先安装 Git 并确保 git 在 PATH 中。'); ensureCommandAvailable('tar', '请先安装 tar,Windows 10/11 通常已内置 bsdtar。'); ensureCommandAvailable('ssh', '请先安装 OpenSSH Client 并确保 ssh 在 PATH 中。'); ensureCommandAvailable('scp', '请先安装 OpenSSH Client 并确保 scp 在 PATH 中。'); // 1. 读取远端 current.md,确定目标目录 const currentVersion = readRemoteCurrentVersion(config, config.deployRoot); const targetDir = resolveTargetDir(currentVersion, config.deployRoot); console.log(`远端当前活跃版本: ${currentVersion},目标部署目录: ${targetDir}`); // 2. 本地打包(不变) const stamp = getNowStamp(); const packageJson = JSON.parse(fs.readFileSync(path.join(ROOT, 'package.json'), 'utf8')); const packageVersion = String(packageJson.version || '0.0.0'); const gitCommitShort = runCommand('git', [ 'rev-parse', '--short', 'HEAD' ]); const releaseVersion = `v${packageVersion}-${stamp}-${gitCommitShort}`; const { archivePath } = buildArchive(stamp, config); const remoteArchive = `${config.incomingDir}/release-${stamp}.tar.gz`; // 3. 远端创建目录结构(目标目录 + incoming 目录) const setupScript = [ 'set -euo pipefail', `mkdir -p ${quoteForBash(targetDir)} ${quoteForBash(config.incomingDir)}`, ].join('\n'); runSsh(config, setupScript); console.log(`远端目录已就绪: ${targetDir}`); // 4. SCP 上传 tar.gz 到远端 incoming 目录 runScp(config, archivePath, remoteArchive); console.log(`发布包已上传到远端: ${remoteArchive}`); // 4.5 推导目标版本标识与端口(供固定文件保护暂存目录命名与后续切换使用) const targetVersion = resolveTargetVersion(currentVersion); const targetPort = getTargetPort(targetVersion); // 5. 在目标目录清理旧代码、解压、安装依赖 // 固定文件保护:warehouse-cert-sync 双环境配置由服务器独立管理(发布包内已 // 固定排除),清理前暂存目标目录既有副本、解压后放回,防止被覆盖/删除。 const pinnedStashDir = `/tmp/wms-pinned-${targetVersion}`; const pinnedGuard = buildPinnedConfigGuardLines('TARGET_DIR', 'PINNED_DIR'); const cleanupGuard = buildRemoteCleanupGuard(config.sharedDirs, config.preserveDirs); const remoteScript = [ 'set -euo pipefail', `TARGET_DIR=${quoteForBash(targetDir)}`, `REMOTE_ARCHIVE=${quoteForBash(remoteArchive)}`, `PINNED_DIR=${quoteForBash(pinnedStashDir)}`, ...pinnedGuard.stash, // 进入目标目录,清理旧代码文件(保留 node_modules、logs、run、temp、.deploy 等运行时/状态目录) 'cd "$TARGET_DIR"', `find . -mindepth 1 -maxdepth 1 ${cleanupGuard} -exec rm -rf {} +`, // 解压发布包 'tar -xzf "$REMOTE_ARCHIVE" -C "$TARGET_DIR"', 'rm -f "$REMOTE_ARCHIVE"', // 解压后放回固定保护的配置文件(发布包内已固定排除,不会冲突) ...pinnedGuard.restore, // 在目标目录安装生产依赖 'npm install --production', ].join('\n'); runSsh(config, remoteScript); console.log(`远端目标目录已清理、解压并安装依赖: ${targetDir}`); // 启动日志路径 const startLogPath = `/tmp/wms-${targetVersion}-start.log`; const currentMdPath = `${config.deployRoot}/current.md`; // 5.5. 强制清理目标端口残留进程,防止端口占用导致启动失败 const killPortScript = [ 'set -euo pipefail', `TARGET_PORT=${targetPort}`, 'PORT_PID=$(ss -tlnp 2>/dev/null | awk -v p=":$TARGET_PORT " \'index($0, p) { print $0 }\' | grep -oP \'pid=\\K[0-9]+\' | head -1 || true)', 'if [ -n "$PORT_PID" ]; then', ' echo "检测到端口 $TARGET_PORT 被进程 $PORT_PID 占用,发送优雅停止信号..."', ' kill "$PORT_PID" 2>/dev/null || true', ' sleep 30', ' PORT_PID_CHECK=$(ss -tlnp 2>/dev/null | awk -v p=":$TARGET_PORT " \'index($0, p) { print $0 }\' | grep -oP \'pid=\\K[0-9]+\' | head -1 || true)', ' if [ -n "$PORT_PID_CHECK" ]; then', ' echo "[WARN] 端口 $TARGET_PORT 仍有残留进程 $PORT_PID_CHECK,强制停止..."', ' kill -9 "$PORT_PID_CHECK" 2>/dev/null || true', ' fuser -k "$TARGET_PORT/tcp" 2>/dev/null || true', ' fi', ' echo "端口 $TARGET_PORT 已释放"', 'else', ' echo "端口 $TARGET_PORT 空闲,无需清理"', 'fi', ].join('\n'); try { const killPortOutput = runSsh(config, killPortScript, { stdio: 'pipe' }); console.log(String(killPortOutput || '').trim()); } catch (err) { console.warn(`[WARN] 端口 ${targetPort} 清理失败: ${err.message}`); } // 6. 更新远端 current.md 并启动新实例 const switchAndStartScript = [ 'set -euo pipefail', // 更新 current.md 指向新版本 `printf '%s\\n' ${quoteForBash(targetVersion)} > ${quoteForBash(currentMdPath)}`, // 在目标目录后台启动 Egg.js 进程 `cd ${quoteForBash(targetDir)}`, `nohup bash -lc 'npm start' > ${quoteForBash(startLogPath)} 2>&1 &`, `echo "已更新 current.md -> ${targetVersion},已在 ${targetDir} 启动新实例,启动日志: ${startLogPath}"`, ].join('\n'); const switchOutput = runSsh(config, switchAndStartScript, { stdio: 'pipe' }); console.log(String(switchOutput || '').trim()); // 6.5. 健康检查新实例(curl 循环等待,最多 20 秒) const oldDir = `${config.deployRoot}/${currentVersion}`; const healthCheckScript = [ 'set -euo pipefail', `TARGET_PORT=${targetPort}`, 'for attempt in $(seq 1 10); do', ' if curl -fsS --connect-timeout 2 --max-time 3 "http://127.0.0.1:$TARGET_PORT/" >/dev/null 2>&1; then', ` echo "新实例 (${targetVersion}) 健康检查通过 (端口 $TARGET_PORT)"`, ' break', ' fi', ' if [ "$attempt" -eq 10 ]; then', ` echo "新实例 (${targetVersion}) 健康检查超时 (端口 $TARGET_PORT)" >&2`, ' exit 1', ' fi', ' sleep 2', 'done', ].join('\n'); try { const healthOutput = runSsh(config, healthCheckScript, { stdio: 'pipe' }); console.log(String(healthOutput || '').trim()); } catch (err) { // 健康检查失败 → 不做切换,回滚 current.md 并清理失败的新实例 console.error(`[ERROR] 新实例健康检查失败 (20s 超时): ${err.message}`); console.error(`[ERROR] 发布中止:不切换 Nginx upstream,不停旧实例。可检查启动日志 ${startLogPath}`); // 回滚:将 current.md 恢复为旧版本 const revertCurrentMdScript = [ 'set -euo pipefail', `printf '%s\\n' ${quoteForBash(currentVersion)} > ${quoteForBash(currentMdPath)}`, `echo "已回滚 current.md -> ${currentVersion}"`, ].join('\n'); try { const revertOutput = runSsh(config, revertCurrentMdScript, { stdio: 'pipe' }); console.log(String(revertOutput || '').trim()); } catch (revertErr) { console.error(`[ERROR] 回滚 current.md 失败: ${revertErr.message}`); } // 清理:杀死启动失败的新实例进程 const killNewScript = [ 'set -euo pipefail', `NEW_DIR=${quoteForBash(targetDir)}`, `NEW_VERSION=${quoteForBash(targetVersion)}`, 'NEW_PIDS=$(ps -eo pid=,args= | awk -v root="$NEW_DIR" \'index($0, root) && $2 ~ /node$/ { print $1 }\')', 'if [ -n "$NEW_PIDS" ]; then', ' echo "正在清理失败的新实例 ($NEW_VERSION): $NEW_PIDS"', ' kill $NEW_PIDS || true', ' sleep 2', ' NEW_PIDS_REMAIN=$(ps -eo pid=,args= | awk -v root="$NEW_DIR" \'index($0, root) && $2 ~ /node$/ { print $1 }\')', ' if [ -n "$NEW_PIDS_REMAIN" ]; then', ' echo "新实例仍有残留进程,强制停止: $NEW_PIDS_REMAIN"', ' kill -9 $NEW_PIDS_REMAIN || true', ' fi', ' echo "失败的新实例 ($NEW_VERSION) 已清理"', 'else', ' echo "未找到新实例 ($NEW_VERSION) 进程,无需清理"', 'fi', ].join('\n'); try { const killOutput = runSsh(config, killNewScript, { stdio: 'pipe' }); console.log(String(killOutput || '').trim()); } catch (killErr) { console.error(`[ERROR] 清理失败新实例进程出错: ${killErr.message}`); } console.error(`[ERROR] 发布失败: ${envName} -> ${config.username}@${config.host}:${targetDir}`); console.error(`[ERROR] 旧实例 (${currentVersion}) 仍在运行,线上服务不受影响`); process.exit(1); } // 6.55. 切换 Nginx upstream 端口并 reload(仅在健康检查通过后执行) const nginxUpstreamPath = `${config.deployRoot}/nginx-upstream.conf`; const switchNginxScript = [ 'set -euo pipefail', `printf 'proxy_pass http://127.0.0.1:%s;\\n' ${targetPort} > ${quoteForBash(nginxUpstreamPath)}`, 'nginx -t && nginx -s reload', `echo "Nginx upstream 已切换至 127.0.0.1:${targetPort}"`, ].join('\n'); try { const nginxOutput = runSsh(config, switchNginxScript, { stdio: 'pipe' }); console.log(String(nginxOutput || '').trim()); } catch (err) { console.warn(`[WARN] Nginx upstream 切换失败: ${err.message}`); console.warn(`[WARN] Nginx reload 可能未成功,请人工确认 ${nginxUpstreamPath} 内容并执行 nginx -s reload`); } // 6.6. 停止旧实例(kill + 兜底 kill -9) const stopOldScript = [ 'set -euo pipefail', `OLD_DIR=${quoteForBash(oldDir)}`, `OLD_VERSION=${quoteForBash(currentVersion)}`, 'OLD_PIDS=$(ps -eo pid=,args= | awk -v root="$OLD_DIR" \'index($0, root) && $2 ~ /node$/ { print $1 }\')', 'if [ -z "$OLD_PIDS" ]; then', ' echo "未找到旧实例 ($OLD_VERSION) 进程,跳过停止步骤"', 'else', ' echo "正在停止旧实例 ($OLD_VERSION): $OLD_PIDS"', ' kill $OLD_PIDS || true', ' sleep 30', ' OLD_PIDS_REMAIN=$(ps -eo pid=,args= | awk -v root="$OLD_DIR" \'index($0, root) && $2 ~ /node$/ { print $1 }\')', ' if [ -n "$OLD_PIDS_REMAIN" ]; then', ' echo "旧实例 ($OLD_VERSION) 仍有残留进程,强制停止: $OLD_PIDS_REMAIN"', ' kill -9 $OLD_PIDS_REMAIN || true', ' fi', ' echo "旧实例 ($OLD_VERSION) 已停止"', 'fi', ].join('\n'); try { const stopOutput = runSsh(config, stopOldScript, { stdio: 'pipe' }); console.log(String(stopOutput || '').trim()); } catch (err) { console.warn(`[WARN] 停止旧实例失败: ${err.message}`); console.warn(`[WARN] 旧实例 (${currentVersion}) 可能仍在运行,请人工确认并停止`); } // 7. 打印完成信息 console.log(`发布完成: ${envName} -> ${config.username}@${config.host}:${targetDir}`); console.log(`线上版本号: ${releaseVersion}`); console.log(`当前活跃版本已切换为: ${targetVersion}`); } main();