oms/backend/script/deploy-remote.cjs
liufumingren 3daa95c96f feat(backend): 新增蓝绿发布脚本与跨域支持
跨域:
- 新增 app/middleware/cors.js:按白名单回 Access-Control-Allow-Origin,OPTIONS 预检直接
  204,使用 Bearer Token 鉴权故不回 Allow-Credentials
- config.default.js 注册全局中间件 cors(置于 requestLog 之前),并新增 config.cors.origins
  (可用环境变量 CORS_ORIGINS 覆盖,默认放行 http/https 的 oms.gztbyc.com 与本地 vite)

端口:
- config.default.js 新增 config.cluster(读 EGG_PORT,默认 6090)
  原因:egg 只在 env=local 时加载 config.local.js,生产(env=prod)不加载它,
  原先把端口写在 config.local.js 会让生产退回框架默认的 7001

发布(参考 WMS 后端的 v1/v2 双实例蓝绿):
- 新增 script/deploy-lib.cjs、deploy-remote.cjs、rollback-remote.cjs、init-deploy-config.cjs
- 目标目录:清理旧代码(保留 logs/run/node_modules/.env)→ 解压 → 缺 .env 时从
  deployRoot/.env 复制 → npm install --production → 释放端口 → 启动 → 健康检查 →
  改写 nginx-upstream.conf 并 reload → 停旧实例;健康检查失败则不切换、回滚 current.md
  并清理新实例,线上不受影响
- 回滚 = 切回另一套版本目录(npm run rollback [-- --to=v1|v2]),秒级完成
- 发布包按 git 文件清单 + include/exclude 白名单生成,.env/uploads/logs 等不入包
  (含 .sequelizerc,便于服务器上直接跑迁移)

配置与依赖:
- 新增 config/deploy.config.example.cjs(模板入库;真实配置 deploy.config.local.cjs 已忽略)
- 新增 env.production.example:生产 .env 模板,说明 MySQL 端口、Redis 密码、
  JWT_SECRET、UPLOAD_DIR(必须放版本目录之外以让 v1/v2 共用)等
- package.json 增加 deploy/deploy:prod/deploy:init/rollback/rollback:prod;
  顺带登记导出任务用到的 exceljs 依赖
- .gitignore 增加:真实部署配置、backend/temp/(本地发布包)、backend/upload/(导出产物)
2026-09-14 22:14:20 +08:00

203 lines
8.2 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

'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. 上传到 <deployRoot>/.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"',
// 服务器端真实环境变量只维护一份(<deployRoot>/.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();