'use strict'; const path = require('node:path'); const { URL } = require('node:url'); const { buildRemoteCleanupGuard, buildScopedEggStopScript, ensureCommandAvailable, getNowStamp, loadDeployConfig, quoteForBash, runSsh, serializeCommands, } = require('./deploy-lib.cjs'); function splitPostDeployCommands(commands) { const normalized = Array.isArray(commands) ? commands.filter(Boolean).map(item => String(item).trim()).filter(Boolean) : []; const stopCommandPattern = /^(?:npm(?:\.cmd)?\s+(?:run\s+)?stop|egg-scripts\s+stop)(?:\s|$)/i; const startCommandIndex = normalized.findIndex(item => /^npm\s+start(?:\s|$)/i.test(item)); const stopCommandIndexes = normalized .map((item, index) => (stopCommandPattern.test(item) ? index : -1)) .filter(index => index >= 0); if (startCommandIndex === -1) { return { preStartCommands: normalized.filter((_, index) => !stopCommandIndexes.includes(index)), startCommand: '', }; } return { preStartCommands: normalized.filter((_, index) => index !== startCommandIndex && !stopCommandIndexes.includes(index)), startCommand: normalized[startCommandIndex], }; } function buildHealthCheckScript(healthCheckUrl) { if (!healthCheckUrl) { return ''; } let fallbackUrl = ''; try { const parsed = new URL(healthCheckUrl); const hostname = String(parsed.hostname || '').toLowerCase(); const isLocalHost = hostname === '127.0.0.1' || hostname === 'localhost'; if (!isLocalHost) { const port = parsed.port || '6060'; fallbackUrl = `http://127.0.0.1:${port}${parsed.pathname || '/'}${parsed.search || ''}`; } } catch (error) { fallbackUrl = 'http://127.0.0.1:6060/'; } return [ `HEALTHCHECK_URL=${quoteForBash(healthCheckUrl)}`, ...(fallbackUrl ? [ `HEALTHCHECK_FALLBACK_URL=${quoteForBash(fallbackUrl)}` ] : []), 'HEALTHCHECK_CURL_OPTS="--connect-timeout 2 --max-time 4"', 'for attempt in $(seq 1 20); do', ' if curl -fsS $HEALTHCHECK_CURL_OPTS "$HEALTHCHECK_URL" >/dev/null; then', ' break', ' fi', ...(fallbackUrl ? [ ' if curl -fsS $HEALTHCHECK_CURL_OPTS "$HEALTHCHECK_FALLBACK_URL" >/dev/null; then', ' break', ' fi' ] : []), ' if [ "$attempt" -eq 20 ]; then', ...(fallbackUrl ? [ ' echo "健康检查失败: $HEALTHCHECK_URL (fallback: $HEALTHCHECK_FALLBACK_URL)" >&2' ] : [ ' echo "健康检查失败: $HEALTHCHECK_URL" >&2' ]), ' exit 1', ' fi', ' sleep 1', 'done', ].join('\n'); } function parseBackupArg(argv) { const backupArg = argv.find(item => item.startsWith('--backup=')); if (!backupArg) { return ''; } return backupArg.slice('--backup='.length).trim(); } 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 中。'); const stamp = getNowStamp(); const cleanupGuard = buildRemoteCleanupGuard(config.sharedDirs, config.preserveDirs); const postDeploy = splitPostDeployCommands(config.postDeployCommands); const postDeployCommands = serializeCommands(postDeploy.preStartCommands); const startCommand = postDeploy.startCommand; const scopedStopCommand = buildScopedEggStopScript(config.deployRoot); const detachedStartCommand = startCommand ? `nohup bash -lc ${quoteForBash(startCommand)} >/tmp/wms-rollback-start.log 2>&1 &` : ''; const latestBackupFile = path.posix.join(config.stateDir, 'latest-backup.txt'); const healthCheckCommand = buildHealthCheckScript(config.healthCheckUrl); const remoteScript = [ 'set -euo pipefail', `DEPLOY_ROOT=${quoteForBash(config.deployRoot)}`, `BACKUP_DIR=${quoteForBash(config.backupDir)}`, `LATEST_BACKUP_FILE=${quoteForBash(latestBackupFile)}`, `REQUESTED_BACKUP=${quoteForBash(backupName)}`, `CURRENT_SAFETY_BACKUP=${quoteForBash(`rollback-safety-${stamp}.tar.gz`)}`, 'if [ -n "$REQUESTED_BACKUP" ]; then', ' TARGET_BACKUP="$REQUESTED_BACKUP"', 'elif [ -f "$LATEST_BACKUP_FILE" ]; then', ' TARGET_BACKUP="$(cat "$LATEST_BACKUP_FILE")"', 'else', ' echo "未找到最近一次发布备份,请通过 --backup=backup-时间戳.tar.gz 指定回退包。" >&2', ' exit 1', 'fi', 'if [ ! -f "$BACKUP_DIR/$TARGET_BACKUP" ]; then', ' echo "回退包不存在: $BACKUP_DIR/$TARGET_BACKUP" >&2', ' exit 1', 'fi', 'cd "$DEPLOY_ROOT"', 'tar --exclude=.deploy -czf "$BACKUP_DIR/$CURRENT_SAFETY_BACKUP" .', `find . -mindepth 1 -maxdepth 1 ${cleanupGuard} -exec rm -rf {} +`, 'tar -xzf "$BACKUP_DIR/$TARGET_BACKUP" -C "$DEPLOY_ROOT"', postDeployCommands, detachedStartCommand, healthCheckCommand, ].filter(Boolean).join('\n'); try { runSsh(config, scopedStopCommand, { stdio: 'inherit' }); } catch (error) { console.warn(`定点停进程失败,继续回退流程: ${error.message}`); } runSsh(config, remoteScript); console.log(`回退完成: ${envName} -> ${config.username}@${config.host}:${config.deployRoot}`); } main();