wms_worker_station_service/script/rollback-remote.cjs
liufumingren 561cd27f81 初始化
2026-07-25 00:46:47 +08:00

232 lines
8.4 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,
ensureCommandAvailable,
loadDeployConfig,
quoteForBash,
runSsh,
} = require('./deploy-lib.cjs');
/**
* 通过 SSH 读取远端 current.md 文件,获取当前活跃版本标识(v1 或 v2)
*
* @param {object} config - 部署配置对象
* @param {string} deployRoot - 远端部署根目录,如 /www/wwwroot/ye4s
* @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 → 7071,v2 → 7072)
*
* @param {string} targetVersion - 目标版本标识,'v1' 或 'v2'
* @return {number} 对应端口号
*/
function getTargetPort(targetVersion) {
if (targetVersion === 'v1') {
return 7071;
}
return 7072;
}
/**
* 解析命令行中的 --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();
}
/**
* 根据版本标识返回进程 title(v1 → egg-server-ye4s-v1,v2 → egg-server-ye4s-v2)
*
* @param {string} version - 版本标识,'v1' 或 'v2'
* @return {string} 进程 title
*/
function getProcessTitle(version) {
return `egg-server-ye4s-${version}`;
}
/**
* 回滚入口函数:
* 读取远端 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);
const currentTitle = getProcessTitle(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 "SELECTED_BACKUP=$TARGET_BACKUP"',
'echo "$TARGET_BACKUP"',
].join('\n');
const selectedBackup = runSsh(config, selectBackupScript, { stdio: 'pipe' }).trim();
const backupFile = selectedBackup.replace(/^SELECTED_BACKUP=/, '').split('\n').pop().trim();
if (!backupFile || backupFile.startsWith('ERROR:')) {
throw new Error(selectedBackup);
}
console.log(`使用备份包: ${config.backupDir}/${backupFile}`);
// 3. 停止当前活跃实例
const stopCurrentScript = [
'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=$(ps -eo pid=,args= | awk -v root="$CURRENT_DIR" \'index($0, root) && $2 ~ /node$/ { print $1 }\')',
' if [ -n "$REMAIN" ]; then',
' kill -9 $REMAIN || true',
' fi',
' echo "当前实例 ($CURRENT_VERSION) 已停止"',
'fi',
].join('\n');
try {
const stopOutput = runSsh(config, stopCurrentScript, { stdio: 'pipe' });
console.log(String(stopOutput || '').trim());
} catch (err) {
console.warn(`[WARN] 停止当前实例失败: ${err.message}`);
}
// 4. 清理当前活跃目录并解压备份包
const cleanupGuard = buildRemoteCleanupGuard(config.sharedDirs, config.preserveDirs);
const rollbackScript = [
'set -euo pipefail',
`CURRENT_DIR=${quoteForBash(currentDir)}`,
`BACKUP_DIR=${quoteForBash(config.backupDir)}`,
`BACKUP_FILE=${quoteForBash(backupFile)}`,
'cd "$CURRENT_DIR"',
`find . -mindepth 1 -maxdepth 1 ${cleanupGuard} -exec rm -rf {} +`,
'tar -xzf "$BACKUP_DIR/$BACKUP_FILE" -C "$CURRENT_DIR"',
'npm install --production',
'echo "备份包已解压并安装依赖: $BACKUP_FILE"',
].join('\n');
runSsh(config, rollbackScript);
console.log(`回滚包已解压到: ${currentDir}`);
// 5. 重启当前实例(指定端口和版本专用 title)
const startLogPath = `/tmp/ye4s-${currentVersion}-rollback.log`;
const restartScript = [
'set -euo pipefail',
`cd ${quoteForBash(currentDir)}`,
`nohup bash -lc 'npx egg-scripts start --daemon --title=${currentTitle} --sticky --port=${currentPort} --ignore-stderr' > ${quoteForBash(startLogPath)} 2>&1 &`,
`echo "已在 ${currentDir} 重启实例 ${currentVersion} (title=${currentTitle}, 端口 ${currentPort}),启动日志: ${startLogPath}"`,
].join('\n');
const restartOutput = runSsh(config, restartScript, { stdio: 'pipe' });
console.log(String(restartOutput || '').trim());
// 6. 健康检查
const healthCheckScript = [
'set -euo pipefail',
`TARGET_PORT=${currentPort}`,
'for attempt in $(seq 1 30); do',
' if curl -fsS --connect-timeout 2 --max-time 4 "http://127.0.0.1:$TARGET_PORT/" >/dev/null 2>&1; then',
` echo "回滚实例 (${currentVersion}) 健康检查通过 (端口 $TARGET_PORT)"`,
' break',
' fi',
' if [ "$attempt" -eq 30 ]; then',
` echo "回滚实例 (${currentVersion}) 健康检查超时 (端口 $TARGET_PORT)" >&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}`);
}
// 7. 确保 Nginx upstream 指向当前端口
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.log('========================================');
console.log(`回滚完成: ${currentVersion} (端口 ${currentPort})`);
console.log(`使用备份包: ${backupFile}`);
console.log('========================================');
}
main();