'use strict'; const fs = require('node:fs'); const path = require('node:path'); const { ROOT, buildArchive, buildFrontConf, buildFrontendArchive, buildHealthCheckScript, buildKillPortScript, buildNginxSwitchScript, buildPinnedPathGuardLines, buildRemoteCleanupGuard, buildRemoteJsonWriteLines, buildStartScript, buildStopDirScript, ensureCommandAvailable, ensureTempDeployDir, getNowStamp, getRemoteEnvFile, loadDeployConfig, quoteForBash, runCommand, runNpm, runScp, runSsh, } = require('./deploy-lib.cjs'); const { recordVersionUpdate } = require('./version-registry.cjs'); /** * 通过 SSH 读取远端 current.md,获取当前活跃版本(v1 / v2) * * @param {object} config - 部署配置 * @return {string} 'v1' 或 'v2' */ function readRemoteCurrentVersion(config) { const currentMdPath = `${config.deployRoot}/current.md`; const output = runSsh(config, `cat ${quoteForBash(currentMdPath)} 2>/dev/null || true`, { stdio: 'pipe' }); const rawVersion = String(output || '').trim(); if (!rawVersion) { throw new Error( `无法读取远端当前版本文件: ${currentMdPath}。请确保远端已存在该文件且内容为 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; } function otherVersion(version) { return version === 'v1' ? 'v2' : 'v1'; } /** 本地构建前端(产物由 nginx 托管,单独发布到 deployRoot/frontend) */ function buildFrontend(config) { if (!config.buildFrontend) { console.log('已配置 buildFrontend=false,跳过前端构建。'); return; } const frontendRoot = path.resolve(ROOT, config.frontendDir); if (!fs.existsSync(path.join(frontendRoot, 'package.json'))) { throw new Error(`前端目录无效: ${frontendRoot}`); } console.log(`构建前端: ${frontendRoot}`); runNpm([ 'run', 'build' ], frontendRoot); } /** 远端目标目录:清理、解压、恢复私有文件、安装依赖 */ function deployToTargetDir(config, { targetDir, targetVersion, remoteArchive, stamp }) { const pinnedStashDir = `/tmp/pack-service-pinned-${targetVersion}`; const pinnedGuard = buildPinnedPathGuardLines('TARGET_DIR', 'PINNED_DIR', config.preservePaths); const cleanupGuard = buildRemoteCleanupGuard(config.sharedDirs); const backupName = `backup-${stamp}.tar.gz`; const backupLines = [ 'if [ -f "$TARGET_DIR/package.json" ]; then', ' mkdir -p "$BACKUP_DIR"', " tar -czf \"$BACKUP_DIR/$BACKUP_NAME\" -C \"$TARGET_DIR\" --exclude='./node_modules' --exclude='./logs' --exclude='./run' --exclude='./temp' --exclude='./app/public/download' --exclude='./app/public/version' --exclude='./config/config.prod.js' --exclude='./config/config.local.js' .", ' printf \'%s\\n\' "$BACKUP_NAME" > "$STATE_DIR/latest-backup.txt"', ' echo "已备份目标目录旧代码: $BACKUP_DIR/$BACKUP_NAME"', ' COUNT=0', ' for FILE in $(ls -1t "$BACKUP_DIR"/backup-*.tar.gz 2>/dev/null || true); do', ' COUNT=$((COUNT + 1))', ' if [ "$COUNT" -gt "$KEEP_BACKUPS" ]; then rm -f "$FILE"; fi', ' done', 'else', ' echo "目标目录首次发布,跳过备份"', 'fi', ]; const script = [ 'set -euo pipefail', `TARGET_DIR=${quoteForBash(targetDir)}`, `REMOTE_ARCHIVE=${quoteForBash(remoteArchive)}`, `PINNED_DIR=${quoteForBash(pinnedStashDir)}`, `BACKUP_DIR=${quoteForBash(config.backupDir)}`, `STATE_DIR=${quoteForBash(config.stateDir)}`, `SHARED_CONFIG_DIR=${quoteForBash(config.sharedConfigDir)}`, `ENV_FILE=${quoteForBash(getRemoteEnvFile(config))}`, `BACKUP_NAME=${quoteForBash(backupName)}`, `KEEP_BACKUPS=${Number(config.keepBackups || 5)}`, 'mkdir -p "$TARGET_DIR" "$BACKUP_DIR" "$STATE_DIR"', ...backupLines, ...pinnedGuard.stash, '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, // 服务端共享配置优先:每次发布都从 shared-config 复制,避免各版本配置漂移 'if [ -n "$SHARED_CONFIG_DIR" ] && [ -d "$SHARED_CONFIG_DIR" ]; then', ' for FILE_NAME in config.prod.js config.local.js; do', ' if [ -f "$SHARED_CONFIG_DIR/$FILE_NAME" ]; then', ' mkdir -p "$TARGET_DIR/config"', ' cp -a "$SHARED_CONFIG_DIR/$FILE_NAME" "$TARGET_DIR/config/$FILE_NAME"', ' echo "SHARED_CONFIG_APPLIED $FILE_NAME"', ' fi', ' done', 'else', ' echo "[WARN] 未找到共享配置目录: $SHARED_CONFIG_DIR"', 'fi', 'mkdir -p "$TARGET_DIR/app/public/download" "$TARGET_DIR/app/public/version"', 'mkdir -p "$TARGET_DIR/logs" "$TARGET_DIR/run" "$TARGET_DIR/temp"', 'if [ -n "$ENV_FILE" ] && [ -f "$ENV_FILE" ]; then', ' set -a; . "$ENV_FILE"; set +a', ' echo "已加载服务端环境变量: $ENV_FILE"', 'fi', 'npm install --production', ]; if (config.remoteDbDeploy) { script.push('EGG_SERVER_ENV=prod npm run db:deploy'); } runSsh(config, script.join('\n')); } /** 发布失败收尾:回滚 current.md、清理新实例,旧实例继续服务 */ function abortDeploy(config, { envName, currentVersion, currentMdPath, targetDir, targetVersion, startLogPath, reason }) { console.error(`[ERROR] ${reason}`); console.error(`[ERROR] 发布中止:不切换 Nginx,不停旧实例。启动日志: ${startLogPath}`); try { const revertOutput = runSsh(config, [ 'set -euo pipefail', `printf '%s\\n' ${quoteForBash(currentVersion)} > ${quoteForBash(currentMdPath)}`, `echo "已回滚 current.md -> ${currentVersion}"`, ].join('\n'), { stdio: 'pipe' }); console.log(String(revertOutput || '').trim()); } catch (revertErr) { console.error(`[ERROR] 回滚 current.md 失败: ${revertErr.message}`); } try { const killOutput = runSsh(config, buildStopDirScript(targetDir, `新实例 (${targetVersion})`), { stdio: 'pipe' }); console.log(String(killOutput || '').trim()); } catch (killErr) { console.error(`[ERROR] 清理失败的新实例出错: ${killErr.message}`); } let oldAlive = false; try { runSsh(config, [ 'set -euo pipefail', `curl -fsS --connect-timeout 2 --max-time 5 ${quoteForBash(`http://127.0.0.1:${config.ports[currentVersion]}${config.healthCheckPath}`)} >/dev/null`, ].join('\n'), { stdio: 'pipe' }); oldAlive = true; } catch (checkErr) { oldAlive = false; } console.error(`[ERROR] 发布失败: ${envName} -> ${config.username}@${config.host}:${targetDir}`); if (oldAlive) { console.error(`[ERROR] 旧实例 (${currentVersion}) 仍在运行,线上服务不受影响`); } else { console.error(`[ERROR] 未检测到旧实例 (${currentVersion}) 在 ${config.ports[currentVersion]} 提供服务,请人工介入`); } process.exit(1); } /** 把本机权威 env 同步到服务器 shared-config(存在才上传;统一转成 LF) */ function uploadEnvFile(config, stamp) { if (!config.uploadEnvFile || !config.sharedConfigDir) { return; } if (!fs.existsSync(config.envFileLocalPath)) { console.log(`未找到本机 env 文件 ${config.envFileLocalPath},沿用服务器 shared-config/${config.envFile}`); return; } const content = fs.readFileSync(config.envFileLocalPath, 'utf8').replace(/\r\n?/g, '\n'); const uploadDir = ensureTempDeployDir(); const localUpload = path.join(uploadDir, `env-${stamp}.sh`); fs.writeFileSync(localUpload, content, 'utf8'); const remoteTemp = `${config.sharedConfigDir}/${config.envFile}.upload-${stamp}`; try { runScp(config, localUpload, remoteTemp); } finally { fs.rmSync(localUpload, { force: true }); } runSsh(config, [ 'set -euo pipefail', `TARGET=${quoteForBash(`${config.sharedConfigDir}/${config.envFile}`)}`, `TEMP=${quoteForBash(remoteTemp)}`, 'mkdir -p "$(dirname "$TARGET")"', 'mv "$TEMP" "$TARGET"', 'chmod 600 "$TARGET"', // 防御:即使上传来源混入 CRLF,也在服务器上再转一次 "sed -i 's/\\r$//' \"$TARGET\"", 'echo "ENV_UPLOADED"', ].join('\n'), { stdio: 'pipe' }); console.log(`本机 env 已同步到服务器: ${config.sharedConfigDir}/${config.envFile}`); } /** 写入 nginx 前端静态托管 + 后端反代配置(front.conf,由发布脚本维护) */ function writeFrontConf(config) { if (!config.manageNginxFrontConf || !config.nginxFrontConf) { return; } const base64 = Buffer.from(buildFrontConf(config), 'utf8').toString('base64'); runSsh(config, [ 'set -euo pipefail', `TARGET=${quoteForBash(config.nginxFrontConf)}`, 'mkdir -p "$(dirname "$TARGET")"', `printf '%s' ${quoteForBash(base64)} | base64 -d > "$TARGET"`, 'echo "FRONT_CONF_WRITTEN"', ].join('\n'), { stdio: 'pipe' }); console.log(`nginx 前端配置已更新: ${config.nginxFrontConf}`); } /** 发布前端静态文件:解压到临时目录后整目录切换,上一版保留为 frontend.prev */ function deployFrontend(config, { stamp, remoteFrontendArchive }) { if (!config.buildFrontend) { console.log('已配置 buildFrontend=false,跳过前端发布。'); return; } const newDir = `${config.frontendDeployDir}.new-${stamp}`; const script = [ 'set -euo pipefail', `FRONTEND_DIR=${quoteForBash(config.frontendDeployDir)}`, `PREV_DIR=${quoteForBash(config.frontendPrevDir)}`, `NEW_DIR=${quoteForBash(newDir)}`, `REMOTE_ARCHIVE=${quoteForBash(remoteFrontendArchive)}`, 'rm -rf "$NEW_DIR"', 'mkdir -p "$NEW_DIR"', 'tar -xzf "$REMOTE_ARCHIVE" -C "$NEW_DIR"', 'rm -f "$REMOTE_ARCHIVE"', 'find "$NEW_DIR" -type d -exec chmod 755 {} +', 'find "$NEW_DIR" -type f -exec chmod 644 {} +', 'if [ -d "$FRONTEND_DIR" ]; then', ' rm -rf "$PREV_DIR"', ' mv "$FRONTEND_DIR" "$PREV_DIR"', 'fi', 'mv "$NEW_DIR" "$FRONTEND_DIR"', 'echo "FRONTEND_DEPLOYED $FRONTEND_DIR"', ].join('\n'); runSsh(config, script); console.log(`前端已发布到 nginx 静态目录: ${config.frontendDeployDir}`); } 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 中。'); const currentVersion = readRemoteCurrentVersion(config); const targetVersion = otherVersion(currentVersion); const targetDir = `${config.deployRoot}/${targetVersion}`; const oldDir = `${config.deployRoot}/${currentVersion}`; const targetPort = config.ports[targetVersion]; console.log(`远端当前活跃版本: ${currentVersion},目标部署目录: ${targetDir}(端口 ${targetPort})`); buildFrontend(config); const stamp = getNowStamp(); const packageJson = JSON.parse(fs.readFileSync(path.join(ROOT, 'package.json'), 'utf8')); const packageVersion = String(packageJson.version || '0.0.0'); const gitCommit = runCommand('git', [ 'rev-parse', 'HEAD' ]); const gitCommitShort = runCommand('git', [ 'rev-parse', '--short', 'HEAD' ]); const gitBranch = runCommand('git', [ 'rev-parse', '--abbrev-ref', 'HEAD' ]); const releaseVersion = `v${packageVersion}-${stamp}-${gitCommitShort}`; const { archivePath, fileCount } = buildArchive(stamp, config); console.log(`后端发布包已生成: ${archivePath}(文件 ${fileCount} 个)`); let frontendArchivePath = ''; if (config.buildFrontend) { frontendArchivePath = buildFrontendArchive(stamp, config).archivePath; console.log(`前端发布包已生成: ${frontendArchivePath}`); } const remoteArchive = `${config.incomingDir}/release-${stamp}.tar.gz`; const remoteFrontendArchive = `${config.incomingDir}/frontend-${stamp}.tar.gz`; runSsh(config, [ 'set -euo pipefail', `mkdir -p ${quoteForBash(targetDir)} ${quoteForBash(config.incomingDir)} ${quoteForBash(config.backupDir)} ${quoteForBash(config.stateDir)} ${quoteForBash(config.sharedConfigDir)}`, ].join('\n')); console.log(`远端目录已就绪: ${targetDir}`); uploadEnvFile(config, stamp); runScp(config, archivePath, remoteArchive); console.log(`后端发布包已上传: ${remoteArchive}`); if (frontendArchivePath) { runScp(config, frontendArchivePath, remoteFrontendArchive); console.log(`前端发布包已上传: ${remoteFrontendArchive}`); } deployToTargetDir(config, { targetDir, targetVersion, remoteArchive, stamp }); console.log(`远端目标目录已清理、解压并安装生产依赖: ${targetDir}`); const startLogPath = `/tmp/pack-service-${targetVersion}-start.log`; const currentMdPath = `${config.deployRoot}/current.md`; try { const killPortOutput = runSsh(config, buildKillPortScript(targetPort), { stdio: 'pipe' }); console.log(String(killPortOutput || '').trim()); } catch (err) { console.warn(`[WARN] 端口 ${targetPort} 清理失败: ${err.message}`); } const switchAndStartScript = [ 'set -euo pipefail', `printf '%s\\n' ${quoteForBash(targetVersion)} > ${quoteForBash(currentMdPath)}`, buildStartScript({ dir: targetDir, port: targetPort, envFile: getRemoteEnvFile(config), logPath: startLogPath, }), `echo "已更新 current.md -> ${targetVersion}"`, ].join('\n'); try { const switchOutput = runSsh(config, switchAndStartScript, { stdio: 'pipe' }); console.log(String(switchOutput || '').trim()); } catch (err) { abortDeploy(config, { envName, currentVersion, currentMdPath, targetDir, targetVersion, startLogPath, reason: `新实例启动命令执行失败: ${err.message}`, }); } try { const healthOutput = runSsh(config, buildHealthCheckScript({ port: targetPort, healthPath: config.healthCheckPath, attempts: config.healthCheckAttempts, interval: config.healthCheckInterval, }), { stdio: 'pipe' }); console.log(String(healthOutput || '').trim()); } catch (err) { abortDeploy(config, { envName, currentVersion, currentMdPath, targetDir, targetVersion, startLogPath, reason: `新实例健康检查失败: ${err.message}`, }); } try { writeFrontConf(config); deployFrontend(config, { stamp, remoteFrontendArchive }); } catch (err) { abortDeploy(config, { envName, currentVersion, currentMdPath, targetDir, targetVersion, startLogPath, reason: `前端发布失败: ${err.message}`, }); } if (config.nginxUpstreamFile) { try { const nginxOutput = runSsh(config, buildNginxSwitchScript(config.nginxUpstreamFile, targetPort), { stdio: 'pipe' }); console.log(String(nginxOutput || '').trim()); } catch (err) { abortDeploy(config, { envName, currentVersion, currentMdPath, targetDir, targetVersion, startLogPath, reason: `Nginx upstream 切换失败: ${err.message}。请确认 ${config.nginxUpstreamFile} 被站点配置 include,且当前账号可执行 nginx -t / nginx -s reload`, }); } } else { console.log('已配置 nginxUpstreamFile 为空,跳过 Nginx upstream 切换。'); } try { const stopOutput = runSsh(config, buildStopDirScript(oldDir, `旧实例 (${currentVersion})`), { stdio: 'pipe' }); console.log(String(stopOutput || '').trim()); } catch (err) { console.warn(`[WARN] 停止旧实例失败: ${err.message}`); console.warn(`[WARN] 旧实例 (${currentVersion}) 可能仍在运行,请人工确认并停止`); } const releaseRecord = { deployedAt: new Date().toISOString(), releaseVersion, packageVersion, gitCommit, gitCommitShort, gitBranch, envName, activeVersion: targetVersion, port: targetPort, dir: targetDir, previousVersion: currentVersion, frontendDir: config.buildFrontend ? config.frontendDeployDir : '', deployedBy: process.env.USERNAME || process.env.USER || '', }; try { runSsh(config, [ 'set -euo pipefail', `STATE_DIR=${quoteForBash(config.stateDir)}`, 'mkdir -p "$STATE_DIR"', ...buildRemoteJsonWriteLines(config.stateDir, 'current-release.json', releaseRecord, false), ...buildRemoteJsonWriteLines(config.stateDir, 'release-history.jsonl', releaseRecord, true), 'echo "远端发布状态已记录"', ].join('\n'), { stdio: 'pipe' }); } catch (err) { console.warn(`[WARN] 远端发布状态记录失败: ${err.message}`); } try { recordVersionUpdate({ source: 'deploy', note: `deploy ${targetVersion}`, releaseVersion, deployRoot: config.deployRoot, }); } catch (err) { console.warn(`[WARN] 本地版本记录失败: ${err.message}`); } console.log(`发布完成: ${envName} -> ${config.username}@${config.host}:${targetDir}`); console.log(`线上版本号: ${releaseVersion}`); console.log(`当前活跃版本已切换为: ${targetVersion}(端口 ${targetPort})`); } try { main(); } catch (err) { console.error(`[ERROR] ${err && err.message ? err.message : err}`); process.exit(1); }