'use strict'; const fs = require('node:fs'); const path = require('node:path'); const { ROOT, buildArchive, buildRemoteCleanupGuard, ensureCommandAvailable, getNowStamp, isGitAvailable, loadDeployConfig, quoteForBash, runCommand, runCommandSafe, runScp, runSsh, } = require('./deploy-lib.cjs'); /** * 通过 SSH 读取远端 current.md 文件,获取当前活跃版本标识(v1 或 v2) * * @param {object} config - 部署配置对象 * @param {string} deployRoot - 远端部署根目录,如 /www/wwwroot/ye4s * @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/ye4s/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/ye4s * @return {string} 目标部署目录,如 /www/wwwroot/ye4s/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 → 7071,v2 → 7072) * * @param {string} targetVersion - 目标版本标识,'v1' 或 'v2' * @return {number} 对应端口号 */ function getTargetPort(targetVersion) { if (targetVersion === 'v1') { return 7071; } return 7072; } /** * 根据版本标识返回进程 title(v1 → egg-server-ye4s-v1,v2 → egg-server-ye4s-v2) * * @param {string} version - 版本标识,'v1' 或 'v2' * @return {string} 进程 title */ function getProcessTitle(version) { return `egg-server-ye4s-${version}`; } 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. 部署前安全检查 console.log('========================================'); console.log('ye4s 蓝绿部署'); console.log(`环境: ${envName}`); console.log(`目标: ${config.username}@${config.host}:${config.port}`); console.log(`远端根目录: ${config.deployRoot}`); console.log('========================================'); // 检查 Git 未提交更改 if (isGitAvailable()) { const uncommitted = runCommandSafe('git', [ 'status', '--porcelain' ]); if (uncommitted) { console.warn('[WARN] 检测到未提交的更改:'); const changes = uncommitted.split(/\r?\n/).filter(Boolean); for (const line of changes.slice(0, 10)) { console.warn(` ${line}`); } if (changes.length > 10) { console.warn(` ... 还有 ${changes.length - 10} 处更改`); } console.warn('[WARN] 未提交的更改不会被包含在发布包中!'); console.warn('[WARN] 建议先 git add && git commit 后再部署。'); } } // 1. 读取远端 current.md,确定目标目录 const currentVersion = readRemoteCurrentVersion(config, config.deployRoot); const targetDir = resolveTargetDir(currentVersion, config.deployRoot); console.log(`远端当前活跃版本: ${currentVersion},目标部署目录: ${targetDir}`); // 2. 本地打包 console.log('[1/8] 正在本地打包...'); const stamp = getNowStamp(); const packageJson = JSON.parse(fs.readFileSync(path.join(ROOT, 'package.json'), 'utf8')); const packageVersion = String(packageJson.version || '0.0.0'); let gitCommitShort = 'nogit'; if (isGitAvailable()) { gitCommitShort = runCommandSafe('git', [ 'rev-parse', '--short', 'HEAD' ]) || 'nogit'; } const releaseVersion = `v${packageVersion}-${stamp}-${gitCommitShort}`; const { archivePath } = buildArchive(stamp, config); console.log(`[1/8] 打包完成: ${archivePath}`); const remoteArchive = `${config.incomingDir}/release-${stamp}.tar.gz`; // 3. 远端创建目录结构(目标目录 + incoming/backups/state 目录) console.log('[2/8] 正在远端创建目录...'); const setupScript = [ 'set -euo pipefail', `mkdir -p ${quoteForBash(targetDir)} ${quoteForBash(config.incomingDir)} ${quoteForBash(config.backupDir)} ${quoteForBash(config.stateDir)}`, ].join('\n'); runSsh(config, setupScript); console.log(`[2/8] 远端目录已就绪: ${targetDir}`); // 3.5. 远端备份当前目标目录(如果已有内容) console.log('[3/8] 正在备份远端目标目录...'); const backupScript = [ 'set -euo pipefail', `TARGET_DIR=${quoteForBash(targetDir)}`, `BACKUP_DIR=${quoteForBash(config.backupDir)}`, `STAMP=${quoteForBash(stamp)}`, 'if [ -f "$TARGET_DIR/package.json" ]; then', ' BACKUP_FILE="$BACKUP_DIR/backup-${STAMP}.tar.gz"', ' cd "$TARGET_DIR"', ' tar -czf "$BACKUP_FILE" . --exclude="./node_modules" --exclude="./.deploy" --exclude="./logs" --exclude="./run" --exclude="./tmp" 2>/dev/null || true', ' echo "已备份目标目录到: $BACKUP_FILE"', 'else', ' echo "目标目录为空,跳过备份"', 'fi', ].join('\n'); try { const backupOutput = runSsh(config, backupScript, { stdio: 'pipe' }); console.log(String(backupOutput || '').trim()); } catch (err) { console.warn(`[WARN] 备份失败(非致命): ${err.message}`); } // 4. SCP 上传 tar.gz 到远端 incoming 目录 console.log('[4/8] 正在上传发布包...'); runScp(config, archivePath, remoteArchive); console.log(`[4/8] 发布包已上传到远端: ${remoteArchive}`); // 5. 在目标目录清理旧代码、解压、安装依赖 const cleanupGuard = buildRemoteCleanupGuard( [ ...config.sharedDirs, 'node_modules' ], config.preserveDirs ); const remoteScript = [ 'set -euo pipefail', `TARGET_DIR=${quoteForBash(targetDir)}`, `REMOTE_ARCHIVE=${quoteForBash(remoteArchive)}`, `ACTIVE_DIR=${quoteForBash(`${config.deployRoot}/${currentVersion}`)}`, // 从活跃版本复制 node_modules(蓝绿部署核心优化,避免每次全量重装) 'if [ ! -d "$TARGET_DIR/node_modules" ] && [ -d "$ACTIVE_DIR/node_modules" ]; then', ' echo "正在从活跃版本 ($ACTIVE_DIR) 复制 node_modules ..."', ' cp -a "$ACTIVE_DIR/node_modules" "$TARGET_DIR/node_modules"', ' echo "node_modules 复制完成"', 'fi', // 进入目标目录,清理旧代码文件(保留 node_modules、logs、run、tmp、.deploy 等运行时/状态目录) 'cd "$TARGET_DIR"', `find . -mindepth 1 -maxdepth 1 ${cleanupGuard} -exec rm -rf {} +`, // 解压发布包 'tar -xzf "$REMOTE_ARCHIVE" -C "$TARGET_DIR"', 'rm -f "$REMOTE_ARCHIVE"', // 检查 config 目录是否存在,不存在则从活跃版本复制 'if [ ! -d "$TARGET_DIR/config" ]; then', ` ACTIVE_DIR=${quoteForBash(`${config.deployRoot}/${currentVersion}`)}`, ' if [ -d "$ACTIVE_DIR/config" ]; then', ' cp -a "$ACTIVE_DIR/config" "$TARGET_DIR/config"', ' echo "已从活跃版本 ($ACTIVE_DIR) 复制 config 目录"', ' else', ` FALLBACK_DIR=${quoteForBash(config.deployRoot)}`, ' if [ -d "$FALLBACK_DIR/config" ]; then', ' cp -a "$FALLBACK_DIR/config" "$TARGET_DIR/config"', ' echo "已从根目录 ($FALLBACK_DIR) 复制 config 目录"', ' else', ' echo "[WARN] 未找到 config 目录来源,目标目录将缺少 config 配置!"', ' fi', ' fi', 'fi', // 在目标目录安装生产依赖 'npm install --production', ].join('\n'); console.log('[5/8] 正在远端清理、解压、安装依赖...'); runSsh(config, remoteScript); console.log(`[5/8] 远端目标目录已清理、解压并安装依赖: ${targetDir}`); // 推导目标版本标识与启动日志路径 const targetVersion = resolveTargetVersion(currentVersion); const targetPort = getTargetPort(targetVersion); const targetTitle = getProcessTitle(targetVersion); const currentTitle = getProcessTitle(currentVersion); const startLogPath = `/tmp/ye4s-${targetVersion}-start.log`; const currentMdPath = `${config.deployRoot}/current.md`; const oldDir = `${config.deployRoot}/${currentVersion}`; // 6. 停止目标目录可能残留的旧进程(使用版本专用 title) const stopTargetScript = [ 'set -euo pipefail', `TARGET_DIR=${quoteForBash(targetDir)}`, `TARGET_VERSION=${quoteForBash(targetVersion)}`, `TARGET_TITLE=${quoteForBash(targetTitle)}`, // 先按目录路径查找进程 'TARGET_PIDS=$(ps -eo pid=,args= | awk -v root="$TARGET_DIR" \'index($0, root) && $2 ~ /node$/ { print $1 }\')', // 再按 title 查找 'TITLE_PIDS=$(ps -eo pid=,args= | awk -v t="$TARGET_TITLE" \'index($0, t) { print $1 }\')', 'ALL_PIDS=$(echo "$TARGET_PIDS $TITLE_PIDS" | tr " " "\\n" | sort -u | grep -v "^$" | tr "\\n" " ")', 'if [ -z "$ALL_PIDS" ]; then', ' echo "未找到目标目录 ($TARGET_VERSION) 残留进程"', 'else', ' echo "正在停止目标目录 ($TARGET_VERSION) 残留进程: $ALL_PIDS"', ' kill $ALL_PIDS || true', ' sleep 2', ' REMAIN=$(ps -eo pid=,args= | awk -v root="$TARGET_DIR" \'index($0, root) && $2 ~ /node$/ { print $1 }\')', ' if [ -n "$REMAIN" ]; then', ' kill -9 $REMAIN || true', ' fi', ' echo "目标目录 ($TARGET_VERSION) 残留进程已停止"', 'fi', ].join('\n'); try { const stopTargetOutput = runSsh(config, stopTargetScript, { stdio: 'pipe' }); console.log(String(stopTargetOutput || '').trim()); } catch (err) { console.warn(`[WARN] 停止目标目录残留进程失败: ${err.message}`); } // 6.5. 检测并停止旧版根目录遗留进程(端口 7001 等,首次蓝绿迁移时需要) const legacyRootDir = config.deployRoot; const stopLegacyScript = [ 'set -euo pipefail', `ROOT_DIR=${quoteForBash(legacyRootDir)}`, // 查找 baseDir 指向根目录(而非 v1/v2)的 egg 进程 'LEGACY_PIDS=$(ps -eo pid=,args= | awk -v root="$ROOT_DIR" \'index($0, "baseDir") && index($0, root) && !index($0, root"/v1") && !index($0, root"/v2") { print $1 }\')', 'if [ -z "$LEGACY_PIDS" ]; then', ' echo "未发现旧版根目录遗留进程"', 'else', ' echo "发现旧版根目录遗留进程: $LEGACY_PIDS,正在停止..."', ' kill $LEGACY_PIDS || true', ' sleep 3', ' REMAIN=$(ps -eo pid=,args= | awk -v root="$ROOT_DIR" \'index($0, "baseDir") && index($0, root) && !index($0, root"/v1") && !index($0, root"/v2") { print $1 }\')', ' if [ -n "$REMAIN" ]; then', ' kill -9 $REMAIN || true', ' fi', ' echo "旧版根目录遗留进程已停止"', 'fi', ].join('\n'); try { const legacyOutput = runSsh(config, stopLegacyScript, { stdio: 'pipe' }); console.log(String(legacyOutput || '').trim()); } catch (err) { // 旧版进程清理失败不阻塞部署 console.warn(`[WARN] 旧版进程清理: ${err.message}`); } // 7. 启动新实例(先不切换 current.md) console.log('[6/8] 正在启动新实例...'); const startScript = [ 'set -euo pipefail', `cd ${quoteForBash(targetDir)}`, `nohup bash -lc 'npx egg-scripts start --daemon --title=${targetTitle} --sticky --port=${targetPort} --ignore-stderr' > ${quoteForBash(startLogPath)} 2>&1 &`, `echo "已在 ${targetDir} 启动新实例 ${targetVersion} (title=${targetTitle}, 端口 ${targetPort}),启动日志: ${startLogPath}"`, ].join('\n'); const startOutput = runSsh(config, startScript, { stdio: 'pipe' }); console.log(String(startOutput || '').trim()); // 8. 健康检查新实例(curl 循环等待,最多 60 秒) console.log('[7/8] 正在进行健康检查(最多等待 60 秒)...'); const healthCheckScript = [ 'set -euo pipefail', `TARGET_PORT=${targetPort}`, 'HEALTH_OK=false', 'for attempt in $(seq 1 30); do', ' if curl -fsS --connect-timeout 2 --max-time 4 "http://127.0.0.1:$TARGET_PORT/" >/dev/null 2>&1; then', ` echo "新实例 (${targetVersion}) 健康检查通过 (端口 $TARGET_PORT, 第 $attempt 次)"`, ' HEALTH_OK=true', ' break', ' fi', ' sleep 2', 'done', 'if [ "$HEALTH_OK" != "true" ]; then', ` echo "FATAL: 新实例 (${targetVersion}) 健康检查超时 (端口 $TARGET_PORT)" >&2`, ' exit 1', 'fi', ].join('\n'); let healthPassed = false; try { const healthOutput = runSsh(config, healthCheckScript, { stdio: 'pipe' }); console.log(String(healthOutput || '').trim()); healthPassed = true; } catch (err) { console.error(`[FATAL] 新实例健康检查失败: ${err.message}`); console.error(`[FATAL] 新实例 (${targetVersion}) 未能正常启动,保留当前活跃版本 (${currentVersion}) 不变。`); console.error(`[FATAL] 请检查启动日志: ssh ${config.username}@${config.host} "cat ${startLogPath}"`); console.error('[FATAL] 部署已中止,当前服务不受影响。'); // 尝试停止失败的新实例 const cleanupFailedScript = [ 'set -euo pipefail', `TARGET_DIR=${quoteForBash(targetDir)}`, 'FAILED_PIDS=$(ps -eo pid=,args= | awk -v root="$TARGET_DIR" \'index($0, root) && $2 ~ /node$/ { print $1 }\')', 'if [ -n "$FAILED_PIDS" ]; then kill -9 $FAILED_PIDS || true; fi', 'echo "已清理失败的新实例进程"', ].join('\n'); try { runSsh(config, cleanupFailedScript, { stdio: 'pipe' }); } catch (_) { /* ignore */ } process.exit(1); } // 9. 健康检查通过 → 切换 current.md console.log('[8/8] 正在切换流量...'); const switchCurrentMdScript = [ 'set -euo pipefail', `printf '%s\\n' ${quoteForBash(targetVersion)} > ${quoteForBash(currentMdPath)}`, `echo "current.md 已切换 -> ${targetVersion}"`, ].join('\n'); const switchOutput2 = runSsh(config, switchCurrentMdScript, { stdio: 'pipe' }); console.log(String(switchOutput2 || '').trim()); // 10. 切换 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] 新实例已在端口 ${targetPort} 运行,但 Nginx 未自动切换。`); console.warn(`[WARN] 请手动更新 ${nginxUpstreamPath} 并执行 nginx -s reload`); } // 11. 停止旧实例(kill + 兜底 kill -9) const stopOldScript = [ 'set -euo pipefail', `OLD_DIR=${quoteForBash(oldDir)}`, `OLD_VERSION=${quoteForBash(currentVersion)}`, `OLD_TITLE=${quoteForBash(currentTitle)}`, '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 3', ' 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}) 可能仍在运行,请人工确认并停止`); } // 11. 记录远端 release 状态 const remoteStateFile = `${config.stateDir}/current-release.json`; const remoteHistoryFile = `${config.stateDir}/release-history.jsonl`; const releaseEntry = { releaseVersion, packageVersion, gitCommitShort, deployRoot: config.deployRoot, targetVersion, targetPort, deployedAt: new Date().toISOString(), }; const releaseJson = JSON.stringify(releaseEntry); const recordReleaseScript = [ 'set -euo pipefail', `STATE_FILE=${quoteForBash(remoteStateFile)}`, `HISTORY_FILE=${quoteForBash(remoteHistoryFile)}`, `ENTRY=${quoteForBash(releaseJson)}`, 'printf "%s\\n" "$ENTRY" > "$STATE_FILE"', 'printf "%s\\n" "$ENTRY" >> "$HISTORY_FILE"', 'echo "远端 release 状态已记录"', ].join('\n'); try { const recordOutput = runSsh(config, recordReleaseScript, { stdio: 'pipe' }); console.log(String(recordOutput || '').trim()); } catch (err) { console.warn(`[WARN] 记录远端 release 状态失败: ${err.message}`); } // 12. 清理旧备份(保留最近 N 个) const cleanupBackupsScript = [ 'set -euo pipefail', `BACKUP_DIR=${quoteForBash(config.backupDir)}`, `KEEP=${Number(config.keepBackups)}`, 'cd "$BACKUP_DIR"', 'ls -1t backup-*.tar.gz 2>/dev/null | tail -n +$((KEEP + 1)) | while read -r f; do rm -f "$f"; echo "已清理旧备份: $f"; done', 'echo "备份清理完成(保留最近 ${KEEP} 个)"', ].join('\n'); try { const cleanupOutput = runSsh(config, cleanupBackupsScript, { stdio: 'pipe' }); console.log(String(cleanupOutput || '').trim()); } catch (err) { console.warn(`[WARN] 清理旧备份失败: ${err.message}`); } // 13. 打印完成信息 console.log('========================================'); console.log(`发布完成: ${envName} -> ${config.username}@${config.host}:${targetDir}`); console.log(`线上版本号: ${releaseVersion}`); console.log(`当前活跃版本已切换为: ${targetVersion} (端口 ${targetPort})`); console.log('========================================'); } main();