WMS_MAIN/script/deploy-remote.cjs
liufumingren 34273c166b 1
2026-07-02 22:08:47 +08:00

244 lines
9.2 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,
loadDeployConfig,
quoteForBash,
runCommand,
runScp,
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}。请确保远端已存在 /www/wwwroot/qimen/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;
}
/**
* 根据当前活跃版本确定目标部署目录(另一个实例目录)
*
* @param {string} currentVersion - 当前活跃版本,'v1' 或 'v2'
* @param {string} deployRoot - 远端部署根目录,如 /www/wwwroot/qimen
* @return {string} 目标部署目录,如 /www/wwwroot/qimen/v2
*/
function resolveTargetDir(currentVersion, deployRoot) {
if (currentVersion === 'v1') {
return `${deployRoot}/v2`;
}
return `${deployRoot}/v1`;
}
/**
* 根据当前活跃版本推导目标版本标识(v1 ↔ v2 互换)
*
* @param {string} currentVersion - 当前活跃版本,'v1' 或 'v2'
* @return {string} 目标版本标识,'v1' 或 'v2'
*/
function resolveTargetVersion(currentVersion) {
if (currentVersion === 'v1') {
return 'v2';
}
return 'v1';
}
/**
* 根据版本标识返回对应监听端口(v1 → 6061,v2 → 6062)
*
* @param {string} targetVersion - 目标版本标识,'v1' 或 'v2'
* @return {number} 对应端口号
*/
function getTargetPort(targetVersion) {
if (targetVersion === 'v1') {
return 6061;
}
return 6062;
}
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. 读取远端 current.md,确定目标目录
const currentVersion = readRemoteCurrentVersion(config, config.deployRoot);
const targetDir = resolveTargetDir(currentVersion, config.deployRoot);
console.log(`远端当前活跃版本: ${currentVersion},目标部署目录: ${targetDir}`);
// 2. 本地打包(不变)
const stamp = getNowStamp();
const packageJson = JSON.parse(fs.readFileSync(path.join(ROOT, 'package.json'), 'utf8'));
const packageVersion = String(packageJson.version || '0.0.0');
const gitCommitShort = runCommand('git', [ 'rev-parse', '--short', 'HEAD' ]);
const releaseVersion = `v${packageVersion}-${stamp}-${gitCommitShort}`;
const { archivePath } = buildArchive(stamp, config);
const remoteArchive = `${config.incomingDir}/release-${stamp}.tar.gz`;
// 3. 远端创建目录结构(目标目录 + incoming 目录)
const setupScript = [
'set -euo pipefail',
`mkdir -p ${quoteForBash(targetDir)} ${quoteForBash(config.incomingDir)}`,
].join('\n');
runSsh(config, setupScript);
console.log(`远端目录已就绪: ${targetDir}`);
// 4. SCP 上传 tar.gz 到远端 incoming 目录
runScp(config, archivePath, remoteArchive);
console.log(`发布包已上传到远端: ${remoteArchive}`);
// 5. 在目标目录清理旧代码、解压、安装依赖
const cleanupGuard = buildRemoteCleanupGuard(config.sharedDirs, config.preserveDirs);
const remoteScript = [
'set -euo pipefail',
`TARGET_DIR=${quoteForBash(targetDir)}`,
`REMOTE_ARCHIVE=${quoteForBash(remoteArchive)}`,
// 进入目标目录,清理旧代码文件(保留 node_modules、logs、run、temp、.deploy 等运行时/状态目录)
'cd "$TARGET_DIR"',
`find . -mindepth 1 -maxdepth 1 ${cleanupGuard} -exec rm -rf {} +`,
// 解压发布包
'tar -xzf "$REMOTE_ARCHIVE" -C "$TARGET_DIR"',
'rm -f "$REMOTE_ARCHIVE"',
// 在目标目录安装生产依赖
'npm install --production',
].join('\n');
runSsh(config, remoteScript);
console.log(`远端目标目录已清理、解压并安装依赖: ${targetDir}`);
// 推导目标版本标识与启动日志路径
const targetVersion = resolveTargetVersion(currentVersion);
const targetPort = getTargetPort(targetVersion);
const startLogPath = `/tmp/wms-${targetVersion}-start.log`;
const currentMdPath = `${config.deployRoot}/current.md`;
// 6. 更新远端 current.md 并启动新实例
const switchAndStartScript = [
'set -euo pipefail',
// 更新 current.md 指向新版本
`printf '%s\\n' ${quoteForBash(targetVersion)} > ${quoteForBash(currentMdPath)}`,
// 在目标目录后台启动 Egg.js 进程
`cd ${quoteForBash(targetDir)}`,
`nohup bash -lc 'npm start' > ${quoteForBash(startLogPath)} 2>&1 &`,
`echo "已更新 current.md -> ${targetVersion},已在 ${targetDir} 启动新实例,启动日志: ${startLogPath}"`,
].join('\n');
const switchOutput = runSsh(config, switchAndStartScript, { stdio: 'pipe' });
console.log(String(switchOutput || '').trim());
// 6.5. 健康检查新实例(curl 循环等待,最多 60 秒)
const oldDir = `${config.deployRoot}/${currentVersion}`;
const healthCheckScript = [
'set -euo pipefail',
`TARGET_PORT=${targetPort}`,
'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)"`,
' break',
' fi',
' if [ "$attempt" -eq 30 ]; then',
` echo "新实例 (${targetVersion}) 健康检查超时 (端口 $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}`);
console.warn(`[WARN] 新实例 (${targetVersion}) 可能未完全就绪,请人工确认 127.0.0.1:${targetPort} 状态`);
}
// 6.55. 切换 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] Nginx reload 可能未成功,请人工确认 ${nginxUpstreamPath} 内容并执行 nginx -s reload`);
}
// 6.6. 停止旧实例(kill + 兜底 kill -9)
const stopOldScript = [
'set -euo pipefail',
`OLD_DIR=${quoteForBash(oldDir)}`,
`OLD_VERSION=${quoteForBash(currentVersion)}`,
'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}) 可能仍在运行,请人工确认并停止`);
}
// 7. 打印完成信息
console.log(`发布完成: ${envName} -> ${config.username}@${config.host}:${targetDir}`);
console.log(`线上版本号: ${releaseVersion}`);
console.log(`当前活跃版本已切换为: ${targetVersion}`);
}
main();