197 lines
7.2 KiB
JavaScript
197 lines
7.2 KiB
JavaScript
'use strict';
|
|
|
|
const path = require('node:path');
|
|
const {
|
|
buildRemoteCleanupGuard,
|
|
ensureCommandAvailable,
|
|
loadDeployConfig,
|
|
quoteForBash,
|
|
runSsh,
|
|
} = require('./deploy-lib.cjs');
|
|
|
|
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;
|
|
}
|
|
|
|
function getTargetPort(targetVersion) {
|
|
if (targetVersion === 'v1') return 4051;
|
|
return 4052;
|
|
}
|
|
|
|
function parseBackupArg(argv) {
|
|
const backupArg = argv.find(item => item.startsWith('--backup='));
|
|
if (!backupArg) return '';
|
|
return backupArg.slice('--backup='.length).trim();
|
|
}
|
|
|
|
function getProcessTitle(version) {
|
|
return `egg-server-services.printer-${version}`;
|
|
}
|
|
|
|
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. 重启当前实例
|
|
const startLogPath = `/tmp/services.printer-${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();
|