services.printer/script/deploy-remote.cjs

441 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';
const fs = require('node:fs');
const path = require('node:path');
const {
ROOT,
buildArchive,
buildRemoteCleanupGuard,
ensureCommandAvailable,
getNowStamp,
isGitAvailable,
loadDeployConfig,
quoteForBash,
runCommand,
runCommandSafe,
runScp,
runSsh,
} = require('./deploy-lib.cjs');
/**
* 通过 SSH 读取远端 current.md 文件,获取当前活跃版本标识(v1 或 v2)
*/
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 resolveTargetDir(currentVersion, deployRoot) {
if (currentVersion === 'v1') return `${deployRoot}/v2`;
return `${deployRoot}/v1`;
}
function resolveTargetVersion(currentVersion) {
if (currentVersion === 'v1') return 'v2';
return 'v1';
}
function getTargetPort(targetVersion) {
if (targetVersion === 'v1') return 4051;
return 4052;
}
function getProcessTitle(version) {
return `egg-server-services.printer-${version}`;
}
function main() {
const envName = process.argv[2] || 'production';
const config = loadDeployConfig(envName);
ensureCommandAvailable('git', '请先安装 Git 并确保 git 在 PATH 中。');
ensureCommandAvailable('tar', '请先安装 tar,Windows 10/11 通常已内置 bsdtar。');
ensureCommandAvailable('ssh', '请先安装 OpenSSH Client 并确保 ssh 在 PATH 中。');
ensureCommandAvailable('scp', '请先安装 OpenSSH Client 并确保 scp 在 PATH 中。');
// 1. 部署前信息
console.log('========================================');
console.log('services.printer 蓝绿部署');
console.log(`环境: ${envName}`);
console.log(`目标: ${config.username}@${config.host}:${config.port}`);
console.log(`远端根目录: ${config.deployRoot}`);
console.log('========================================');
// 检查 Git 未提交更改
if (isGitAvailable()) {
const uncommitted = runCommandSafe('git', [ 'status', '--porcelain' ]);
if (uncommitted) {
console.warn('[WARN] 检测到未提交的更改:');
const changes = uncommitted.split(/\r?\n/).filter(Boolean);
for (const line of changes.slice(0, 10)) {
console.warn(` ${line}`);
}
if (changes.length > 10) {
console.warn(` ... 还有 ${changes.length - 10} 处更改`);
}
console.warn('[WARN] 未提交的更改不会被包含在发布包中!');
console.warn('[WARN] 建议先 git add && git commit 后再部署。');
}
}
// 2. 读取远端 current.md,确定目标目录
const currentVersion = readRemoteCurrentVersion(config, config.deployRoot);
const targetDir = resolveTargetDir(currentVersion, config.deployRoot);
console.log(`远端当前活跃版本: ${currentVersion},目标部署目录: ${targetDir}`);
// 3. 本地打包
console.log('[1/8] 正在本地打包...');
const stamp = getNowStamp();
const packageJson = JSON.parse(fs.readFileSync(path.join(ROOT, 'package.json'), 'utf8'));
const packageVersion = String(packageJson.version || '0.0.0');
let gitCommitShort = 'nogit';
if (isGitAvailable()) {
gitCommitShort = runCommandSafe('git', [ 'rev-parse', '--short', 'HEAD' ]) || 'nogit';
}
const releaseVersion = `v${packageVersion}-${stamp}-${gitCommitShort}`;
const { archivePath } = buildArchive(stamp, config);
console.log(`[1/8] 打包完成: ${archivePath}`);
const remoteArchive = `${config.incomingDir}/release-${stamp}.tar.gz`;
// 4. 远端创建目录结构
console.log('[2/8] 正在远端创建目录...');
const setupScript = [
'set -euo pipefail',
`mkdir -p ${quoteForBash(targetDir)} ${quoteForBash(config.incomingDir)} ${quoteForBash(config.backupDir)} ${quoteForBash(config.stateDir)}`,
].join('\n');
runSsh(config, setupScript);
console.log(`[2/8] 远端目录已就绪: ${targetDir}`);
// 5. 远端备份当前目标目录
console.log('[3/8] 正在备份远端目标目录...');
const backupScript = [
'set -euo pipefail',
`TARGET_DIR=${quoteForBash(targetDir)}`,
`BACKUP_DIR=${quoteForBash(config.backupDir)}`,
`STAMP=${quoteForBash(stamp)}`,
'if [ -f "$TARGET_DIR/package.json" ]; then',
' BACKUP_FILE="$BACKUP_DIR/backup-${STAMP}.tar.gz"',
' cd "$TARGET_DIR"',
' tar -czf "$BACKUP_FILE" . --exclude="./node_modules" --exclude="./.deploy" --exclude="./logs" --exclude="./run" --exclude="./tmp" 2>/dev/null || true',
' echo "已备份目标目录到: $BACKUP_FILE"',
'else',
' echo "目标目录为空,跳过备份"',
'fi',
].join('\n');
try {
const backupOutput = runSsh(config, backupScript, { stdio: 'pipe' });
console.log(String(backupOutput || '').trim());
} catch (err) {
console.warn(`[WARN] 备份失败(非致命): ${err.message}`);
}
// 6. SCP 上传
console.log('[4/8] 正在上传发布包...');
runScp(config, archivePath, remoteArchive);
console.log(`[4/8] 发布包已上传到远端: ${remoteArchive}`);
// 7. 解压、安装依赖
const cleanupGuard = buildRemoteCleanupGuard(
[ ...config.sharedDirs, 'node_modules' ],
config.preserveDirs
);
const remoteScript = [
'set -euo pipefail',
`TARGET_DIR=${quoteForBash(targetDir)}`,
`REMOTE_ARCHIVE=${quoteForBash(remoteArchive)}`,
`ACTIVE_DIR=${quoteForBash(`${config.deployRoot}/${currentVersion}`)}`,
// 从活跃版本复制 node_modules(蓝绿部署核心优化)
'if [ ! -d "$TARGET_DIR/node_modules" ] && [ -d "$ACTIVE_DIR/node_modules" ]; then',
' echo "正在从活跃版本 ($ACTIVE_DIR) 复制 node_modules ..."',
' cp -a "$ACTIVE_DIR/node_modules" "$TARGET_DIR/node_modules"',
' echo "node_modules 复制完成"',
'fi',
'cd "$TARGET_DIR"',
`find . -mindepth 1 -maxdepth 1 ${cleanupGuard} -exec rm -rf {} +`,
'tar -xzf "$REMOTE_ARCHIVE" -C "$TARGET_DIR"',
'rm -f "$REMOTE_ARCHIVE"',
// 保留 config 目录
'if [ ! -d "$TARGET_DIR/config" ]; then',
` ACTIVE_DIR=${quoteForBash(`${config.deployRoot}/${currentVersion}`)}`,
' if [ -d "$ACTIVE_DIR/config" ]; then',
' cp -a "$ACTIVE_DIR/config" "$TARGET_DIR/config"',
' echo "已从活跃版本 ($ACTIVE_DIR) 复制 config 目录"',
' else',
` FALLBACK_DIR=${quoteForBash(config.deployRoot)}`,
' if [ -d "$FALLBACK_DIR/config" ]; then',
' cp -a "$FALLBACK_DIR/config" "$TARGET_DIR/config"',
' echo "已从根目录 ($FALLBACK_DIR) 复制 config 目录"',
' else',
' echo "[WARN] 未找到 config 目录来源,目标目录将缺少 config 配置!"',
' fi',
' fi',
'fi',
// 清理 node_modules 后重新安装,避免残留状态导致 npm semver 冲突
'echo "正在清理旧 node_modules ..."',
'rm -rf "$TARGET_DIR/node_modules"',
'npm install --production',
].join('\n');
console.log('[5/8] 正在远端清理、解压、安装依赖...');
runSsh(config, remoteScript);
console.log(`[5/8] 远端目标目录已清理、解压并安装依赖: ${targetDir}`);
// 8. 目标版本信息
const targetVersion = resolveTargetVersion(currentVersion);
const targetPort = getTargetPort(targetVersion);
const targetTitle = getProcessTitle(targetVersion);
const currentTitle = getProcessTitle(currentVersion);
const startLogPath = `/tmp/services.printer-${targetVersion}-start.log`;
const currentMdPath = `${config.deployRoot}/current.md`;
const oldDir = `${config.deployRoot}/${currentVersion}`;
// 9. 停止目标目录可能残留的旧进程
const stopTargetScript = [
'set -euo pipefail',
`TARGET_DIR=${quoteForBash(targetDir)}`,
`TARGET_VERSION=${quoteForBash(targetVersion)}`,
`TARGET_TITLE=${quoteForBash(targetTitle)}`,
'TARGET_PIDS=$(ps -eo pid=,args= | awk -v root="$TARGET_DIR" \'index($0, root) && $2 ~ /node$/ { print $1 }\')',
'TITLE_PIDS=$(ps -eo pid=,args= | awk -v t="$TARGET_TITLE" \'index($0, t) { print $1 }\')',
'ALL_PIDS=$(echo "$TARGET_PIDS $TITLE_PIDS" | tr " " "\\n" | sort -u | grep -v "^$" | tr "\\n" " ")',
'if [ -z "$ALL_PIDS" ]; then',
' echo "未找到目标目录 ($TARGET_VERSION) 残留进程"',
'else',
' echo "正在停止目标目录 ($TARGET_VERSION) 残留进程: $ALL_PIDS"',
' kill $ALL_PIDS || true',
' sleep 2',
' REMAIN=$(ps -eo pid=,args= | awk -v root="$TARGET_DIR" \'index($0, root) && $2 ~ /node$/ { print $1 }\')',
' if [ -n "$REMAIN" ]; then',
' kill -9 $REMAIN || true',
' fi',
' echo "目标目录 ($TARGET_VERSION) 残留进程已停止"',
'fi',
].join('\n');
try {
const stopTargetOutput = runSsh(config, stopTargetScript, { stdio: 'pipe' });
console.log(String(stopTargetOutput || '').trim());
} catch (err) {
console.warn(`[WARN] 停止目标目录残留进程失败: ${err.message}`);
}
// 10. 检测并停止旧版根目录遗留进程(端口 4050 等)
const stopLegacyScript = [
'set -euo pipefail',
`ROOT_DIR=${quoteForBash(config.deployRoot)}`,
'LEGACY_PIDS=$(ps -eo pid=,args= | awk -v root="$ROOT_DIR" \'index($0, "baseDir") && index($0, root) && !index($0, root"/v1") && !index($0, root"/v2") { print $1 }\')',
'if [ -z "$LEGACY_PIDS" ]; then',
' echo "未发现旧版根目录遗留进程"',
'else',
' echo "发现旧版根目录遗留进程: $LEGACY_PIDS,正在停止..."',
' kill $LEGACY_PIDS || true',
' sleep 3',
' REMAIN=$(ps -eo pid=,args= | awk -v root="$ROOT_DIR" \'index($0, "baseDir") && index($0, root) && !index($0, root"/v1") && !index($0, root"/v2") { print $1 }\')',
' if [ -n "$REMAIN" ]; then',
' kill -9 $REMAIN || true',
' fi',
' echo "旧版根目录遗留进程已停止"',
'fi',
].join('\n');
try {
const legacyOutput = runSsh(config, stopLegacyScript, { stdio: 'pipe' });
console.log(String(legacyOutput || '').trim());
} catch (err) {
console.warn(`[WARN] 旧版进程清理: ${err.message}`);
}
// 11. 启动新实例
console.log('[6/8] 正在启动新实例...');
const startScript = [
'set -euo pipefail',
`cd ${quoteForBash(targetDir)}`,
`nohup bash -lc 'npx egg-scripts start --daemon --title=${targetTitle} --sticky --port=${targetPort} --ignore-stderr' > ${quoteForBash(startLogPath)} 2>&1 &`,
`echo "已在 ${targetDir} 启动新实例 ${targetVersion} (title=${targetTitle}, 端口 ${targetPort}),启动日志: ${startLogPath}"`,
].join('\n');
const startOutput = runSsh(config, startScript, { stdio: 'pipe' });
console.log(String(startOutput || '').trim());
// 12. 健康检查
console.log('[7/8] 正在进行健康检查(最多等待 60 秒)...');
const healthCheckScript = [
'set -euo pipefail',
`TARGET_PORT=${targetPort}`,
'HEALTH_OK=false',
'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 "新实例 (${targetVersion}) 健康检查通过 (端口 $TARGET_PORT, 第 $attempt 次)"`,
' HEALTH_OK=true',
' break',
' fi',
' sleep 2',
'done',
'if [ "$HEALTH_OK" != "true" ]; then',
` echo "FATAL: 新实例 (${targetVersion}) 健康检查超时 (端口 $TARGET_PORT)" >&2`,
' exit 1',
'fi',
].join('\n');
let healthPassed = false;
try {
const healthOutput = runSsh(config, healthCheckScript, { stdio: 'pipe' });
console.log(String(healthOutput || '').trim());
healthPassed = true;
} catch (err) {
console.error(`[FATAL] 新实例健康检查失败: ${err.message}`);
console.error(`[FATAL] 新实例 (${targetVersion}) 未能正常启动,保留当前活跃版本 (${currentVersion}) 不变。`);
console.error(`[FATAL] 请检查启动日志: ssh ${config.username}@${config.host} "cat ${startLogPath}"`);
console.error('[FATAL] 部署已中止,当前服务不受影响。');
// 清理失败的新实例
const cleanupFailedScript = [
'set -euo pipefail',
`TARGET_DIR=${quoteForBash(targetDir)}`,
'FAILED_PIDS=$(ps -eo pid=,args= | awk -v root="$TARGET_DIR" \'index($0, root) && $2 ~ /node$/ { print $1 }\')',
'if [ -n "$FAILED_PIDS" ]; then kill -9 $FAILED_PIDS || true; fi',
'echo "已清理失败的新实例进程"',
].join('\n');
try {
runSsh(config, cleanupFailedScript, { stdio: 'pipe' });
} catch (_) { /* ignore */ }
process.exit(1);
}
// 13. 切换 current.md
console.log('[8/8] 正在切换流量...');
const switchCurrentMdScript = [
'set -euo pipefail',
`printf '%s\\n' ${quoteForBash(targetVersion)} > ${quoteForBash(currentMdPath)}`,
`echo "current.md 已切换 -> ${targetVersion}"`,
].join('\n');
const switchOutput2 = runSsh(config, switchCurrentMdScript, { stdio: 'pipe' });
console.log(String(switchOutput2 || '').trim());
// 14. 切换 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' ${targetPort} > ${quoteForBash(nginxUpstreamPath)}`,
'nginx -t && nginx -s reload',
`echo "Nginx upstream 已切换至 127.0.0.1:${targetPort}"`,
].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] 新实例已在端口 ${targetPort} 运行,但 Nginx 未自动切换。`);
console.warn(`[WARN] 请手动更新 ${nginxUpstreamPath} 并执行 nginx -s reload`);
}
// 15. 停止旧实例
const stopOldScript = [
'set -euo pipefail',
`OLD_DIR=${quoteForBash(oldDir)}`,
`OLD_VERSION=${quoteForBash(currentVersion)}`,
`OLD_TITLE=${quoteForBash(currentTitle)}`,
'OLD_PIDS=$(ps -eo pid=,args= | awk -v root="$OLD_DIR" \'index($0, root) && $2 ~ /node$/ { print $1 }\')',
'if [ -z "$OLD_PIDS" ]; then',
' echo "未找到旧实例 ($OLD_VERSION) 进程,跳过停止步骤"',
'else',
' echo "正在停止旧实例 ($OLD_VERSION): $OLD_PIDS"',
' kill $OLD_PIDS || true',
' sleep 3',
' OLD_PIDS_REMAIN=$(ps -eo pid=,args= | awk -v root="$OLD_DIR" \'index($0, root) && $2 ~ /node$/ { print $1 }\')',
' if [ -n "$OLD_PIDS_REMAIN" ]; then',
' echo "旧实例 ($OLD_VERSION) 仍有残留进程,强制停止: $OLD_PIDS_REMAIN"',
' kill -9 $OLD_PIDS_REMAIN || true',
' fi',
' echo "旧实例 ($OLD_VERSION) 已停止"',
'fi',
].join('\n');
try {
const stopOutput = runSsh(config, stopOldScript, { stdio: 'pipe' });
console.log(String(stopOutput || '').trim());
} catch (err) {
console.warn(`[WARN] 停止旧实例失败: ${err.message}`);
console.warn(`[WARN] 旧实例 (${currentVersion}) 可能仍在运行,请人工确认并停止`);
}
// 16. 记录远端 release 状态
const remoteStateFile = `${config.stateDir}/current-release.json`;
const remoteHistoryFile = `${config.stateDir}/release-history.jsonl`;
const releaseEntry = {
releaseVersion,
packageVersion,
gitCommitShort,
deployRoot: config.deployRoot,
targetVersion,
targetPort,
deployedAt: new Date().toISOString(),
};
const releaseJson = JSON.stringify(releaseEntry);
const recordReleaseScript = [
'set -euo pipefail',
`STATE_FILE=${quoteForBash(remoteStateFile)}`,
`HISTORY_FILE=${quoteForBash(remoteHistoryFile)}`,
`ENTRY=${quoteForBash(releaseJson)}`,
'printf "%s\\n" "$ENTRY" > "$STATE_FILE"',
'printf "%s\\n" "$ENTRY" >> "$HISTORY_FILE"',
'echo "远端 release 状态已记录"',
].join('\n');
try {
const recordOutput = runSsh(config, recordReleaseScript, { stdio: 'pipe' });
console.log(String(recordOutput || '').trim());
} catch (err) {
console.warn(`[WARN] 记录远端 release 状态失败: ${err.message}`);
}
// 17. 清理旧备份
const cleanupBackupsScript = [
'set -euo pipefail',
`BACKUP_DIR=${quoteForBash(config.backupDir)}`,
`KEEP=${Number(config.keepBackups)}`,
'cd "$BACKUP_DIR"',
'ls -1t backup-*.tar.gz 2>/dev/null | tail -n +$((KEEP + 1)) | while read -r f; do rm -f "$f"; echo "已清理旧备份: $f"; done',
'echo "备份清理完成(保留最近 ${KEEP} 个)"',
].join('\n');
try {
const cleanupOutput = runSsh(config, cleanupBackupsScript, { stdio: 'pipe' });
console.log(String(cleanupOutput || '').trim());
} catch (err) {
console.warn(`[WARN] 清理旧备份失败: ${err.message}`);
}
// 18. 完成
console.log('========================================');
console.log(`发布完成: ${envName} -> ${config.username}@${config.host}:${targetDir}`);
console.log(`线上版本号: ${releaseVersion}`);
console.log(`当前活跃版本已切换为: ${targetVersion} (端口 ${targetPort})`);
console.log('========================================');
}
main();