'use strict'; /** * 后端发布脚本(双实例蓝绿) * * npm run deploy # 等价 npm run deploy:prod * npm run deploy:prod * * 流程: * 1. 本地按 git 文件清单打发布包(不含 .env / uploads / logs 等) * 2. 读取远端 current.md,确定目标版本(v1 ↔ v2 交替;首次发布用 v1) * 3. 上传到 /.deploy/incoming,清理目标版本目录(保留 logs/run/node_modules)后解压 * 4. 补齐 .env、安装生产依赖、释放目标端口、启动新实例 * 5. 健康检查通过后切换 Nginx upstream(nginx -t && nginx -s reload) * 6. 停止旧实例、记录当前发布版本号 * 健康检查失败:回滚 current.md、杀掉新实例,旧实例不受影响(线上不中断) */ const fs = require('node:fs'); const path = require('node:path'); const { ROOT, buildArchive, buildFreePortLines, buildHealthCheckLines, buildNginxSwitchLines, buildRemoteCleanupGuard, buildScopedEggStopLines, buildStartInstanceLines, ensureCommandAvailable, getNowStamp, loadDeployConfig, otherVersion, portOf, quoteForBash, readRemoteCurrentVersion, runCommand, runScp, runSsh, } = require('./deploy-lib.cjs'); 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. 远端当前活跃版本 → 本次目标版本 const currentVersion = readRemoteCurrentVersion(config); const targetVersion = otherVersion(currentVersion); const targetPort = portOf(config, targetVersion); const targetDir = `${config.deployRoot}/${targetVersion}`; const oldDir = currentVersion ? `${config.deployRoot}/${currentVersion}` : ''; if (currentVersion) { console.log(`远端当前活跃版本: ${currentVersion}(端口 ${portOf(config, currentVersion)})`); } else { console.log('远端尚未初始化(无 current.md),本次作为首次发布,落到 v1'); } console.log(`本次发布目标: ${targetVersion} → ${targetDir}(端口 ${targetPort})`); // 2. 本地打包 const stamp = getNowStamp(); const packageJson = JSON.parse(fs.readFileSync(path.join(ROOT, 'package.json'), 'utf8')); const gitCommitShort = runCommand('git', [ 'rev-parse', '--short', 'HEAD' ]); const releaseVersion = `v${packageJson.version || '0.0.0'}-${stamp}-${gitCommitShort}`; const { archivePath, fileCount } = buildArchive(stamp, config); const remoteArchive = `${config.incomingDir}/${path.basename(archivePath)}`; console.log(`发布包已生成: ${archivePath}(${fileCount} 个文件,版本号 ${releaseVersion})`); // 3. 远端准备目录并上传发布包 runSsh(config, [ 'set -euo pipefail', `mkdir -p ${quoteForBash(targetDir)} ${quoteForBash(config.incomingDir)} ${quoteForBash(config.stateDir)}`, `echo "远端目录已就绪: ${targetDir}"`, ].join('\n')); runScp(config, archivePath, remoteArchive); console.log(`发布包已上传: ${remoteArchive}`); // 4. 清理目标目录 → 解压 → 补齐 .env → 安装生产依赖 const envFile = `${config.deployRoot}/.env`; const cleanupGuard = buildRemoteCleanupGuard(config.sharedDirs); const installScript = [ 'set -euo pipefail', `TARGET_DIR=${quoteForBash(targetDir)}`, `REMOTE_ARCHIVE=${quoteForBash(remoteArchive)}`, `ENV_FILE=${quoteForBash(envFile)}`, 'cd "$TARGET_DIR"', // 清理上一次遗留的代码(保留 .deploy 与 sharedDirs:logs / run / node_modules) `find . -mindepth 1 -maxdepth 1 ${cleanupGuard} -exec rm -rf {} +`, 'tar -xzf "$REMOTE_ARCHIVE" -C "$TARGET_DIR"', 'rm -f "$REMOTE_ARCHIVE"', // 服务器端真实环境变量只维护一份(/.env),首次落到某版本目录时复制过去; // 已存在则不覆盖,便于个别版本目录单独调整 'if [ ! -f "$TARGET_DIR/.env" ]; then', ' if [ -f "$ENV_FILE" ]; then', ' cp -a "$ENV_FILE" "$TARGET_DIR/.env"', ' echo "ENV_COPIED $ENV_FILE -> $TARGET_DIR/.env"', ' else', ' echo "WARN_ENV_MISSING 未找到 $ENV_FILE,请先在该文件写入生产环境变量(数据库、JWT_SECRET 等)" >&2', ' fi', 'else', ' echo "ENV_KEPT $TARGET_DIR/.env(已存在,未覆盖)"', 'fi', config.installCommand, ].join('\n'); runSsh(config, installScript); console.log(`远端代码已更新并安装依赖: ${targetDir}`); // 5. 释放目标端口(防止残留进程占用导致新实例起不来) runSsh(config, [ 'set -euo pipefail', ...buildFreePortLines(targetPort) ].join('\n')); const startLogPath = `/tmp/oms-${targetVersion}-start.log`; // 6. 记录 current.md 并启动新实例 runSsh(config, [ 'set -euo pipefail', `printf '%s\\n' ${quoteForBash(targetVersion)} > ${quoteForBash(`${config.deployRoot}/current.md`)}`, ...buildStartInstanceLines(targetDir, config.startCommand, startLogPath), ].join('\n')); // 7. 健康检查(20 秒内轮询;失败则回滚记录并清理新实例,旧实例继续服务) const healthCheckScript = [ 'set -euo pipefail', ...buildHealthCheckLines(targetPort, config.healthCheckPath, targetVersion), ].join('\n'); try { runSsh(config, healthCheckScript); } catch (err) { console.error(`[ERROR] 新实例健康检查失败: ${err.message}`); console.error(`[ERROR] 发布中止(未切换 Nginx),请查看启动日志 ${startLogPath}`); if (currentVersion) { try { runSsh(config, [ 'set -euo pipefail', `printf '%s\\n' ${quoteForBash(currentVersion)} > ${quoteForBash(`${config.deployRoot}/current.md`)}`, `echo "current.md 已回滚为 ${currentVersion}"`, ].join('\n')); } catch (revertErr) { console.error(`[ERROR] current.md 回滚失败: ${revertErr.message}`); } } try { runSsh(config, [ 'set -euo pipefail', ...buildScopedEggStopLines(targetDir, 'STOP_FAILED_NEW'), ].join('\n')); } catch (killErr) { console.error(`[ERROR] 清理失败的新实例出错: ${killErr.message}`); } console.error(`[ERROR] 发布失败: ${envName} -> ${config.username}@${config.host}:${targetDir}`); if (currentVersion) console.error(`[ERROR] 旧实例(${currentVersion})仍在服务,线上不受影响`); process.exit(1); } // 8. 切换 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`); console.warn('[WARN] 若站点配置尚未 include 该文件,请先按 config/deploy.config.example.cjs 顶部说明改一次站点配置'); } // 9. 停止旧实例 if (currentVersion) { try { runSsh(config, [ 'set -euo pipefail', ...buildScopedEggStopLines(oldDir, 'STOP_OLD'), `echo "旧实例 ${currentVersion} 已停止"`, ].join('\n')); } catch (err) { console.warn(`[WARN] 停止旧实例失败: ${err.message},请人工确认并停止 ${oldDir} 下的进程`); } } // 10. 记录当前发布版本号 try { runSsh(config, [ 'set -euo pipefail', `printf '%s\\n' ${quoteForBash(releaseVersion)} > ${quoteForBash(`${config.stateDir}/current-release.txt`)}`, `echo "当前发布版本: ${releaseVersion}"`, ].join('\n')); } catch (err) { console.warn(`[WARN] 记录发布版本号失败: ${err.message}`); } console.log(`发布完成: ${config.username}@${config.host}:${targetDir}`); console.log(`活跃版本: ${targetVersion}(端口 ${targetPort})`); console.log(`发布版本号: ${releaseVersion}`); } main();