WMS_MAIN/script/rollback-remote.cjs
liufumingren b1000fd0e8 chore(deploy): 证书同步双环境配置发布约定落地
- 发布/回退链路新增固定文件排除与保护:warehouse-cert-sync 两份环境配置不进发布包、清理时暂存/放回,服务器副本不被覆盖/删除(deploy-lib 独立常量 + 共用守卫函数)

- deploy-cert-sync 新增 config-check 只读核对;install 对 prod 配置首次放置一次、之后永不覆盖;dev 配置永不上传生产

- 薄包装简化:nginx 二进制/upstream/reload 全部收敛到 prod 配置,包装仅保留 cwd+依赖+DB 运行时引导

- 新增 warehouse-cert-sync.cjs 与 dev/prod 双环境配置;package.json 增加 deploy:cert-sync:config-check
2026-09-08 04:26:39 +08:00

228 lines
8.8 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';
const path = require('node:path');
const {
buildRemoteCleanupGuard,
buildPinnedConfigGuardLines,
ensureCommandAvailable,
loadDeployConfig,
quoteForBash,
runSsh,
} = require('./deploy-lib.cjs');
/**
* 通过 SSH 读取远端 current.md 文件,获取当前活跃版本标识(v1 或 v2)
*
* @param {object} config - 部署配置对象
* @param {string} deployRoot - 远端部署根目录,如 /www/wwwroot/qimen
* @return {string} 当前活跃版本标识,如 'v1' 或 'v2'
* @throws {Error} 如果读取失败或内容无效
*/
function readRemoteCurrentVersion(config, deployRoot) {
const currentMdPath = `${deployRoot}/current.md`;
const script = `cat ${quoteForBash(currentMdPath)} 2>/dev/null || true`;
const output = runSsh(config, script, { stdio: 'pipe' });
const rawVersion = String(output || '').trim();
if (!rawVersion) {
throw new Error(
`无法读取远端当前版本文件: ${currentMdPath}。请确保远端已存在 ${deployRoot}/current.md 且内容为 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;
}
/**
* 根据版本标识返回对应监听端口(v1 → 6061,v2 → 6062)
*
* @param {string} targetVersion - 目标版本标识,'v1' 或 'v2'
* @return {number} 对应端口号
*/
function getTargetPort(targetVersion) {
if (targetVersion === 'v1') {
return 6061;
}
return 6062;
}
/**
* 解析命令行中的 --backup= 参数,提取备份包名称
*
* @param {string[]} argv - 命令行参数数组
* @return {string} 备份包名称,如未指定则返回空字符串
*/
function parseBackupArg(argv) {
const backupArg = argv.find(item => item.startsWith('--backup='));
if (!backupArg) {
return '';
}
return backupArg.slice('--backup='.length).trim();
}
/**
* 回滚入口函数:
* 读取远端 current.md → 确定当前活跃版本目录和端口 → 选择备份包
* → 停进程 → 清理代码 → 解压备份 → npm install → 重启 → 健康检查 → 切换 Nginx
*/
function main() {
const envName = process.argv[2] || 'production';
const config = loadDeployConfig(envName);
const backupName = parseBackupArg(process.argv.slice(3));
ensureCommandAvailable('ssh', '请先安装 OpenSSH Client 并确保 ssh 在 PATH 中。');
// 1. 读取远端 current.md,确定当前活跃版本和目录
const currentVersion = readRemoteCurrentVersion(config, config.deployRoot);
const currentDir = `${config.deployRoot}/${currentVersion}`;
const currentPort = getTargetPort(currentVersion);
console.log(`远端当前活跃版本: ${currentVersion},活跃目录: ${currentDir},端口: ${currentPort}`);
// 2. 确定备份包
const latestBackupFile = path.posix.join(config.stateDir, 'latest-backup.txt');
const selectBackupScript = [
'set -euo pipefail',
`BACKUP_DIR=${quoteForBash(config.backupDir)}`,
`LATEST_BACKUP_FILE=${quoteForBash(latestBackupFile)}`,
`REQUESTED_BACKUP=${quoteForBash(backupName)}`,
'if [ -n "$REQUESTED_BACKUP" ]; then',
' TARGET_BACKUP="$REQUESTED_BACKUP"',
'elif [ -f "$LATEST_BACKUP_FILE" ]; then',
' TARGET_BACKUP="$(cat "$LATEST_BACKUP_FILE")"',
'else',
' echo "ERROR: 未找到最近一次发布备份,请通过 --backup=backup-时间戳.tar.gz 指定回退包。" >&2',
' exit 1',
'fi',
'if [ ! -f "$BACKUP_DIR/$TARGET_BACKUP" ]; then',
' echo "ERROR: 回退包不存在: $BACKUP_DIR/$TARGET_BACKUP" >&2',
' exit 1',
'fi',
'echo "$TARGET_BACKUP"',
].join('\n');
const targetBackup = runSsh(config, selectBackupScript, { stdio: 'pipe' });
console.log(`回退包: ${targetBackup}`);
// 3. 停止当前活跃版本的进程(ps + awk 匹配目录 + kill + kill -9 兜底)
const stopScript = [
'set -euo pipefail',
`CURRENT_DIR=${quoteForBash(currentDir)}`,
`CURRENT_VERSION=${quoteForBash(currentVersion)}`,
'CURRENT_PIDS=$(ps -eo pid=,args= | awk -v root="$CURRENT_DIR" \'index($0, root) && $2 ~ /node$/ { print $1 }\')',
'if [ -z "$CURRENT_PIDS" ]; then',
' echo "未找到当前活跃实例 ($CURRENT_VERSION) 进程,跳过停止步骤"',
'else',
' echo "正在停止当前活跃实例 ($CURRENT_VERSION): $CURRENT_PIDS"',
' kill $CURRENT_PIDS || true',
' sleep 3',
' REMAIN_PIDS=$(ps -eo pid=,args= | awk -v root="$CURRENT_DIR" \'index($0, root) && $2 ~ /node$/ { print $1 }\')',
' if [ -n "$REMAIN_PIDS" ]; then',
' echo "当前活跃实例 ($CURRENT_VERSION) 仍有残留进程,强制停止: $REMAIN_PIDS"',
' kill -9 $REMAIN_PIDS || true',
' fi',
' echo "当前活跃实例 ($CURRENT_VERSION) 已停止"',
'fi',
].join('\n');
try {
const stopOutput = runSsh(config, stopScript, { stdio: 'pipe' });
console.log(String(stopOutput || '').trim());
} catch (err) {
console.warn(`[WARN] 停止当前活跃实例失败: ${err.message}`);
console.warn(`[WARN] 继续回退流程,请人工确认 ${currentDir} 进程状态`);
}
// 4. 在活跃目录清理旧代码、解压备份包、安装依赖
// 固定文件保护:与发布链路一致,清理前暂存、解压后放回
// warehouse-cert-sync 双环境配置文件,避免回退覆盖/删除服务器既有副本。
const pinnedStashDir = `/tmp/wms-pinned-rollback-${currentVersion}`;
const pinnedGuard = buildPinnedConfigGuardLines('CURRENT_DIR', 'PINNED_DIR');
const cleanupGuard = buildRemoteCleanupGuard(config.sharedDirs, config.preserveDirs);
const restoreScript = [
'set -euo pipefail',
`CURRENT_DIR=${quoteForBash(currentDir)}`,
`BACKUP_DIR=${quoteForBash(config.backupDir)}`,
`TARGET_BACKUP=${quoteForBash(targetBackup)}`,
`PINNED_DIR=${quoteForBash(pinnedStashDir)}`,
...pinnedGuard.stash,
'cd "$CURRENT_DIR"',
`find . -mindepth 1 -maxdepth 1 ${cleanupGuard} -exec rm -rf {} +`,
'echo "旧代码已清理完成"',
'tar -xzf "$BACKUP_DIR/$TARGET_BACKUP" -C "$CURRENT_DIR"',
'echo "备份包已解压到 $CURRENT_DIR"',
...pinnedGuard.restore,
'npm install --production',
'echo "生产依赖安装完成"',
].join('\n');
runSsh(config, restoreScript);
console.log(`当前活跃目录已恢复为备份包内容: ${currentDir}`);
// 5. 重启当前活跃版本
const startLogPath = `/tmp/wms-${currentVersion}-rollback-start.log`;
const startScript = [
'set -euo pipefail',
`cd ${quoteForBash(currentDir)}`,
`nohup bash -lc 'npm start' > ${quoteForBash(startLogPath)} 2>&1 &`,
`echo "已在 ${currentDir} 重启当前活跃实例 (${currentVersion}),启动日志: ${startLogPath}"`,
].join('\n');
const startOutput = runSsh(config, startScript, { stdio: 'pipe' });
console.log(String(startOutput || '').trim());
// 6. 健康检查当前活跃端口(curl 循环,最多 30 次 × 2 秒)
const healthCheckScript = [
'set -euo pipefail',
`CURRENT_PORT=${currentPort}`,
`CURRENT_VERSION=${quoteForBash(currentVersion)}`,
'for attempt in $(seq 1 30); do',
' if curl -fsS --connect-timeout 2 --max-time 4 "http://127.0.0.1:$CURRENT_PORT/" >/dev/null 2>&1; then',
` echo "当前活跃实例 (${currentVersion}) 健康检查通过 (端口 ${currentPort})"`,
' break',
' fi',
' if [ "$attempt" -eq 30 ]; then',
` echo "当前活跃实例 (${currentVersion}) 健康检查超时 (端口 ${currentPort})" >&2`,
' exit 1',
' fi',
' sleep 2',
'done',
].join('\n');
try {
const healthOutput = runSsh(config, healthCheckScript, { stdio: 'pipe' });
console.log(String(healthOutput || '').trim());
} catch (err) {
console.warn(`[WARN] 当前活跃实例健康检查失败: ${err.message}`);
console.warn(`[WARN] 当前活跃实例 (${currentVersion}) 可能未完全就绪,请人工确认 127.0.0.1:${currentPort} 状态`);
}
// 7. 更新 Nginx upstream 指向当前活跃端口并 reload
const nginxUpstreamPath = `${config.deployRoot}/nginx-upstream.conf`;
const switchNginxScript = [
'set -euo pipefail',
`printf 'proxy_pass http://127.0.0.1:%s;\\n' ${currentPort} > ${quoteForBash(nginxUpstreamPath)}`,
'nginx -t && nginx -s reload',
`echo "Nginx upstream 已指向 127.0.0.1:${currentPort}"`,
].join('\n');
try {
const nginxOutput = runSsh(config, switchNginxScript, { stdio: 'pipe' });
console.log(String(nginxOutput || '').trim());
} catch (err) {
console.warn(`[WARN] Nginx upstream 切换失败: ${err.message}`);
console.warn(`[WARN] Nginx reload 可能未成功,请人工确认 ${nginxUpstreamPath} 内容并执行 nginx -s reload`);
}
console.log(`回退完成: ${envName} -> ${config.username}@${config.host}:${currentDir}`);
}
main();