/** * cert-sync 部署工具(npm 命令仅 install / uninstall 两条)。 * * - install:校验并上传主脚本 / DB 配置;prod 配置按「首次放置一次、永不覆盖」约定处理; * 生成薄包装 /script/warehouse-cert-sync.sh 并注册 root crontab(每分钟 flock)。 * - uninstall:先备份再删除工具自身(包装脚本 / 主脚本 / 双环境配置 / database/config.js / * 历史位置与 .prev-* / .legacy-* 备份 / crontab 行);支持 --dry-run 只打印计划。 * 证书、nginx server 块、日志、watchdog 相关一律不删(原因见输出)。 * * 运行期手动操作仍可直接调用服务器上的包装脚本(这是主脚本 CLI 的能力,不属于本工具 npm 命令): * /script/warehouse-cert-sync.sh --dry-run * /script/warehouse-cert-sync.sh --cleanup-only --dry-run * /script/warehouse-cert-sync.sh --cleanup-only * /script/warehouse-cert-sync.sh --env production */ 'use strict'; const fs = require('node:fs'); const path = require('node:path'); const { ROOT, getNowStamp, loadDeployConfig, quoteForBash, runScp, runSsh, } = require('./deploy-lib.cjs'); const COMMANDS = new Set([ 'install', 'uninstall' ]); const LOCAL_SYNC_SCRIPT = path.join(ROOT, 'script', 'warehouse-cert-sync.cjs'); const LOCAL_DB_CONFIG = path.join(ROOT, 'database', 'config.js'); const LOCAL_PROD_CONFIG = path.join(ROOT, 'script', 'warehouse-cert-sync.config.prod.json'); /** * 打印本工具用法(仅 install / uninstall 两条 npm 命令)。 */ function printUsage() { console.error([ 'usage: node script/deploy-cert-sync.cjs [env] [--dry-run]', ' env: production | development(默认 production)', ' command: install 上传脚本/配置、生成薄包装、注册 crontab', ' uninstall 备份并删除工具自身(脚本/配置/crontab),支持 --dry-run', '运行期手动操作请直接调用服务器上的包装脚本(主脚本 CLI 能力,非本工具命令):', ' /script/warehouse-cert-sync.sh --dry-run', ' /script/warehouse-cert-sync.sh --cleanup-only --dry-run', ' /script/warehouse-cert-sync.sh --cleanup-only', ' /script/warehouse-cert-sync.sh --env production', ].join('\n')); } /** * 解析命令行参数。 * @param {string[]} argv 原始参数数组(不含 node / 脚本名)。 * @return {{ envName: string, command: string, dryRun: boolean }} 解析结果。 */ function parseArgs(argv) { const options = { envName: 'production', command: '', dryRun: false }; const tokens = [ ...argv ]; 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(positional[0])) { options.envName = positional[0]; positional.shift(); } if (positional.length === 0 || !COMMANDS.has(positional[0])) { printUsage(); throw new Error('missing command: install | uninstall'); } options.command = positional[0]; return options; } /** * Build the thin shell wrapper content for the server. * 薄包装职责收敛为: * 1. cd 部署根目录(脚本以部署根为 cwd 运行,certDir/confDir 按 prod 配置解析); * 2. 运行时依赖引导:从活跃实例 node_modules 借用 sequelize(部署根无 node_modules); * 3. 运行时 DB 引导:从活跃实例 egg 配置解析 DB_* 环境变量(不落盘、不打印凭据); * 4. 执行 node script/warehouse-cert-sync.cjs --env production "$@"。 * nginx 二进制 / upstream include / reload 命令已全部收敛到 * script/warehouse-cert-sync.config.prod.json,本包装不再注入任何 nginx 相关参数。 */ function buildWrapperContent() { return `#!/usr/bin/env bash # ============================================================== # warehouse-cert-sync thin shell wrapper (installed by wms-deploy-agent) # 1. cd into deploy root; cert/conf default to ../.ssl and ../nginx_config # 2. nginx binary / upstream include / reload 命令全部来自 prod 配置文件 # 3. resolve prod DB connection at runtime from the ACTIVE instance egg # config (exported as DB_* env vars only; not persisted, never printed) # 4. dependency resolution: borrow sequelize from active instance node_modules # 5. all output appended to /var/log/warehouse-cert-sync.log (tee to tty) # ============================================================== set -uo pipefail DEPLOY_ROOT='/www/wwwroot/qimen' LOG_FILE='/var/log/warehouse-cert-sync.log' exec > >(tee -a "$LOG_FILE") 2>&1 echo "===== $(date '+%F %T') warehouse-cert-sync.sh args=[$*] =====" cd "$DEPLOY_ROOT" || { echo "[CERT-WRAPPER] FATAL cannot enter $DEPLOY_ROOT"; exit 1; } # ---------- nginx 参数来源 ---------- # nginx 二进制 / upstream include / reload 命令全部由 # script/warehouse-cert-sync.config.prod.json 提供(--env production 自动加载), # 本包装不再注入 --nginx-bin / --upstream-include / --reload-cmd 参数。 # ---------- runtime dependency resolution ---------- # borrow sequelize etc. from the active instance node_modules via NODE_PATH if [ ! -d "$DEPLOY_ROOT/node_modules" ]; then ACTIVE_VERSION='' if [ -f "$DEPLOY_ROOT/current.md" ]; then ACTIVE_VERSION="$(tr -d '[:space:]' < "$DEPLOY_ROOT/current.md")" fi for CAND in "$ACTIVE_VERSION" v1 v2; do if [ -n "$CAND" ] && [ -d "$DEPLOY_ROOT/$CAND/node_modules" ]; then export NODE_PATH="$DEPLOY_ROOT/$CAND/node_modules\${NODE_PATH:+:$NODE_PATH}" echo "[CERT-WRAPPER] NODE_PATH -> $DEPLOY_ROOT/$CAND/node_modules" break fi done fi # ---------- prod DB connection resolution ---------- # deploy root has no config dir (release mechanism ships app code only), so the # DB connection is resolved from the active instance egg config at runtime. ACTIVE_APP_DIR='' if [ -n "\${ACTIVE_VERSION:-}" ] && [ -d "$DEPLOY_ROOT/$ACTIVE_VERSION/config" ]; then ACTIVE_APP_DIR="$DEPLOY_ROOT/$ACTIVE_VERSION" fi if [ -z "$ACTIVE_APP_DIR" ]; then for CAND in v1 v2; do if [ -d "$DEPLOY_ROOT/$CAND/config" ]; then ACTIVE_APP_DIR="$DEPLOY_ROOT/$CAND"; break; fi done fi if [ -z "$ACTIVE_APP_DIR" ]; then echo '[CERT-WRAPPER] FATAL no active instance dir found (current.md / v1 / v2)' exit 1 fi eval "$(node -e ' const path = require("node:path"); const appDir = process.argv[1]; function load(p) { try { const f = require(p); const c = typeof f === "function" ? f({ name: "cert-sync-wrapper", baseDir: appDir }) : f; return c && typeof c === "object" ? c : {}; } catch (e) { return {}; } } let src = "none"; let client = null; const def = load(path.join(appDir, "config", "config.default.js")); if (def.sequelize && def.sequelize.host) { src = "config.default.js#sequelize"; client = def.sequelize; } else if (def.mysql && def.mysql.clients && def.mysql.clients.wms && def.mysql.clients.wms.host) { src = "config.default.js#mysql.clients.wms"; client = def.mysql.clients.wms; } else if (def.mysql && def.mysql.host) { src = "config.default.js#mysql"; client = def.mysql; } if (!client) { const loc = load(path.join(appDir, "config", "config.local.js")); if (loc.sequelize && loc.sequelize.host) { src = "config.local.js#sequelize"; client = loc.sequelize; } else if (loc.mysql && loc.mysql.host) { src = "config.local.js#mysql"; client = loc.mysql; } } if (!client) { console.error("[CERT-WRAPPER] cannot resolve db config from: " + appDir); process.exit(1); } console.log("export DB_HOST=" + JSON.stringify(String(client.host || ""))); console.log("export DB_PORT=" + JSON.stringify(String(client.port || 3306))); console.log("export DB_USER=" + JSON.stringify(String(client.username || client.user || ""))); console.log("export DB_PASSWORD=" + JSON.stringify(String(client.password || ""))); console.log("export DB_NAME=" + JSON.stringify(String(client.database || "wms"))); console.error("[CERT-WRAPPER] db config source: " + src + " (database=" + String(client.database || "") + ")"); ' "$ACTIVE_APP_DIR")" || { echo '[CERT-WRAPPER] FATAL db config resolution failed'; exit 1; } # ---------- run main script ---------- # nginx 二进制 / upstream include / reload 命令全部由 prod 配置文件提供 node "$DEPLOY_ROOT/script/warehouse-cert-sync.cjs" --env production "$@" STATUS=$? echo "===== $(date '+%F %T') warehouse-cert-sync.sh exit=$STATUS =====" exit $STATUS `; } /** * Install: upload files, create thin shell wrapper, register root crontab. * @param {Object} config deploy 配置对象。 */ function runInstall(config) { const deployRoot = config.deployRoot; for (const [ file, label ] of [ [ LOCAL_SYNC_SCRIPT, 'script/warehouse-cert-sync.cjs' ], [ LOCAL_DB_CONFIG, 'database/config.js' ], ]) { if (!fs.existsSync(file)) { throw new Error(`local file missing: ${file} (${label})`); } } const remoteDirScript = [ 'set -euo pipefail', `DEPLOY_ROOT=${quoteForBash(deployRoot)}`, `STAMP=${quoteForBash(getNowStamp())}`, 'mkdir -p "$DEPLOY_ROOT/script" "$DEPLOY_ROOT/database"', 'for p in "$DEPLOY_ROOT/script/warehouse-cert-sync.sh" "$DEPLOY_ROOT/script/warehouse-cert-sync.cjs" "$DEPLOY_ROOT/database/config.js"; do', ' if [ -f "$p" ]; then cp -a "$p" "$p.prev-$STAMP" && echo "BACKED_UP $p -> $p.prev-$STAMP"; fi', 'done', '# 历史位置(部署根)一次性迁移:旧 wrapper 挪进 script/ 留作回滚备份,避免根目录残留孤儿', 'LEGACY="$DEPLOY_ROOT/warehouse-cert-sync.sh"', 'if [ -f "$LEGACY" ]; then mv "$LEGACY" "$DEPLOY_ROOT/script/warehouse-cert-sync.sh.legacy-$STAMP" && echo "LEGACY_MOVED $LEGACY -> $DEPLOY_ROOT/script/warehouse-cert-sync.sh.legacy-$STAMP"; fi', ].join('\n'); console.log('[INSTALL] remote dir prep + backup of existing files (wrapper installs under script/)'); console.log(runSsh(config, remoteDirScript, { stdio: 'pipe' }).trim()); const remoteScriptPath = `${deployRoot}/script/warehouse-cert-sync.cjs`; const remoteDbConfigPath = `${deployRoot}/database/config.js`; runScp(config, LOCAL_SYNC_SCRIPT, remoteScriptPath); console.log(`[INSTALL] uploaded -> ${remoteScriptPath}`); runScp(config, LOCAL_DB_CONFIG, remoteDbConfigPath); console.log(`[INSTALL] uploaded -> ${remoteDbConfigPath}`); // prod 配置文件:服务器「首次放置一次、之后永不覆盖」的发布约定。 // dev 配置只属于开发机,永不上传生产服务器。 if (!fs.existsSync(LOCAL_PROD_CONFIG)) { throw new Error(`local file missing: ${LOCAL_PROD_CONFIG}`); } JSON.parse(fs.readFileSync(LOCAL_PROD_CONFIG, 'utf8')); const prodConfigRemotePath = `${deployRoot}/script/warehouse-cert-sync.config.prod.json`; const prodConfigProbeScript = [ 'set -euo pipefail', `PROD_CONFIG=${quoteForBash(prodConfigRemotePath)}`, 'if [ -f "$PROD_CONFIG" ]; then', ' echo "PROD_CONFIG_EXISTS"', ' if node -e \'JSON.parse(require("node:fs").readFileSync(process.argv[1], "utf8"))\' "$PROD_CONFIG" >/dev/null 2>&1; then', ' echo "PROD_CONFIG_JSON_VALID"', ' else', ' echo "PROD_CONFIG_JSON_INVALID"', ' fi', 'else', ' echo "PROD_CONFIG_MISSING"', 'fi', ].join('\n'); const prodConfigProbe = String(runSsh(config, prodConfigProbeScript, { stdio: 'pipe' }) || '').trim(); console.log(prodConfigProbe); if (prodConfigProbe.includes('PROD_CONFIG_EXISTS')) { console.log('[INSTALL] prod config already on server -> skip placement (发布约定:永不覆盖)'); } else { runScp(config, LOCAL_PROD_CONFIG, prodConfigRemotePath); console.log(`[INSTALL] placed once -> ${prodConfigRemotePath}`); const verifyScript = [ 'set -euo pipefail', `node -e ${quoteForBash('JSON.parse(require("node:fs").readFileSync(process.argv[1], "utf8")); console.log("PROD_CONFIG_JSON_VALID")')} ${quoteForBash(prodConfigRemotePath)}`, ].join('\n'); console.log(String(runSsh(config, verifyScript, { stdio: 'pipe' }) || '').trim()); } console.log('[INSTALL] dev config NOT uploaded (development-only)'); const wrapperPath = `${deployRoot}/script/warehouse-cert-sync.sh`; const installScript = [ 'set -euo pipefail', `DEPLOY_ROOT=${quoteForBash(deployRoot)}`, `WRAPPER=${quoteForBash(wrapperPath)}`, 'LOG_FILE="/var/log/warehouse-cert-sync.log"', 'cat > "$WRAPPER" <<\'WMS_CERT_WRAPPER_EOF\'', buildWrapperContent(), 'WMS_CERT_WRAPPER_EOF', 'chmod 755 "$WRAPPER"', 'bash -n "$WRAPPER" && echo "WRAPPER_SYNTAX_OK"', 'touch "$LOG_FILE" && chmod 644 "$LOG_FILE" && echo "LOG_FILE_OK"', 'FLOCK_BIN=$(command -v flock || true)', 'if [ -z "$FLOCK_BIN" ]; then echo "FATAL: flock not found, cannot register crontab"; exit 1; fi', 'echo "FLOCK_BIN=$FLOCK_BIN"', 'CRON_LINE="* * * * * $FLOCK_BIN -n /var/lock/warehouse-cert-sync.lock $WRAPPER >/dev/null 2>&1"', '( crontab -l 2>/dev/null | grep -v "warehouse-cert-sync" || true; printf "%s\\n" "$CRON_LINE" ) | crontab -', 'echo "CRONTAB_INSTALLED:"', 'crontab -l | grep -n "warehouse-cert-sync" || true', ].join('\n'); console.log('[INSTALL] write thin shell wrapper + register crontab'); console.log(runSsh(config, installScript, { stdio: 'pipe' }).trim()); } /** * 把远端配置里的目录值(如 ./.ssl)按部署根解析成绝对路径。 * @param {string} deployRoot 部署根目录。 * @param {string} value 配置值(相对或绝对)。 * @param {string} fallback 解析失败时的默认值。 * @return {string} 远端绝对路径。 */ function resolveRemotePath(deployRoot, value, fallback) { const v = String(value || '').trim(); if (!v) return fallback; if (v.startsWith('/')) return v; return `${String(deployRoot).replace(/\/+$/, '')}/${v.replace(/^\.\//, '')}`; } /** * 只读解析服务器 prod 配置中的 certDir / confDir(用于「未触碰」清单展示)。 * 配置缺失或解析失败时回退默认值(/.ssl、/nginx_config),不阻断卸载流程。 * @param {Object} config deploy 配置对象。 * @return {{ certDir: string, confDir: string }} 解析出的远端绝对目录。 */ function resolveServerDirs(config) { const deployRoot = config.deployRoot; const defaultCertDir = `${deployRoot}/.ssl`; const defaultConfDir = `${deployRoot}/nginx_config`; const result = { certDir: defaultCertDir, confDir: defaultConfDir }; const cfgPath = `${deployRoot}/script/warehouse-cert-sync.config.prod.json`; const probeScript = [ 'set -uo pipefail', `CFG=${quoteForBash(cfgPath)}`, 'if [ -f "$CFG" ]; then', ` node -e ${quoteForBash('const c=JSON.parse(require("node:fs").readFileSync(process.argv[1],"utf8")); console.log("CERT_DIR="+(c.certDir||"./.ssl")); console.log("CONF_DIR="+(c.confDir||"./nginx_config"));')} "$CFG"`, 'else', ' echo "CERT_DIR=./.ssl"', ' echo "CONF_DIR=./nginx_config"', 'fi', ].join('\n'); try { const output = String(runSsh(config, probeScript, { stdio: 'pipe' }) || ''); for (const line of output.split('\n')) { if (line.startsWith('CERT_DIR=')) { result.certDir = resolveRemotePath(deployRoot, line.slice(9), defaultCertDir); } if (line.startsWith('CONF_DIR=')) { result.confDir = resolveRemotePath(deployRoot, line.slice(9), defaultConfDir); } } } catch (err) { console.warn(`[UNINSTALL] 服务器目录探测失败,回退默认值:${err.message}`); } return result; } /** * 生成卸载目标清单:精确路径 + 历史备份 glob(.prev-* / .legacy-*)。 * @param {string} deployRoot 部署根目录。 * @return {{ exactPaths: string[], globPatterns: string[] }} 目标清单。 */ function buildUninstallTargets(deployRoot) { const exactPaths = [ `${deployRoot}/script/warehouse-cert-sync.sh`, `${deployRoot}/warehouse-cert-sync.sh`, `${deployRoot}/script/warehouse-cert-sync.cjs`, `${deployRoot}/script/warehouse-cert-sync.config.prod.json`, `${deployRoot}/script/warehouse-cert-sync.config.dev.json`, `${deployRoot}/database/config.js`, ]; const globPatterns = []; for (const base of [ `${deployRoot}/script/warehouse-cert-sync.sh`, `${deployRoot}/warehouse-cert-sync.sh`, `${deployRoot}/script/warehouse-cert-sync.cjs`, `${deployRoot}/script/warehouse-cert-sync.config.prod.json`, `${deployRoot}/script/warehouse-cert-sync.config.dev.json`, `${deployRoot}/database/config.js`, ]) { globPatterns.push(`${base}.prev-*`, `${base}.legacy-*`); } return { exactPaths, globPatterns }; } /** * 生成 dry-run 计划脚本(只读:只打印将备份/将删除的目标与将清理的 crontab 行)。 * @param {Object} config deploy 配置对象。 * @param {string} backupDir 计划使用的备份目录(dry-run 不创建)。 * @return {string} 远端 bash 脚本。 */ 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_BEFORE=$(crontab -l 2>/dev/null | wc -l)', 'CRON_CERT=$(crontab -l 2>/dev/null | grep -c "warehouse-cert-sync" || true)', 'if [ "$CRON_CERT" -gt 0 ]; then', ' crontab -l 2>/dev/null | grep "warehouse-cert-sync" | sed "s|^|WOULD_REMOVE_CRON_LINE |" || true', ' echo "CRONTAB_WOULD_GO before=$CRON_BEFORE after=$((CRON_BEFORE - CRON_CERT))"', 'else', ' echo "CRONTAB_UNTOUCHED_NO_MATCH"', 'fi', ].join('\n'); } /** * 生成真实卸载脚本:先备份(cp -a 保留权限/时间)再删除,清理 crontab 行。 * 单项失败不中断(HAD_ERRORS 标记),证书/server 块/日志/watchdog 一律不触碰。 * @param {Object} config deploy 配置对象。 * @param {string} backupDir 备份目录(/tmp/wms-cert-sync-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', ' 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_BEFORE=$(crontab -l 2>/dev/null | wc -l)', 'CRON_CERT=$(crontab -l 2>/dev/null | grep -c "warehouse-cert-sync" || true)', 'if [ "$CRON_CERT" -gt 0 ]; then', ' crontab -l 2>/dev/null | grep "warehouse-cert-sync" | sed "s|^|CRON_REMOVED_LINE |" || true', ' if ( crontab -l 2>/dev/null | grep -v "warehouse-cert-sync" || 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'); } /** * 按三段结构打印卸载输出:[UNINSTALL] 备份 / [UNINSTALL] 已删除 / [UNINSTALL] 未触碰(原因)。 * @param {string} output 远端脚本输出。 * @param {boolean} dryRun 是否 dry-run(只打印计划)。 * @param {string} backupDir 备份目录路径。 * @param {{ certDir: string, confDir: string }} dirs 证书/server 块目录解析结果。 * @param {string} deployRoot 部署根目录。 */ function printUninstallReport(output, dryRun, backupDir, dirs, deployRoot) { const lines = String(output || '').split(/\r?\n/); const planNote = dryRun ? '(计划,未执行)' : ''; const backupLines = []; const deletedLines = []; for (const line of lines) { if (line.startsWith('PLAN_BACKUP_DIR=')) { backupLines.push(`BACKUP_DIR=${line.slice('PLAN_BACKUP_DIR='.length)}${dryRun ? '(计划,不创建)' : ''}`); } else if (line.startsWith('WOULD_BACKUP_AND_DELETE ')) { const src = line.slice('WOULD_BACKUP_AND_DELETE '.length); backupLines.push(`BACKED_UP ${src} -> ${backupDir}${src.split('/').pop()}${planNote}`); deletedLines.push(`DELETED ${src}${planNote}`); } else if (line.startsWith('MISSING_SKIP ')) { backupLines.push(`SKIP ${line.slice('MISSING_SKIP '.length)}(不存在)`); } else if (line.startsWith('BACKUP_DIR=')) { backupLines.push(line); } else if (line.startsWith('BACKUP_DIR_CREATE_FAILED ')) { backupLines.push(line); } else if (line.startsWith('BACKED_UP ')) { backupLines.push(line); } else if (line.startsWith('BACKUP_FAILED ')) { backupLines.push(line); } else if (line.startsWith('DELETED ')) { deletedLines.push(line); } else if (line.startsWith('DELETE_FAILED ')) { deletedLines.push(line); } else if (line.startsWith('WOULD_REMOVE_CRON_LINE ')) { deletedLines.push(`CRON_REMOVED_LINE ${line.slice('WOULD_REMOVE_CRON_LINE '.length)}${planNote}`); } else if (line.startsWith('CRON_REMOVED_LINE ')) { deletedLines.push(line); } else if (line.startsWith('CRONTAB_REWRITTEN ')) { deletedLines.push(line); } else if (line.startsWith('CRONTAB_WOULD_GO ')) { deletedLines.push(`${line}${dryRun ? '(计划,未执行)' : ''}`); } else if (line.startsWith('CRONTAB_UNTOUCHED_NO_MATCH')) { deletedLines.push('crontab 无 warehouse-cert-sync 行,未改写'); } } console.log(`[UNINSTALL] 备份${dryRun ? '(计划)' : ''}`); for (const line of backupLines) console.log(` ${line}`); console.log(`[UNINSTALL] 已删除${dryRun ? '(计划)' : ''}`); for (const line of deletedLines) console.log(` ${line}`); console.log('[UNINSTALL] 未触碰(原因)'); console.log(` CERT_DIR_KEPT ${dirs.certDir}(运行产物:证书/私钥,nginx 仍在 include,删除会立断 443;由运维自行决定,如先切走 include 再手工删)`); console.log(` CONF_DIR_KEPT ${dirs.confDir}(运行产物:-.conf server 块,nginx 仍在 include,同上)`); console.log(' LOG_KEPT /var/log/warehouse-cert-sync.log(默认保留作排查线索)'); console.log(` UPSTREAM_KEPT ${deployRoot}/nginx-upstream.conf(非本工具文件,不删)`); console.log(` WATCHDOG_KEPT ${deployRoot}/script/qimen-watchdog.*、/etc/cron.d/qimen-watchdog(看门狗相关,不属于 cert-sync 工具)`); if (dryRun) { console.log(`[UNINSTALL] dry-run 结束(未做任何变更)。实际执行时备份目录:${backupDir}`); console.log('如需回滚(实际执行后):把备份目录里的文件 cp -a 回原路径并重跑 install'); return; } console.log(`备份目录:${backupDir}`); console.log('如需回滚:把备份目录里的文件 cp -a 回原路径并重跑 install'); if (lines.some(line => line === 'HAD_ERRORS=1')) { console.error('[UNINSTALL] 存在失败项(见上),可从备份目录恢复'); process.exitCode = 1; } } /** * 卸载 cert-sync 工具自身:先备份再删除(包装脚本 / 主脚本 / 双环境配置 / * database/config.js / 历史位置与 .prev-* / .legacy-* 备份 / crontab 行)。 * 证书、nginx server 块、日志、watchdog 相关一律不删(原因见输出)。 * --dry-run 时只打印计划,不备份、不删除、不改 crontab。 * @param {Object} config deploy 配置对象。 * @param {Object} options 命令选项(dryRun)。 */ function runUninstall(config, options) { const backupDir = `/tmp/wms-cert-sync-uninstall-${getNowStamp()}/`; const dirs = resolveServerDirs(config); const remoteScript = options.dryRun ? buildUninstallDryRunScript(config, backupDir) : buildUninstallScript(config, backupDir); if (options.dryRun) { console.log('[UNINSTALL] dry-run(只读:只打印计划,不备份、不删除、不改 crontab)'); } else { console.log('[UNINSTALL] 开始卸载(先备份再删除)'); } const output = String(runSsh(config, remoteScript, { stdio: 'pipe' }) || ''); printUninstallReport(output, options.dryRun, backupDir, dirs, config.deployRoot); } /** * 入口:解析命令行参数并执行 install / uninstall。 */ function main() { const options = parseArgs(process.argv.slice(2)); const config = loadDeployConfig(options.envName); if (options.command === 'install') { runInstall(config); return; } if (options.command === 'uninstall') { runUninstall(config, options); return; } throw new Error(`unsupported command: ${options.command}`); } main();