oms/backend/script/deploy-lib.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

499 lines
17 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';
/**
* 后端发布公共库(配置加载/校验、SSH/SCP 封装、发布包构建、远端脚本片段)
*
* 发布模型:双实例蓝绿(参考 WMS 后端)
* <deployRoot>/{v1,v2} 两套代码目录,发布时交替部署
* <deployRoot>/current.md 当前活跃版本(v1 / v2)
* <deployRoot>/nginx-upstream.conf Nginx 反代目标(proxy_pass http://127.0.0.1:<端口>;)
* <deployRoot>/.deploy/incoming 上传的发布包
* <deployRoot>/.deploy/state 状态文件(当前发布版本号)
*/
const fs = require('node:fs');
const path = require('node:path');
const { spawnSync } = require('node:child_process');
/** backend 根目录(本文件在 backend/script 下) */
const ROOT = path.resolve(__dirname, '..');
const LOCAL_CONFIG_PATH = path.join(ROOT, 'config', 'deploy.config.local.cjs');
const EXAMPLE_CONFIG_PATH = path.join(ROOT, 'config', 'deploy.config.example.cjs');
const DEFAULT_ENV = 'production';
const VERSIONS = [ 'v1', 'v2' ];
/** 发布包默认包含的文件(相对 backend 根目录) */
const DEFAULT_INCLUDE_PATHS = [
'app.js',
'app/**',
'config/**',
'database/**',
'package.json',
'package-lock.json',
];
/** 发布包默认排除(叠加在 include 之上) */
const DEFAULT_EXCLUDE_PATHS = [
'config/deploy.config.local.cjs',
'config/deploy.config.example.cjs',
'.env',
'.env.*',
'uploads/**',
'logs/**',
'run/**',
'temp/**',
'test/**',
'swagger.json',
];
/**
* bash 单引号字符串里的单引号转义(' → '\'')
* @param {String} value 原始值
* @return {String} 可安全放进单引号中的字符串
*/
function quoteForBash(value) {
return `'${String(value).replace(/'/g, "'\\''")}'`;
}
/**
* 执行本地命令
* @param {String} command 命令
* @param {String[]} args 参数
* @param {Object} [options] 选项(cwd / stdio)
* @return {String} stdout(trim 后)
*/
function runCommand(command, args, options = {}) {
const result = spawnSync(command, args, {
cwd: options.cwd || ROOT,
encoding: 'utf8',
stdio: options.stdio || 'pipe',
shell: false,
});
if (result.error) throw result.error;
if (result.status !== 0) {
const stderr = (result.stderr || '').trim();
const stdout = (result.stdout || '').trim();
throw new Error(stderr || stdout || `${command} 退出码 ${result.status}`);
}
return (result.stdout || '').trim();
}
/**
* 检查本地命令是否存在(不存在时给出安装提示)
* @param {String} command 命令名
* @param {String} installHint 安装提示
* @return {void}
*/
function ensureCommandAvailable(command, installHint) {
const result = spawnSync(command, [], { cwd: ROOT, encoding: 'utf8', stdio: 'pipe', shell: false });
if (result.error && result.error.code === 'ENOENT') {
throw new Error(`${command} 不可用。${installHint}`);
}
}
/** @return {String} yyyyMMddHHmmss 时间戳 */
function getNowStamp() {
const now = new Date();
const pad = value => String(value).padStart(2, '0');
return `${now.getFullYear()}${pad(now.getMonth() + 1)}${pad(now.getDate())}${pad(now.getHours())}${pad(now.getMinutes())}${pad(now.getSeconds())}`;
}
/** @return {String} 本地临时工作目录 backend/temp/deploy(自动创建) */
function ensureTempDeployDir() {
const tempDir = path.join(ROOT, 'temp', 'deploy');
fs.mkdirSync(tempDir, { recursive: true });
return tempDir;
}
/**
* 是否为未填写的占位值
* @param {String} value 值
* @return {Boolean} 是占位值返回 true
*/
function isPlaceholder(value) {
if (!value) return true;
return String(value).includes('__FILL_');
}
/**
* 校验并补齐配置默认值
* @param {Object} config 原始配置
* @param {String} envName 环境名
* @return {Object} 规范化后的配置
*/
function normalizeDeployConfig(config, envName) {
const sshOptions = Array.isArray(config.sshOptions) ? [ ...config.sshOptions ] : [];
const guardedOptions = [
'IdentitiesOnly=yes',
'PreferredAuthentications=publickey',
'PubkeyAuthentication=yes',
'PasswordAuthentication=no',
'KbdInteractiveAuthentication=no',
'BatchMode=yes',
'ConnectTimeout=10',
];
for (const option of guardedOptions) {
const key = option.split('=')[0];
if (!sshOptions.some(item => new RegExp(`^${key}=`, 'i').test(item))) sshOptions.push(option);
}
const deployRoot = String(config.deployRoot || '/www/wwwroot/api.oms.gztbyc.com').replace(/\/+$/, '');
const ports = config.ports || {};
return {
envName,
host: config.host,
port: Number(config.port || 22),
username: config.username,
// 支持绝对路径(Windows 下如 C:/Users/x/.ssh/id_ed25519)与相对 backend 根目录的路径
privateKeyPath: config.privateKeyPath ? path.resolve(ROOT, config.privateKeyPath) : '',
deployRoot,
ports: { v1: Number(ports.v1 || 6090), v2: Number(ports.v2 || 6091) },
incomingDir: `${deployRoot}/.deploy/incoming`,
stateDir: `${deployRoot}/.deploy/state`,
sharedDirs: Array.isArray(config.sharedDirs) ? config.sharedDirs : [ 'logs', 'run', 'node_modules' ],
deployIncludePaths: Array.isArray(config.deployIncludePaths) && config.deployIncludePaths.length
? config.deployIncludePaths
: DEFAULT_INCLUDE_PATHS,
deployExcludePaths: Array.isArray(config.deployExcludePaths) && config.deployExcludePaths.length
? config.deployExcludePaths
: DEFAULT_EXCLUDE_PATHS,
installCommand: config.installCommand || 'npm install --production',
startCommand: config.startCommand || 'npm start',
healthCheckPath: config.healthCheckPath || '/',
sshOptions,
};
}
/**
* 校验配置必填项
* @param {Object} config 原始配置
* @param {String} configPath 配置文件路径
* @param {String} envName 环境名
* @return {void}
*/
function validateDeployConfig(config, configPath, envName) {
if (!config) throw new Error(`${configPath} 中未找到 ${envName} 配置。`);
const missing = [];
if (isPlaceholder(config.host)) missing.push('host');
if (isPlaceholder(config.username)) missing.push('username');
if (isPlaceholder(config.privateKeyPath)) missing.push('privateKeyPath');
if (missing.length) {
throw new Error(`请先完善配置字段: ${missing.join(', ')}。配置文件: ${configPath}`);
}
const resolvedPrivateKeyPath = path.resolve(ROOT, config.privateKeyPath);
if (!fs.existsSync(resolvedPrivateKeyPath)) {
throw new Error(`SSH 私钥不存在: ${resolvedPrivateKeyPath}。请修正 ${configPath} 中的 privateKeyPath。`);
}
}
/**
* 加载本地部署配置
* @param {String} [envName] 环境名,默认 production
* @return {Object} 规范化后的配置
*/
function loadDeployConfig(envName = DEFAULT_ENV) {
if (!fs.existsSync(LOCAL_CONFIG_PATH)) {
throw new Error(`缺少本地部署配置 ${LOCAL_CONFIG_PATH}。请复制 ${EXAMPLE_CONFIG_PATH} 为 deploy.config.local.cjs 并填写 SSH 信息。`);
}
delete require.cache[require.resolve(LOCAL_CONFIG_PATH)];
const loaded = require(LOCAL_CONFIG_PATH);
const config = loaded[envName];
validateDeployConfig(config, LOCAL_CONFIG_PATH, envName);
return normalizeDeployConfig(config, envName);
}
/**
* 构造 ssh/scp 公共参数
* @param {Object} config 部署配置
* @return {String[]} 参数数组
*/
function buildSshBaseArgs(config) {
const args = [ '-p', String(config.port), '-i', config.privateKeyPath ];
for (const option of config.sshOptions) args.push('-o', option);
return args;
}
/**
* 在服务器上执行 bash 脚本(通过 bash -lc,保证加载登录环境里的 node/npm)
* @param {Object} config 部署配置
* @param {String} remoteScript 脚本内容
* @param {Object} [options] 选项(stdio)
* @return {String} 输出
*/
function runSsh(config, remoteScript, options = {}) {
const args = [
...buildSshBaseArgs(config),
`${config.username}@${config.host}`,
`bash -lc ${quoteForBash(remoteScript)}`,
];
return runCommand('ssh', args, { stdio: options.stdio || 'inherit' });
}
/**
* 上传文件到服务器
* @param {Object} config 部署配置
* @param {String} localPath 本地路径
* @param {String} remotePath 远端路径
* @return {String} 输出
*/
function runScp(config, localPath, remotePath) {
const args = [ '-P', String(config.port), '-i', config.privateKeyPath ];
for (const option of config.sshOptions) args.push('-o', option);
args.push(localPath, `${config.username}@${config.host}:${remotePath}`);
return runCommand('scp', args, { stdio: 'inherit' });
}
/**
* 判断路径是否命中规则(`a/**` 匹配 a 及其全部子项,其余为精确匹配)
* @param {String} filePath 相对路径
* @param {String} rule 规则
* @return {Boolean} 命中返回 true
*/
function pathMatchesRule(filePath, rule) {
const normalizedPath = String(filePath || '').replace(/\\/g, '/');
const normalizedRule = String(rule || '').replace(/\\/g, '/').trim();
if (!normalizedRule) return false;
if (normalizedRule.endsWith('/**')) {
const prefix = normalizedRule.slice(0, -3);
return normalizedPath === prefix || normalizedPath.startsWith(`${prefix}/`);
}
return normalizedPath === normalizedRule;
}
/**
* 列出可发布文件:以 git 的视角取文件(天然排除 .gitignore 里的 .env / uploads 等),
* 再按 include / exclude 规则过滤
* @param {Object} config 部署配置
* @return {String[]} 相对 backend 根目录的文件列表
*/
function listDeployableFiles(config) {
const output = runCommand('git', [ 'ls-files', '--cached', '--others', '--exclude-standard' ], { cwd: ROOT });
return Array.from(new Set(
output
.split(/\r?\n/)
.map(item => item.trim())
.filter(Boolean)
.filter(item => !item.startsWith('.git/'))
.filter(item => fs.existsSync(path.join(ROOT, item)))
.filter(item => config.deployIncludePaths.some(rule => pathMatchesRule(item, rule)))
.filter(item => !config.deployExcludePaths.some(rule => pathMatchesRule(item, rule)))
));
}
/**
* 构建本地发布包(tar.gz)
* @param {String} stamp 时间戳
* @param {Object} config 部署配置
* @return {{ archivePath: String, fileCount: Number }} 发布包路径与文件数
*/
function buildArchive(stamp, config) {
const tempDir = ensureTempDeployDir();
const listPath = path.join(tempDir, `deploy-files-${stamp}.txt`);
const archivePath = path.join(tempDir, `release-${stamp}.tar.gz`);
const files = listDeployableFiles(config);
if (!files.length) throw new Error('未找到可发布文件(请检查 deployIncludePaths 配置)。');
fs.writeFileSync(listPath, `${files.join('\n')}\n`, 'utf8');
runCommand('tar', [ '-czf', archivePath, '-T', listPath ], { stdio: 'inherit', cwd: ROOT });
return { archivePath, fileCount: files.length };
}
/**
* 生成远端清理守卫:`find . -mindepth 1 -maxdepth 1 <守卫> -exec rm -rf {} +`
* 保留 .deploy 与 sharedDirs(logs / run / node_modules 等)
* @param {String[]} sharedDirs 需保留的目录名
* @return {String} find 命令的守卫参数
*/
function buildRemoteCleanupGuard(sharedDirs) {
const preserved = [ '.deploy', ...sharedDirs ];
return preserved.map(item => `! -name ${quoteForBash(item)}`).join(' ');
}
/**
* 生成「按目录停止 egg 进程」的远端脚本行:
* 通过 ps 匹配命令行里的版本目录 + node,先 kill 再 kill -9 兜底。
* 不用 `npm run stop`(egg-scripts 按 title 停止,v1/v2 同 title 会互相误杀)。
* @param {String} dirPath 目标目录绝对路径
* @param {String} label 日志前缀
* @return {String[]} 脚本行
*/
function buildScopedEggStopLines(dirPath, label) {
const matchNode = '$2 == "node" || $2 ~ /\\/node$/';
const awkProgram = `index($0, root) && (${matchNode}) { print $1 }`;
return [
`TARGET_DIR=${quoteForBash(dirPath)}`,
`TARGET_PIDS=$(ps -eo pid=,args= | awk -v root="$TARGET_DIR" ${quoteForBash(awkProgram)})`,
'if [ -z "$TARGET_PIDS" ]; then',
` echo "${label}_NONE"`,
'else',
` echo "${label} $TARGET_PIDS"`,
' kill $TARGET_PIDS || true',
' sleep 5',
` REMAIN_PIDS=$(ps -eo pid=,args= | awk -v root="$TARGET_DIR" ${quoteForBash(awkProgram)})`,
' if [ -n "$REMAIN_PIDS" ]; then',
` echo "${label}_FORCE $REMAIN_PIDS"`,
' kill -9 $REMAIN_PIDS || true',
' fi',
'fi',
];
}
/**
* 读取远端当前活跃版本
* @param {Object} config 部署配置
* @return {String} 'v1' / 'v2';尚未初始化(无 current.md)时返回空字符串
*/
function readRemoteCurrentVersion(config) {
const currentMdPath = `${config.deployRoot}/current.md`;
const script = `cat ${quoteForBash(currentMdPath)} 2>/dev/null || true`;
const output = String(runSsh(config, script, { stdio: 'pipe' }) || '').replace(/\r/g, '').trim();
if (!output) return '';
if (!VERSIONS.includes(output)) {
throw new Error(`远端 ${currentMdPath} 内容无效: "${output}",期望 v1 或 v2。`);
}
return output;
}
/**
* 取另一个版本标识(v1 ↔ v2)
* @param {String} version 当前版本,为空时返回首次部署使用的 v1
* @return {String} 目标版本
*/
function otherVersion(version) {
if (!version) return 'v1';
if (!VERSIONS.includes(version)) throw new Error(`版本标识无效: ${version}`);
return version === 'v1' ? 'v2' : 'v1';
}
/**
* 取版本对应端口
* @param {Object} config 部署配置
* @param {String} version 版本标识
* @return {Number} 端口
*/
function portOf(config, version) {
if (!VERSIONS.includes(version)) throw new Error(`版本标识无效: ${version}`);
return config.ports[version];
}
/**
* 生成「释放指定端口」的远端脚本行(结束占用该端口的残留进程)
* @param {Number} port 端口
* @return {String[]} 脚本行
*/
function buildFreePortLines(port) {
return [
`TARGET_PORT=${port}`,
'PORT_PID=$(ss -tlnp 2>/dev/null | awk -v p=":$TARGET_PORT " \'index($0, p) { print $0 }\' | grep -oP \'pid=\\K[0-9]+\' | head -1 || true)',
'if [ -n "$PORT_PID" ]; then',
' echo "端口 $TARGET_PORT 被进程 $PORT_PID 占用,先停止..."',
' kill "$PORT_PID" 2>/dev/null || true',
' sleep 5',
' PORT_PID_CHECK=$(ss -tlnp 2>/dev/null | awk -v p=":$TARGET_PORT " \'index($0, p) { print $0 }\' | grep -oP \'pid=\\K[0-9]+\' | head -1 || true)',
' if [ -n "$PORT_PID_CHECK" ]; then',
' echo "端口 $TARGET_PORT 仍有残留进程 $PORT_PID_CHECK,强制停止"',
' kill -9 "$PORT_PID_CHECK" 2>/dev/null || true',
' fuser -k "$TARGET_PORT/tcp" 2>/dev/null || true',
' fi',
'else',
' echo "端口 $TARGET_PORT 空闲"',
'fi',
];
}
/**
* 生成「启动实例」的远端脚本行(后台运行,输出重定向到启动日志)
* @param {String} dirPath 版本目录
* @param {String} startCommand 启动命令(如 npm start)
* @param {String} logPath 启动日志路径
* @return {String[]} 脚本行
*/
function buildStartInstanceLines(dirPath, startCommand, logPath) {
return [
`cd ${quoteForBash(dirPath)}`,
`nohup bash -lc ${quoteForBash(startCommand)} > ${quoteForBash(logPath)} 2>&1 < /dev/null &`,
`echo "已启动实例: ${dirPath},启动日志: ${logPath}"`,
];
}
/**
* 生成「健康检查」的远端脚本行(轮询 http://127.0.0.1:<端口><路径>)
* @param {Number} port 端口
* @param {String} healthPath 检查路径
* @param {String} label 日志标签
* @param {Number} [attempts] 重试次数
* @param {Number} [interval] 重试间隔秒数
* @return {String[]} 脚本行
*/
function buildHealthCheckLines(port, healthPath, label, attempts = 10, interval = 2) {
return [
`TARGET_PORT=${port}`,
`HEALTH_PATH=${quoteForBash(healthPath)}`,
`for attempt in $(seq 1 ${attempts}); do`,
' if curl -fsS --connect-timeout 2 --max-time 3 "http://127.0.0.1:$TARGET_PORT$HEALTH_PATH" >/dev/null 2>&1; then',
` echo "健康检查通过: ${label} 已就绪(端口 $TARGET_PORT)"`,
' break',
' fi',
` if [ "$attempt" -eq ${attempts} ]; then`,
` echo "健康检查超时: ${label}(端口 $TARGET_PORT)未就绪" >&2`,
' exit 1',
' fi',
` sleep ${interval}`,
'done',
];
}
/**
* 生成「切换 Nginx upstream 并 reload」的远端脚本行
* @param {String} upstreamPath upstream 文件路径
* @param {Number} port 目标端口
* @return {String[]} 脚本行
*/
function buildNginxSwitchLines(upstreamPath, port) {
return [
`printf 'proxy_pass http://127.0.0.1:%s;\\n' ${port} > ${quoteForBash(upstreamPath)}`,
'nginx -t && nginx -s reload',
`echo "Nginx upstream 已切换至 127.0.0.1:${port}"`,
];
}
module.exports = {
ROOT,
VERSIONS,
DEFAULT_ENV,
LOCAL_CONFIG_PATH,
EXAMPLE_CONFIG_PATH,
buildArchive,
buildFreePortLines,
buildHealthCheckLines,
buildNginxSwitchLines,
buildRemoteCleanupGuard,
buildScopedEggStopLines,
buildSshBaseArgs,
buildStartInstanceLines,
ensureCommandAvailable,
ensureTempDeployDir,
getNowStamp,
listDeployableFiles,
loadDeployConfig,
otherVersion,
pathMatchesRule,
portOf,
quoteForBash,
readRemoteCurrentVersion,
runCommand,
runScp,
runSsh,
};