chore(deploy): 运维命令收敛为 install/uninstall,移除失效的 deploy:gateway-probe
- watchdog 部署工具只保留 install / uninstall:uninstall 先备份到
/tmp/qimen-watchdog-uninstall-<时间戳>/(cp -a 保留权限/时间),再**注销调度**
—— 删除 /etc/cron.d/qimen-watchdog 并清理 root crontab 中残留的 qimen-watchdog 行
(历史手工安装可能留过,双跑会并发 kill/start 同一实例),随后删除服务器副本
<部署根>/script/qimen-watchdog.sh 及其 .prev-* / .legacy-* 与历史根目录副本;
不碰日志、锁文件与接口服务进程;支持 --dry-run 只打印计划。
原 precheck 的只读环境快照改为 install 开头自动打印;status / dry-run / run
三个命令删除(需要时直接 ssh 执行 <部署根>/script/qimen-watchdog.sh --dry-run)。
- 移除失效的 deploy:gateway-probe:npm 脚本未传必需的 method 位置参数,而
gatewayProbe() 在缺参时直接抛错,命令必然 exit 1(CLI 契约与 npm 接线不匹配,
该命令从未能成功)。删除 npm 命令与 script/deploy-ops.cjs 中的 gatewayProbe 实现;
需要网关真实探活时直连活跃端口(current.md:v1→6061 / v2→6062)。
- 两份发布 agent 文档中的 "npm run deploy:gateway-probe -- releaseProbe.ping {}"
已删除 —— 其中的 releaseProbe.ping 这个 method 在应用内并不存在(双重失效),
改为「直连活跃端口」的说明;README 同步运维命令清单与 watchdog 卸载说明。
- 顺手修掉 script/deploy-ops.cjs 两处历史 lint 问题(模板字符串改单引号、
文件末尾补换行),该文件 lint 现已干净。
This commit is contained in:
parent
0918f2d572
commit
1fbc24c904
@ -90,8 +90,9 @@ npm run deploy:verify
|
||||
# 按文件名清理远端失败备份
|
||||
npm run deploy:cleanup-backups -- backup-20260324202526.tar.gz backup-20260324204750.tar.gz
|
||||
|
||||
# 调用 internal gateway 做 method 连通探针
|
||||
npm run deploy:gateway-probe -- releaseProbe.ping "{}"
|
||||
# internal gateway 真实探活(无 npm 命令;需要时直连活跃端口)
|
||||
# 活跃端口读 current.md:v1 → 6061 / v2 → 6062
|
||||
# ssh <host> 'curl -sS -X POST "http://127.0.0.1:<port>/internal/v1/gateway?method=<method>&v=1×tamp=$(date +%s)" -H "Content-Type: text/plain" --data "{}"'
|
||||
|
||||
# 手动记录一次本地包版本快照
|
||||
npm run version:record
|
||||
|
||||
5
.github/agents/发布.agent.md
vendored
5
.github/agents/发布.agent.md
vendored
@ -127,8 +127,9 @@ npm run deploy:verify
|
||||
# 按文件名清理远端失败备份
|
||||
npm run deploy:cleanup-backups -- backup-20260324202526.tar.gz backup-20260324204750.tar.gz
|
||||
|
||||
# 调用 internal gateway 做 method 连通探针
|
||||
npm run deploy:gateway-probe -- releaseProbe.ping "{}"
|
||||
# internal gateway 真实探活(无 npm 命令;需要时直连活跃端口)
|
||||
# 活跃端口读 current.md:v1 → 6061 / v2 → 6062
|
||||
# ssh <host> 'curl -sS -X POST "http://127.0.0.1:<port>/internal/v1/gateway?method=<method>&v=1×tamp=$(date +%s)" -H "Content-Type: text/plain" --data "{}"'
|
||||
|
||||
# 手动记录一次本地包版本快照
|
||||
npm run version:record
|
||||
|
||||
@ -177,10 +177,10 @@ npm run doc:api:update -- --spec=temp/api-doc-update.json --dry-run
|
||||
|
||||
```bash
|
||||
npm run deploy:precheck / deploy:authcheck / deploy:inspect / deploy:smoke / deploy:verify
|
||||
npm run deploy:version / deploy:version:history / deploy:cleanup-backups / deploy:gateway-probe
|
||||
npm run deploy:version / deploy:version:history / deploy:cleanup-backups
|
||||
npm run deploy # 发布(= deploy:prod);npm run rollback # 回退
|
||||
npm run deploy:cert-sync:install / npm run deploy:cert-sync:uninstall
|
||||
npm run deploy:watchdog:precheck | :install | :status | :dry-run | :run
|
||||
npm run deploy:watchdog:install / npm run deploy:watchdog:uninstall
|
||||
```
|
||||
|
||||
- **部署配置**:`config/deploy.config.local.cjs`(**本地文件、已被 `.gitignore` 忽略**;模板 `config/deploy.config.example.cjs`)。键:`host / port / username / privateKeyPath / deployRoot / sharedDirs / preserveDirs / keepBackups / preDeployCommands / postDeployCommands / healthCheckUrl / deployIncludePaths / deployExcludePaths / sshOptions`;缺省值在 `script/deploy-lib.cjs`。查看归一化后的生效配置:
|
||||
@ -190,6 +190,7 @@ npm run deploy:watchdog:precheck | :install | :status | :dry-run | :run
|
||||
- **证书同步运行时配置**:`script/warehouse-cert-sync.config.prod.json`(生产)/ `.dev.json`(开发)。生产那份是**服务器自管**(`deploy:cert-sync:install` 仅首次放置,之后永不覆盖)——改生产运行参数请在**服务器上**直接改它,改本地仓库无效。
|
||||
- **安装位置**:`deploy:cert-sync:install` 与 `deploy:watchdog:install` 都装到 `<deployRoot>/script/`;覆盖前会留 `.prev-<时间戳>` 备份,历史根目录副本会被一次性挪成 `<名>.legacy-<时间戳>`。
|
||||
- **卸载**(`deploy:cert-sync:uninstall`):先备份再删除——备份到服务器 `/tmp/wms-cert-sync-uninstall-<时间戳>/`(`cp -a` 保留权限/时间),删除包装脚本、主脚本、双环境配置、`database/config.js`、历史位置与 `.prev-*`/`.legacy-*` 备份、crontab 中 `warehouse-cert-sync` 行;支持 `--dry-run` 只打印计划。**不删**证书与生成的 server 块(nginx 仍在 include,删了会立断 443,由运维自行决定)、不删 `/var/log/warehouse-cert-sync.log`(默认保留作排查线索)、不碰任何 watchdog 相关文件/任务。
|
||||
- **卸载(watchdog)**(`deploy:watchdog:uninstall [--dry-run]`):备份到 `/tmp/qimen-watchdog-uninstall-<时间戳>/` 后**注销调度**——删除 `/etc/cron.d/qimen-watchdog`,并清理 root crontab 中残留的 `qimen-watchdog` 行(历史手工安装可能留过,双跑会并发 kill/start 同一实例);再删除服务器副本 `<deployRoot>/script/qimen-watchdog.sh`(含 `.prev-*` / `.legacy-*` 与历史根目录副本)。**不删** `/www/wwwlogs/wms/qimen-watchdog.log`(留作排查线索)、锁文件与接口服务进程;`deploy:watchdog:install` 会先只读打印一份目标机环境快照。
|
||||
- **运行期手动排查**:仍可直接执行服务器上的 `<deployRoot>/script/warehouse-cert-sync.sh --dry-run`(主脚本 CLI 不变:`--cleanup-only --dry-run` / `--cleanup-only` / `--env production`)。
|
||||
|
||||
## 功能模块
|
||||
|
||||
@ -61,13 +61,9 @@
|
||||
"deploy:cleanup-backups": "node ./script/deploy-ops.cjs production cleanup-backups",
|
||||
"deploy:cert-sync:install": "node ./script/deploy-cert-sync.cjs production install",
|
||||
"deploy:cert-sync:uninstall": "node ./script/deploy-cert-sync.cjs production uninstall",
|
||||
"deploy:watchdog:precheck": "node ./script/deploy-watchdog.cjs production precheck",
|
||||
"deploy:watchdog:install": "node ./script/deploy-watchdog.cjs production install",
|
||||
"deploy:watchdog:status": "node ./script/deploy-watchdog.cjs production status",
|
||||
"deploy:watchdog:dry-run": "node ./script/deploy-watchdog.cjs production dry-run",
|
||||
"deploy:watchdog:run": "node ./script/deploy-watchdog.cjs production run",
|
||||
"deploy:watchdog:uninstall": "node ./script/deploy-watchdog.cjs production uninstall",
|
||||
|
||||
"deploy:gateway-probe": "node ./script/deploy-ops.cjs production gateway-probe",
|
||||
"ops:check-root-logs": "node ./script/check-root-logs.cjs",
|
||||
"ops:clean-root-logs": "node ./script/check-root-logs.cjs production --clean",
|
||||
"ops:clean-root-logs:apply": "node ./script/check-root-logs.cjs production --clean --apply",
|
||||
|
||||
@ -2,7 +2,7 @@
|
||||
|
||||
const { loadDeployConfig, quoteForBash, runSsh } = require('./deploy-lib.cjs');
|
||||
|
||||
const COMMANDS = new Set([ 'inspect', 'smoke', 'verify', 'cleanup-backups', 'gateway-probe' ]);
|
||||
const COMMANDS = new Set([ 'inspect', 'smoke', 'verify', 'cleanup-backups' ]);
|
||||
|
||||
/**
|
||||
* 解析命令行参数,返回环境名、命令及额外参数
|
||||
@ -19,7 +19,7 @@ function parseArgs(argv) {
|
||||
|
||||
const tokens = [ ...argv ];
|
||||
if (tokens.length === 0) {
|
||||
throw new Error('缺少命令: inspect | smoke | verify | cleanup-backups | gateway-probe');
|
||||
throw new Error('缺少命令: inspect | smoke | verify | cleanup-backups');
|
||||
}
|
||||
|
||||
const first = tokens[0];
|
||||
@ -29,7 +29,7 @@ function parseArgs(argv) {
|
||||
}
|
||||
|
||||
if (tokens.length === 0) {
|
||||
throw new Error('缺少命令: inspect | smoke | verify | cleanup-backups | gateway-probe');
|
||||
throw new Error('缺少命令: inspect | smoke | verify | cleanup-backups');
|
||||
}
|
||||
|
||||
options.command = tokens[0];
|
||||
@ -148,33 +148,6 @@ function cleanupBackups(config, names) {
|
||||
return runSsh(config, remoteScript, { stdio: 'pipe' }).trim();
|
||||
}
|
||||
|
||||
/**
|
||||
* 对当前活跃端口的内部网关接口执行探活调用
|
||||
*
|
||||
* @param {object} config - 部署配置对象
|
||||
* @param {string} methodName - method 名称
|
||||
* @param {string} payloadText - 请求体 JSON 字符串
|
||||
* @return {string} 网关接口响应内容
|
||||
*/
|
||||
function gatewayProbe(config, methodName, payloadText) {
|
||||
if (!methodName) {
|
||||
throw new Error('gateway-probe 需要 method 名称');
|
||||
}
|
||||
|
||||
const { port } = getActivePortInfo(config);
|
||||
const payload = payloadText && payloadText.trim() ? payloadText : '{}';
|
||||
const remoteScript = [
|
||||
'set -euo pipefail',
|
||||
`METHOD_NAME=${quoteForBash(methodName)}`,
|
||||
`PAYLOAD=${quoteForBash(payload)}`,
|
||||
`PORT=${port}`,
|
||||
'timestamp=$(date +%s)',
|
||||
'curl -sS -X POST "http://127.0.0.1:$PORT/internal/v1/gateway?method=$METHOD_NAME&v=1×tamp=$timestamp" -H "Content-Type: text/plain" --data "$PAYLOAD"',
|
||||
].join('\n');
|
||||
|
||||
return runSsh(config, remoteScript, { stdio: 'pipe' }).trim();
|
||||
}
|
||||
|
||||
/**
|
||||
* 显示远端 current.md 内容及当前活跃端口信息
|
||||
*
|
||||
@ -207,7 +180,7 @@ function main() {
|
||||
|
||||
if (options.command === 'smoke') {
|
||||
showActiveInfo(config);
|
||||
console.log(`[SMOKE]`);
|
||||
console.log('[SMOKE]');
|
||||
console.log(smokeRoutes(config));
|
||||
return;
|
||||
}
|
||||
@ -226,16 +199,7 @@ function main() {
|
||||
return;
|
||||
}
|
||||
|
||||
if (options.command === 'gateway-probe') {
|
||||
const methodName = options.args[0];
|
||||
const payloadText = options.args[1] || '{}';
|
||||
showActiveInfo(config);
|
||||
console.log(`[GATEWAY_PROBE] method=${methodName}`);
|
||||
console.log(gatewayProbe(config, methodName, payloadText));
|
||||
return;
|
||||
}
|
||||
|
||||
throw new Error(`不支持的命令: ${options.command}`);
|
||||
}
|
||||
|
||||
main();
|
||||
main();
|
||||
|
||||
@ -23,12 +23,19 @@
|
||||
* 远端 --dry-run 冒烟(只探活、绝不启动/杀进程);
|
||||
* 5. 不碰服务:install 不重启 qimen、不 reload nginx、不动任何数据库。
|
||||
*
|
||||
* 用法:
|
||||
* node script/deploy-watchdog.cjs production precheck
|
||||
* 用法(npm 命令仅 install / uninstall 两条):
|
||||
* node script/deploy-watchdog.cjs production install
|
||||
* node script/deploy-watchdog.cjs production status
|
||||
* node script/deploy-watchdog.cjs production dry-run # 远端执行 --dry-run(只探活并报告)
|
||||
* node script/deploy-watchdog.cjs production run # 远端真实保活(探活失败才会拉起服务)
|
||||
* node script/deploy-watchdog.cjs production uninstall [--dry-run]
|
||||
*
|
||||
* uninstall 做什么(先备份再删除):
|
||||
* 1. 备份到 /tmp/qimen-watchdog-uninstall-<时间戳>/(cp -a 保留权限/时间);
|
||||
* 2. **注销调度**:删除 /etc/cron.d/qimen-watchdog,并清理 root crontab 中残留的
|
||||
* qimen-watchdog 行(历史手工安装可能留过,双跑会并发 kill/start 同一实例);
|
||||
* 3. 删除服务器副本 <部署根>/script/qimen-watchdog.sh 及其 .prev-* / .legacy-* 备份,
|
||||
* 以及历史位置 <部署根>/qimen-watchdog.sh;
|
||||
* 4. **不碰**:日志 /www/wwwlogs/wms/qimen-watchdog.log、锁 /var/lock/qimen-watchdog.lock、
|
||||
* 接口服务进程、nginx 与数据库(日志保留作排查线索)。
|
||||
* 支持 --dry-run:只打印计划,不备份、不删除、不改 crontab。
|
||||
*
|
||||
* 退出码:0 成功;非 0 失败(参数非法 / 本地文件缺失 / sha 不一致 / 远端命令失败)。
|
||||
*/
|
||||
@ -45,8 +52,7 @@ const {
|
||||
runSsh,
|
||||
} = require('./deploy-lib.cjs');
|
||||
|
||||
const COMMANDS = new Set([ 'precheck', 'install', 'status', 'dry-run', 'run' ]);
|
||||
const COMMAND_HINT = 'precheck | install | status | dry-run | run';
|
||||
const COMMANDS = new Set([ 'install', 'uninstall' ]);
|
||||
|
||||
/** 仓库源文件(脚本本体)。 */
|
||||
const LOCAL_WATCHDOG = path.join(ROOT, 'script', 'qimen-watchdog.sh');
|
||||
@ -63,26 +69,43 @@ const LOCK_PATH = '/var/lock/qimen-watchdog.lock';
|
||||
const CRON_SCHEDULE = '*/5 * * * *';
|
||||
const CRON_USER = 'root';
|
||||
|
||||
/**
|
||||
* 打印本工具用法(仅 install / uninstall 两条 npm 命令)。
|
||||
*/
|
||||
function printUsage() {
|
||||
console.error([
|
||||
'usage: node script/deploy-watchdog.cjs [env] <command> [--dry-run]',
|
||||
' env: production | development(默认 production)',
|
||||
' command: install 上传看门狗脚本 + 写 /etc/cron.d/qimen-watchdog(含语法/哈希/冒烟校验)',
|
||||
' uninstall 注销 cron.d 与 root crontab 行,备份后删除服务器副本(支持 --dry-run)',
|
||||
'运行期手动排查:直接执行服务器上的 <deployRoot>/script/qimen-watchdog.sh --dry-run',
|
||||
].join('\n'));
|
||||
}
|
||||
|
||||
/**
|
||||
* 解析命令行参数。
|
||||
* @param {string[]} argv process.argv.slice(2)。
|
||||
* @return {{envName: string, command: string}} 解析结果。
|
||||
* @return {{envName: string, command: string, dryRun: boolean}} 解析结果。
|
||||
* @throws {Error} 缺少/非法命令时抛出。
|
||||
*/
|
||||
function parseArgs(argv) {
|
||||
const options = { envName: 'production', command: '' };
|
||||
const options = { envName: 'production', command: '', dryRun: false };
|
||||
const tokens = [ ...argv ];
|
||||
if (tokens.length === 0) {
|
||||
throw new Error(`missing command: ${COMMAND_HINT}`);
|
||||
options.dryRun = tokens.includes('--dry-run');
|
||||
const positional = tokens.filter(token => token !== '--dry-run');
|
||||
if (positional.length === 0) {
|
||||
printUsage();
|
||||
throw new Error('missing command: install | uninstall');
|
||||
}
|
||||
if (!COMMANDS.has(tokens[0])) {
|
||||
options.envName = tokens[0];
|
||||
tokens.shift();
|
||||
if (!COMMANDS.has(positional[0])) {
|
||||
options.envName = positional[0];
|
||||
positional.shift();
|
||||
}
|
||||
if (tokens.length === 0 || !COMMANDS.has(tokens[0])) {
|
||||
throw new Error(`missing command: ${COMMAND_HINT}`);
|
||||
if (positional.length === 0 || !COMMANDS.has(positional[0])) {
|
||||
printUsage();
|
||||
throw new Error('missing command: install | uninstall');
|
||||
}
|
||||
options.command = tokens[0];
|
||||
options.command = positional[0];
|
||||
return options;
|
||||
}
|
||||
|
||||
@ -124,11 +147,12 @@ function buildCronFileContent(watchdogPath) {
|
||||
}
|
||||
|
||||
/**
|
||||
* 只读预检:确认目标机具备安装条件。
|
||||
* 安装前只读打印目标机环境快照(部署根、current.md、cron.d、实例与端口等),
|
||||
* 让安装日志保留一份「安装前」现场;只读,不启动 / 不杀任何进程。
|
||||
* @param {Object} config deploy 配置对象。
|
||||
* @return {void}
|
||||
*/
|
||||
function runPrecheck(config) {
|
||||
function printTargetEnvInfo(config) {
|
||||
const deployRoot = config.deployRoot;
|
||||
const remoteScript = [
|
||||
'set -uo pipefail',
|
||||
@ -149,7 +173,7 @@ function runPrecheck(config) {
|
||||
'echo "[PORTS]"; ss -lntp 2>/dev/null | grep -E ":6061|:6062" || echo "no 6061/6062 listener"',
|
||||
].join('\n');
|
||||
|
||||
console.log('[PRECHECK] watchdog remote env check (read-only, no service start/kill)');
|
||||
console.log('[INSTALL] 目标机环境快照(只读,不启动/不杀进程)');
|
||||
console.log(String(runSsh(config, remoteScript, { stdio: 'pipe' }) || '').trim());
|
||||
}
|
||||
|
||||
@ -160,6 +184,7 @@ function runPrecheck(config) {
|
||||
*/
|
||||
function runInstall(config) {
|
||||
const deployRoot = config.deployRoot;
|
||||
printTargetEnvInfo(config);
|
||||
if (!fs.existsSync(LOCAL_WATCHDOG)) {
|
||||
throw new Error(`local file missing: ${LOCAL_WATCHDOG} (script/qimen-watchdog.sh)`);
|
||||
}
|
||||
@ -220,70 +245,228 @@ function runInstall(config) {
|
||||
}
|
||||
|
||||
/**
|
||||
* 状态:只读查看副本、cron.d、日志、锁、探活结果,并与本地源比对哈希。
|
||||
* @param {Object} config deploy 配置对象。
|
||||
* @return {void}
|
||||
* 生成卸载目标清单:服务器副本 + 历史位置 + 备份 glob(.prev-* / .legacy-*)。
|
||||
* @param {string} deployRoot 部署根目录。
|
||||
* @return {{ exactPaths: string[], globPatterns: string[] }} 目标清单。
|
||||
*/
|
||||
function runStatus(config) {
|
||||
const target = remoteWatchdogPath(config);
|
||||
const localSha = fs.existsSync(LOCAL_WATCHDOG) ? localSha256(LOCAL_WATCHDOG) : '(local file missing)';
|
||||
|
||||
const remoteScript = [
|
||||
'set -uo pipefail',
|
||||
`TARGET=${quoteForBash(target)}`,
|
||||
`CRON_D=${quoteForBash(CRON_D_PATH)}`,
|
||||
'echo "[WATCHDOG_FILE]"; if [ -f "$TARGET" ]; then ls -l --time-style=full-iso "$TARGET"; else echo "MISSING"; fi',
|
||||
'echo "[SHA_REMOTE]"; sha256sum "$TARGET" 2>/dev/null || echo "(missing)"',
|
||||
'echo "[CRON_D]"; cat "$CRON_D" 2>/dev/null || echo "MISSING"',
|
||||
'echo "[CRON_SERVICE]"; systemctl is-active cron 2>/dev/null || echo unknown',
|
||||
'echo "[ROOT_CRONTAB_MATCH]"; crontab -l 2>/dev/null | grep -n "qimen-watchdog" || echo NONE',
|
||||
'echo "[LOCK]"; ls -l ' + quoteForBash(LOCK_PATH) + ' 2>/dev/null || echo "lock not created yet"',
|
||||
'echo "[LOG_TAIL]"; tail -10 ' + quoteForBash(LOG_PATH) + ' 2>/dev/null || echo "log missing"',
|
||||
'echo "[INSTANCES]"; ps -eo pid=,etime=,args= | grep "[e]gg-scripts start" | head -6 || true',
|
||||
'echo "[PORTS]"; ss -lntp 2>/dev/null | grep -E ":6061|:6062" || echo "no 6061/6062 listener"',
|
||||
'echo "[PROBE_DRY_RUN]"; bash "$TARGET" --dry-run 2>&1 | tail -12 || true',
|
||||
].join('\n');
|
||||
|
||||
console.log('[STATUS] watchdog (read-only; probe uses --dry-run)');
|
||||
console.log(`[STATUS] local source sha256 = ${localSha}`);
|
||||
console.log(String(runSsh(config, remoteScript, { stdio: 'pipe' }) || '').trim());
|
||||
function buildUninstallTargets(deployRoot) {
|
||||
const exactPaths = [
|
||||
`${deployRoot}/${REMOTE_RELATIVE}`,
|
||||
`${deployRoot}/${REMOTE_FILENAME}`,
|
||||
];
|
||||
const globPatterns = [];
|
||||
for (const base of exactPaths) {
|
||||
globPatterns.push(`${base}.prev-*`, `${base}.legacy-*`);
|
||||
}
|
||||
return { exactPaths, globPatterns };
|
||||
}
|
||||
|
||||
/**
|
||||
* 远端执行看门狗脚本(转发参数)。
|
||||
* 生成 dry-run 计划脚本(只读:只打印将备份/将删除的目标与将注销的 cron 项)。
|
||||
* @param {Object} config deploy 配置对象。
|
||||
* @param {string[]} extraArgs 追加参数(如 --dry-run)。
|
||||
* @return {string} 远端输出。
|
||||
* @param {string} backupDir 计划使用的备份目录(dry-run 不创建)。
|
||||
* @return {string} 远端 bash 脚本。
|
||||
*/
|
||||
function runRemoteWatchdog(config, extraArgs = []) {
|
||||
const script = `bash ${quoteForBash(remoteWatchdogPath(config))}${extraArgs.map(arg => ` ${arg}`).join('')}`;
|
||||
return String(runSsh(config, script) || '');
|
||||
function buildUninstallDryRunScript(config, backupDir) {
|
||||
const { exactPaths, globPatterns } = buildUninstallTargets(config.deployRoot);
|
||||
return [
|
||||
'set -uo pipefail',
|
||||
`B_DIR=${quoteForBash(backupDir)}`,
|
||||
'echo "PLAN_BACKUP_DIR=$B_DIR"',
|
||||
`for T in ${exactPaths.map(quoteForBash).join(' ')}; do`,
|
||||
' if [ -f "$T" ]; then echo "WOULD_BACKUP_AND_DELETE $T"; else echo "MISSING_SKIP $T"; fi',
|
||||
'done',
|
||||
`for G in ${globPatterns.map(quoteForBash).join(' ')}; do`,
|
||||
' for F in $G; do',
|
||||
' [ -f "$F" ] || continue',
|
||||
' echo "WOULD_BACKUP_AND_DELETE $F"',
|
||||
' done',
|
||||
'done',
|
||||
`CRON_D=${quoteForBash(CRON_D_PATH)}`,
|
||||
'if [ -f "$CRON_D" ]; then echo "WOULD_BACKUP_AND_DELETE $CRON_D"; else echo "MISSING_SKIP $CRON_D"; fi',
|
||||
'CRON_BEFORE=$(crontab -l 2>/dev/null | wc -l)',
|
||||
'CRON_HIT=$(crontab -l 2>/dev/null | grep -c "qimen-watchdog" || true)',
|
||||
'if [ "$CRON_HIT" -gt 0 ]; then',
|
||||
' crontab -l 2>/dev/null | grep "qimen-watchdog" | sed "s|^|WOULD_REMOVE_CRON_LINE |" || true',
|
||||
' echo "CRONTAB_WOULD_GO before=$CRON_BEFORE after=$((CRON_BEFORE - CRON_HIT))"',
|
||||
'else',
|
||||
' echo "CRONTAB_UNTOUCHED_NO_MATCH"',
|
||||
'fi',
|
||||
].join('\n');
|
||||
}
|
||||
|
||||
/**
|
||||
* 生成真实卸载脚本:先备份(cp -a 保留权限/时间)再删除,并注销调度:
|
||||
* - 删除 /etc/cron.d/qimen-watchdog(先备份);
|
||||
* - 清理 root crontab 中残留的 qimen-watchdog 行(历史手工安装可能留过)。
|
||||
* 单项失败不中断(HAD_ERRORS 标记);日志 / 锁 / 服务 / nginx / 数据库一律不触碰。
|
||||
* @param {Object} config deploy 配置对象。
|
||||
* @param {string} backupDir 备份目录(/tmp/qimen-watchdog-uninstall-<时间戳>/)。
|
||||
* @return {string} 远端 bash 脚本。
|
||||
*/
|
||||
function buildUninstallScript(config, backupDir) {
|
||||
const { exactPaths, globPatterns } = buildUninstallTargets(config.deployRoot);
|
||||
return [
|
||||
'set -u',
|
||||
`BACKUP_DIR=${quoteForBash(backupDir)}`,
|
||||
'HAD_ERRORS=0',
|
||||
'mkdir -p "$BACKUP_DIR" && echo "BACKUP_DIR=$BACKUP_DIR" || { echo "BACKUP_DIR_CREATE_FAILED $BACKUP_DIR"; HAD_ERRORS=1; }',
|
||||
`for T in ${exactPaths.map(quoteForBash).join(' ')}; do`,
|
||||
' if [ -f "$T" ]; then',
|
||||
' BASE=$(basename "$T")',
|
||||
' if cp -a "$T" "$BACKUP_DIR/$BASE"; then echo "BACKED_UP $T -> $BACKUP_DIR/$BASE"; else echo "BACKUP_FAILED $T (保留未删)"; HAD_ERRORS=1; continue; fi',
|
||||
' if rm -f "$T"; then echo "DELETED $T"; else echo "DELETE_FAILED $T"; HAD_ERRORS=1; fi',
|
||||
' else',
|
||||
' echo "MISSING_SKIP $T"',
|
||||
' fi',
|
||||
'done',
|
||||
`for G in ${globPatterns.map(quoteForBash).join(' ')}; do`,
|
||||
' for F in $G; do',
|
||||
' [ -f "$F" ] || continue',
|
||||
' BASE=$(basename "$F")',
|
||||
' if cp -a "$F" "$BACKUP_DIR/$BASE"; then echo "BACKED_UP $F -> $BACKUP_DIR/$BASE"; else echo "BACKUP_FAILED $F (保留未删)"; HAD_ERRORS=1; continue; fi',
|
||||
' if rm -f "$F"; then echo "DELETED $F"; else echo "DELETE_FAILED $F"; HAD_ERRORS=1; fi',
|
||||
' done',
|
||||
'done',
|
||||
`CRON_D=${quoteForBash(CRON_D_PATH)}`,
|
||||
'if [ -f "$CRON_D" ]; then',
|
||||
' if cp -a "$CRON_D" "$BACKUP_DIR/qimen-watchdog.cron.d"; then echo "BACKED_UP $CRON_D -> $BACKUP_DIR/qimen-watchdog.cron.d"; else echo "BACKUP_FAILED $CRON_D (保留未删)"; HAD_ERRORS=1; fi',
|
||||
' if rm -f "$CRON_D"; then echo "CRON_D_REMOVED $CRON_D"; else echo "CRON_D_REMOVE_FAILED $CRON_D"; HAD_ERRORS=1; fi',
|
||||
'else',
|
||||
' echo "MISSING_SKIP $CRON_D"',
|
||||
'fi',
|
||||
'CRON_BEFORE=$(crontab -l 2>/dev/null | wc -l)',
|
||||
'CRON_HIT=$(crontab -l 2>/dev/null | grep -c "qimen-watchdog" || true)',
|
||||
'if [ "$CRON_HIT" -gt 0 ]; then',
|
||||
' crontab -l 2>/dev/null | grep "qimen-watchdog" | sed "s|^|CRON_REMOVED_LINE |" || true',
|
||||
' if ( crontab -l 2>/dev/null | grep -v "qimen-watchdog" || true ) | crontab -; then',
|
||||
' echo "CRONTAB_REWRITTEN before=$CRON_BEFORE after=$(crontab -l 2>/dev/null | wc -l)"',
|
||||
' else',
|
||||
' echo "CRONTAB_REWRITE_FAILED"',
|
||||
' HAD_ERRORS=1',
|
||||
' fi',
|
||||
'else',
|
||||
' echo "CRONTAB_UNTOUCHED_NO_MATCH"',
|
||||
'fi',
|
||||
'echo "HAD_ERRORS=$HAD_ERRORS"',
|
||||
].join('\n');
|
||||
}
|
||||
|
||||
/**
|
||||
* 打印卸载结果(三段:备份 / 已删除(含调度注销)/ 未触碰)。
|
||||
* @param {string} output 远端脚本输出。
|
||||
* @param {boolean} dryRun 是否 dry-run(只打印计划)。
|
||||
* @param {string} backupDir 备份目录路径。
|
||||
* @return {void}
|
||||
*/
|
||||
function printUninstallReport(output, dryRun, backupDir) {
|
||||
const lines = String(output || '')
|
||||
.split(/\r?\n/)
|
||||
.map(line => line.trim())
|
||||
.filter(Boolean);
|
||||
const planned = [];
|
||||
const backedUp = [];
|
||||
const deleted = [];
|
||||
const untouched = [];
|
||||
const failures = [];
|
||||
|
||||
for (const line of lines) {
|
||||
if (line === 'HAD_ERRORS=0' || line === 'HAD_ERRORS=1') {
|
||||
continue;
|
||||
}
|
||||
if (/^(WOULD_BACKUP_AND_DELETE|WOULD_REMOVE_CRON_LINE|CRONTAB_WOULD_GO|PLAN_BACKUP_DIR)/.test(line)) {
|
||||
planned.push(line);
|
||||
continue;
|
||||
}
|
||||
if (/^(BACKED_UP|BACKUP_DIR=)/.test(line)) {
|
||||
backedUp.push(line);
|
||||
continue;
|
||||
}
|
||||
if (/^(DELETED|CRON_D_REMOVED|CRON_REMOVED_LINE|CRONTAB_REWRITTEN)/.test(line)) {
|
||||
deleted.push(line);
|
||||
continue;
|
||||
}
|
||||
if (/^(MISSING_SKIP|CRONTAB_UNTOUCHED_NO_MATCH)/.test(line)) {
|
||||
untouched.push(line);
|
||||
continue;
|
||||
}
|
||||
if (/FAIL|ERROR/.test(line)) {
|
||||
failures.push(line);
|
||||
continue;
|
||||
}
|
||||
failures.push(`UNCLASSIFIED ${line}`);
|
||||
}
|
||||
|
||||
const suffix = dryRun ? '(计划)' : '';
|
||||
const backupLines = dryRun ? planned : backedUp;
|
||||
const deleteLines = dryRun
|
||||
? planned.filter(line => !line.startsWith('PLAN_BACKUP_DIR'))
|
||||
: deleted;
|
||||
console.log(`[UNINSTALL] 备份${suffix}`);
|
||||
for (const line of (backupLines.length > 0 ? backupLines : [ '(无)' ])) {
|
||||
console.log(` ${line}`);
|
||||
}
|
||||
console.log(`[UNINSTALL] 已删除 / 已注销调度${suffix}`);
|
||||
for (const line of (deleteLines.length > 0 ? deleteLines : [ '(无)' ])) {
|
||||
console.log(` ${line}`);
|
||||
}
|
||||
console.log('[UNINSTALL] 未触碰(原因)');
|
||||
for (const line of untouched) {
|
||||
console.log(` ${line}`);
|
||||
}
|
||||
console.log(` 日志(保留作排查线索):${LOG_PATH}`);
|
||||
console.log(` 锁文件(空闲时本就不存在):${LOCK_PATH}`);
|
||||
console.log(' 接口服务进程 / nginx / 数据库:本工具从不触碰');
|
||||
if (failures.length > 0) {
|
||||
console.error('[UNINSTALL] 失败项');
|
||||
for (const line of failures) {
|
||||
console.error(` ${line}`);
|
||||
}
|
||||
}
|
||||
console.log(`[UNINSTALL] 备份目录:${backupDir}`);
|
||||
}
|
||||
|
||||
/**
|
||||
* 卸载:备份 → 注销调度(/etc/cron.d 与 root crontab 残留行)→ 删除服务器副本。
|
||||
* @param {Object} config deploy 配置对象。
|
||||
* @param {{dryRun: boolean}} options 解析后的参数。
|
||||
* @return {void}
|
||||
*/
|
||||
function runUninstall(config, options) {
|
||||
const backupDir = `/tmp/qimen-watchdog-uninstall-${getNowStamp()}/`;
|
||||
const script = options.dryRun
|
||||
? buildUninstallDryRunScript(config, backupDir)
|
||||
: buildUninstallScript(config, backupDir);
|
||||
|
||||
if (options.dryRun) {
|
||||
console.log('[UNINSTALL] dry-run(只读:只打印计划,不备份、不删除、不改 crontab)');
|
||||
} else {
|
||||
console.log('[UNINSTALL] 开始卸载(先备份再删除,并注销 /etc/cron.d 与 root crontab 行)');
|
||||
}
|
||||
|
||||
const output = String(runSsh(config, script, { stdio: 'pipe' }) || '');
|
||||
printUninstallReport(output, options.dryRun, backupDir);
|
||||
|
||||
if (options.dryRun) {
|
||||
console.log('[UNINSTALL] dry-run 结束(未做任何变更)');
|
||||
return;
|
||||
}
|
||||
if (/(^|\n)HAD_ERRORS=1/.test(output)) {
|
||||
console.error('[UNINSTALL] 存在失败项(见上),可从备份目录恢复');
|
||||
process.exitCode = 1;
|
||||
}
|
||||
}
|
||||
|
||||
function main() {
|
||||
const options = parseArgs(process.argv.slice(2));
|
||||
const config = loadDeployConfig(options.envName);
|
||||
|
||||
if (options.command === 'precheck') {
|
||||
runPrecheck(config);
|
||||
return;
|
||||
}
|
||||
if (options.command === 'install') {
|
||||
runInstall(config);
|
||||
return;
|
||||
}
|
||||
if (options.command === 'status') {
|
||||
runStatus(config);
|
||||
return;
|
||||
}
|
||||
if (options.command === 'dry-run') {
|
||||
console.log('[DRY-RUN] remote watchdog --dry-run (probe only, never starts/kills)');
|
||||
console.log(runRemoteWatchdog(config, [ '--dry-run' ]));
|
||||
return;
|
||||
}
|
||||
if (options.command === 'run') {
|
||||
console.log('[RUN] remote watchdog real execution (starts the instance only when probe fails)');
|
||||
console.log(runRemoteWatchdog(config, []));
|
||||
if (options.command === 'uninstall') {
|
||||
runUninstall(config, options);
|
||||
return;
|
||||
}
|
||||
throw new Error(`unsupported command: ${options.command}`);
|
||||
|
||||
Loading…
x
Reference in New Issue
Block a user