oms/backend/script/rollback-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

132 lines
4.9 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 rollback # 回滚到上一个版本(v1 ↔ v2)
* npm run rollback -- --to=v1 # 指定切回某个版本
*
* 流程:启动目标版本实例 → 健康检查通过 → 切换 Nginx upstream → 记录 current.md → 停止当前实例
* 目标版本目录不可用(未发布过)时会直接报错,当前实例不受影响。
*/
const {
VERSIONS,
buildFreePortLines,
buildHealthCheckLines,
buildNginxSwitchLines,
buildScopedEggStopLines,
buildStartInstanceLines,
ensureCommandAvailable,
loadDeployConfig,
otherVersion,
portOf,
quoteForBash,
readRemoteCurrentVersion,
runSsh,
} = require('./deploy-lib.cjs');
/**
* 解析 --to=v1|v2 参数
* @param {String[]} argv 参数数组
* @return {String} 目标版本(未指定时返回空字符串)
*/
function parseTargetArg(argv) {
const arg = argv.find(item => item.startsWith('--to='));
if (!arg) return '';
const value = arg.slice('--to='.length).trim();
if (!VERSIONS.includes(value)) {
throw new Error(`--to 取值无效: ${value}(支持 v1 / v2)`);
}
return value;
}
function main() {
const envName = process.argv[2] || 'production';
const config = loadDeployConfig(envName);
ensureCommandAvailable('ssh', '请先安装 OpenSSH Client 并确保 ssh 在 PATH 中。');
const currentVersion = readRemoteCurrentVersion(config);
if (!currentVersion) {
throw new Error(`远端 ${config.deployRoot}/current.md 不存在或为空,没有可回滚的版本(请先执行 npm run deploy)。`);
}
const targetVersion = parseTargetArg(process.argv.slice(3)) || otherVersion(currentVersion);
if (targetVersion === currentVersion) {
throw new Error(`目标版本与当前活跃版本相同(${targetVersion}),无需回滚。`);
}
const currentPort = portOf(config, currentVersion);
const targetPort = portOf(config, targetVersion);
const currentDir = `${config.deployRoot}/${currentVersion}`;
const targetDir = `${config.deployRoot}/${targetVersion}`;
const startLogPath = `/tmp/oms-${targetVersion}-start.log`;
console.log(`当前活跃版本: ${currentVersion}(端口 ${currentPort})`);
console.log(`回滚目标: ${targetVersion} → ${targetDir}(端口 ${targetPort})`);
// 1. 校验目标版本可用;缺依赖时补装
runSsh(config, [
'set -euo pipefail',
`TARGET_DIR=${quoteForBash(targetDir)}`,
'if [ ! -f "$TARGET_DIR/package.json" ]; then',
' echo "目标版本目录不可用:$TARGET_DIR/package.json 不存在(该版本可能尚未发布过)" >&2',
' exit 1',
'fi',
'if [ ! -d "$TARGET_DIR/node_modules" ]; then',
' echo "目标版本缺少 node_modules,先安装依赖..."',
` ( cd "$TARGET_DIR" && ${config.installCommand} )`,
'fi',
].join('\n'));
// 2. 释放目标端口并启动目标实例
runSsh(config, [ 'set -euo pipefail', ...buildFreePortLines(targetPort) ].join('\n'));
runSsh(config, [
'set -euo pipefail',
...buildStartInstanceLines(targetDir, config.startCommand, startLogPath),
].join('\n'));
// 3. 健康检查(失败则清理刚启动的实例,当前实例继续服务)
try {
runSsh(config, [
'set -euo pipefail',
...buildHealthCheckLines(targetPort, config.healthCheckPath, targetVersion),
].join('\n'));
} catch (err) {
console.error(`[ERROR] 回滚目标健康检查失败: ${err.message}`);
console.error(`[ERROR] 回滚中止(未切换 Nginx),请查看启动日志 ${startLogPath}`);
try {
runSsh(config, [
'set -euo pipefail',
...buildScopedEggStopLines(targetDir, 'STOP_ROLLBACK_TARGET'),
].join('\n'));
} catch (killErr) {
console.error(`[ERROR] 清理回滚目标实例出错: ${killErr.message}`);
}
console.error(`[ERROR] 当前实例(${currentVersion})仍在服务,线上不受影响`);
process.exit(1);
}
// 4. 切换 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`);
}
// 5. 记录 current.md 并停止原实例
runSsh(config, [
'set -euo pipefail',
`printf '%s\\n' ${quoteForBash(targetVersion)} > ${quoteForBash(`${config.deployRoot}/current.md`)}`,
...buildScopedEggStopLines(currentDir, 'STOP_ROLLED_BACK'),
`echo "current.md 已更新为 ${targetVersion}"`,
].join('\n'));
console.log(`回滚完成: 线上已切回 ${targetVersion}(端口 ${targetPort})`);
console.log(`如需再次前进,执行 npm run rollback -- --to=${currentVersion}`);
}
main();