- 发布/回退链路新增固定文件排除与保护:warehouse-cert-sync 两份环境配置不进发布包、清理时暂存/放回,服务器副本不被覆盖/删除(deploy-lib 独立常量 + 共用守卫函数) - deploy-cert-sync 新增 config-check 只读核对;install 对 prod 配置首次放置一次、之后永不覆盖;dev 配置永不上传生产 - 薄包装简化:nginx 二进制/upstream/reload 全部收敛到 prod 配置,包装仅保留 cwd+依赖+DB 运行时引导 - 新增 warehouse-cert-sync.cjs 与 dev/prod 双环境配置;package.json 增加 deploy:cert-sync:config-check
432 lines
20 KiB
JavaScript
432 lines
20 KiB
JavaScript
'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([ 'precheck', 'install', 'dry-run', 'run', 'status', 'config-check' ]);
|
||
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');
|
||
|
||
function parseArgs(argv) {
|
||
const options = { envName: 'production', command: '' };
|
||
const tokens = [ ...argv ];
|
||
if (tokens.length === 0) {
|
||
throw new Error('missing command: precheck | install | dry-run | run | status | config-check');
|
||
}
|
||
if (!COMMANDS.has(tokens[0])) {
|
||
options.envName = tokens[0];
|
||
tokens.shift();
|
||
}
|
||
if (tokens.length === 0 || !COMMANDS.has(tokens[0])) {
|
||
throw new Error('missing command: precheck | install | dry-run | run | status | config-check');
|
||
}
|
||
options.command = tokens[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
|
||
`;
|
||
}
|
||
|
||
/** Read-only DB probe JS (never prints credentials). */
|
||
const DB_PROBE_JS = `
|
||
const path = require("node:path");
|
||
const Sequelize = require("sequelize");
|
||
const appDir = process.argv[1];
|
||
function load(p) {
|
||
try {
|
||
const f = require(p);
|
||
const c = typeof f === "function" ? f({ name: "cert-sync-precheck", 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.log("[DB_PROBE] cannot resolve db config from active instance"); process.exit(0); }
|
||
console.log("[DB_PROBE] config source: " + src + " database=" + String(client.database || ""));
|
||
const seq = new Sequelize(client.database, client.username || client.user, client.password, {
|
||
host: client.host, port: client.port || 3306, dialect: "mysql", logging: false,
|
||
});
|
||
(async () => {
|
||
try {
|
||
await seq.authenticate();
|
||
console.log("[DB_PROBE] prod db connect OK");
|
||
const [t] = await seq.query("SELECT COUNT(*) AS c FROM information_schema.tables WHERE table_schema = DATABASE() AND table_name = 'wms_warehouse_front_config'");
|
||
const exists = Number(t[0].c) > 0;
|
||
console.log("[DB_PROBE] wms_warehouse_front_config exists: " + (exists ? "YES" : "NO"));
|
||
if (exists) {
|
||
const [cols] = await seq.query("SELECT column_name AS cn FROM information_schema.columns WHERE table_schema = DATABASE() AND table_name = 'wms_warehouse_front_config'");
|
||
console.log("[DB_PROBE] columns: " + cols.map(r => r.cn).join(","));
|
||
const [total] = await seq.query("SELECT COUNT(*) AS c FROM wms_warehouse_front_config");
|
||
console.log("[DB_PROBE] total rows: " + total[0].c);
|
||
const [dist] = await seq.query("SELECT sync_status AS s, COUNT(*) AS c FROM wms_warehouse_front_config GROUP BY sync_status ORDER BY sync_status");
|
||
console.log("[DB_PROBE] sync_status distribution: " + (dist.length ? dist.map(r => r.s + "=" + r.c).join(" ") : "(empty)"));
|
||
}
|
||
} catch (e) {
|
||
console.log("[DB_PROBE] failed: " + e.message);
|
||
}
|
||
await seq.close();
|
||
})();
|
||
`;
|
||
|
||
/** Read-only remote precheck. */
|
||
function runPrecheck(config) {
|
||
const deployRoot = config.deployRoot;
|
||
const remoteScript = [
|
||
'set -uo pipefail',
|
||
`DEPLOY_ROOT=${quoteForBash(deployRoot)}`,
|
||
'echo "[WHOAMI] $(id -un)"',
|
||
'echo "[UNAME] $(uname -a)"',
|
||
`echo "[CURRENT_MD] $(cat ${quoteForBash(`${deployRoot}/current.md`)} 2>/dev/null || echo MISSING)"`,
|
||
`echo "[DEPLOY_ROOT_LS]"; ls -la ${quoteForBash(deployRoot)} | awk '{print $1, $3, $4, $9}'`,
|
||
'echo "[NGINX_BIN]"; command -v nginx || echo "nginx not in PATH"',
|
||
'echo "[NGINX_V]"; nginx -v 2>&1 || true',
|
||
'echo "[NGINX_V_PREFIX]"; nginx -V 2>&1 | grep -E "configure arguments|--prefix" | head -2 || true',
|
||
'echo "[NGINX_T_NOW]"; nginx -t 2>&1 || true',
|
||
'echo "[NGINX_PROCESS]"; ps -eo pid=,args= | grep "[n]ginx" | head -6 || true',
|
||
'echo "[SYSTEMD_NGINX]"; systemctl is-active nginx 2>&1 || true; systemctl is-enabled nginx 2>&1 || true',
|
||
'echo "[FLOCK]"; command -v flock || echo "flock missing"',
|
||
'echo "[MAIN_CONF_INCLUDES]"; for f in /etc/nginx/nginx.conf /www/server/nginx/conf/nginx.conf /usr/local/nginx/conf/nginx.conf; do if [ -f "$f" ]; then echo "-- $f"; grep -n "include" "$f" | grep -v "^[[:space:]]*#" | head -20; fi; done',
|
||
'echo "[CONF_DIR_PROBE]"; for d in /etc/nginx/conf.d /www/server/nginx/conf/conf.d; do if [ -d "$d" ]; then echo "-- $d EXISTS"; ls -1 "$d" | head -20; fi; done',
|
||
'echo "[SSL_DIR] /www/wwwroot/.ssl"; if [ -d /www/wwwroot/.ssl ]; then echo EXISTS; ls -la /www/wwwroot/.ssl | head -20; else echo MISSING; fi',
|
||
'echo "[CERT_CONF_DIR] /www/wwwroot/nginx_config"; if [ -d /www/wwwroot/nginx_config ]; then echo EXISTS; ls -la /www/wwwroot/nginx_config | head -30; else echo MISSING; fi',
|
||
'echo "[PARENT_WRITABLE]"; if [ -w /www/wwwroot ]; then echo YES; else echo NO; fi',
|
||
'echo "[DEPLOY_ROOT_META]"; for p in script database config node_modules; do if [ -e "$DEPLOY_ROOT/$p" ]; then echo "$p EXISTS"; else echo "$p MISSING"; fi; done',
|
||
'echo "[V1_CONFIG_LS]"; ls -la "$DEPLOY_ROOT/v1/config" 2>/dev/null | head -20 || echo "v1/config missing"',
|
||
'echo "[V2_CONFIG_LS]"; ls -la "$DEPLOY_ROOT/v2/config" 2>/dev/null | head -20 || echo "v2/config missing"',
|
||
'echo "[V1_SEQUELIZE]"; if [ -d "$DEPLOY_ROOT/v1/node_modules/sequelize" ]; then echo YES; else echo NO; fi',
|
||
'echo "[V2_SEQUELIZE]"; if [ -d "$DEPLOY_ROOT/v2/node_modules/sequelize" ]; then echo YES; else echo NO; fi',
|
||
'echo "[EXISTING_CRON_CERT]"; crontab -l 2>/dev/null | grep -i "cert" || echo NONE',
|
||
'echo "[CRON_LINE_COUNT]"; crontab -l 2>/dev/null | grep -cv "^#" || echo 0',
|
||
'echo "[CERT_LOG_TAIL]"; tail -20 /var/log/warehouse-cert-sync.log 2>/dev/null || echo "log not exists"',
|
||
].join('\n');
|
||
|
||
console.log('[PRECHECK] remote env check (read-only)');
|
||
console.log(runSsh(config, remoteScript, { stdio: 'pipe' }).trim());
|
||
|
||
const dbProbeScript = [
|
||
'set -uo pipefail',
|
||
`DEPLOY_ROOT=${quoteForBash(deployRoot)}`,
|
||
'ACTIVE=$(cat "$DEPLOY_ROOT/current.md" 2>/dev/null | tr -d "[:space:]" || true)',
|
||
'APP_DIR=""',
|
||
'if [ -n "$ACTIVE" ] && [ -d "$DEPLOY_ROOT/$ACTIVE/config" ]; then APP_DIR="$DEPLOY_ROOT/$ACTIVE"; fi',
|
||
'if [ -z "$APP_DIR" ]; then for CAND in v1 v2; do if [ -d "$DEPLOY_ROOT/$CAND/config" ]; then APP_DIR="$DEPLOY_ROOT/$CAND"; break; fi; done; fi',
|
||
'if [ -z "$APP_DIR" ]; then echo "[DB_PROBE] no active instance dir found"; exit 0; fi',
|
||
'export NODE_PATH="$APP_DIR/node_modules"',
|
||
`node -e ${quoteForBash(DB_PROBE_JS)} "$APP_DIR"`,
|
||
].join('\n');
|
||
|
||
console.log('');
|
||
console.log('[PRECHECK] prod db probe (read-only, no credentials printed)');
|
||
console.log(runSsh(config, dbProbeScript, { stdio: 'pipe' }).trim());
|
||
}
|
||
|
||
/** Install: upload files, create thin shell wrapper, register root crontab. */
|
||
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/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',
|
||
].join('\n');
|
||
console.log('[INSTALL] remote dir prep + backup of existing files');
|
||
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}/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());
|
||
}
|
||
|
||
/** Run the remote wrapper with optional extra args; returns output + exit code. */
|
||
function runRemoteWrapper(config, extraArgs = []) {
|
||
const wrapperPath = `${config.deployRoot}/warehouse-cert-sync.sh`;
|
||
const remoteScript = [
|
||
'set -uo pipefail',
|
||
`WRAPPER=${quoteForBash(wrapperPath)}`,
|
||
`ARGS=${quoteForBash(extraArgs.join(' '))}`,
|
||
'if [ ! -f "$WRAPPER" ]; then echo "FATAL: wrapper missing: $WRAPPER"; exit 1; fi',
|
||
'bash "$WRAPPER" $ARGS',
|
||
'echo "CERT_SYNC_EXIT=$?"',
|
||
].join('\n');
|
||
return runSsh(config, remoteScript, { stdio: 'pipe' }).trim();
|
||
}
|
||
|
||
/** Status: crontab line, remote file list, log tail. */
|
||
function runStatus(config) {
|
||
const deployRoot = config.deployRoot;
|
||
const remoteScript = [
|
||
'set -uo pipefail',
|
||
'echo "[CRONTAB_CERT_LINES]"',
|
||
'crontab -l 2>/dev/null | grep -n "warehouse-cert-sync" || echo NONE',
|
||
'echo "[REMOTE_FILES]"',
|
||
`ls -la ${quoteForBash(`${deployRoot}/warehouse-cert-sync.sh`)} ${quoteForBash(`${deployRoot}/script/warehouse-cert-sync.cjs`)} ${quoteForBash(`${deployRoot}/script/warehouse-cert-sync.config.prod.json`)} ${quoteForBash(`${deployRoot}/script/warehouse-cert-sync.config.dev.json`)} ${quoteForBash(`${deployRoot}/database/config.js`)} 2>&1`,
|
||
'echo "[WRAPPER_HEAD]"',
|
||
`head -12 ${quoteForBash(`${deployRoot}/warehouse-cert-sync.sh`)} 2>/dev/null`,
|
||
'echo "[CERT_LOG_TAIL]"',
|
||
'tail -30 /var/log/warehouse-cert-sync.log 2>/dev/null || echo "log not exists"',
|
||
].join('\n');
|
||
console.log(runSsh(config, remoteScript, { stdio: 'pipe' }).trim());
|
||
}
|
||
|
||
/** 只读核对服务器 prod 配置文件:存在性 + JSON 合法性 + 内容展示(无凭据,可安全输出)。 */
|
||
function runConfigCheck(config) {
|
||
const deployRoot = config.deployRoot;
|
||
const remoteScript = [
|
||
'set -uo pipefail',
|
||
`DEPLOY_ROOT=${quoteForBash(deployRoot)}`,
|
||
'PROD="$DEPLOY_ROOT/script/warehouse-cert-sync.config.prod.json"',
|
||
'DEV="$DEPLOY_ROOT/script/warehouse-cert-sync.config.dev.json"',
|
||
'for f in "$PROD" "$DEV"; do',
|
||
' if [ -f "$f" ]; then',
|
||
' echo "[CONFIG_EXISTS] $f"',
|
||
' if node -e \'JSON.parse(require("node:fs").readFileSync(process.argv[1], "utf8"))\' "$f" >/dev/null 2>&1; then',
|
||
' echo "[CONFIG_JSON] $f VALID"',
|
||
' else',
|
||
' echo "[CONFIG_JSON] $f INVALID"',
|
||
' fi',
|
||
' else',
|
||
' echo "[CONFIG_MISSING] $f"',
|
||
' fi',
|
||
'done',
|
||
'echo "[PROD_CONFIG_CONTENT]"',
|
||
'cat "$PROD" 2>/dev/null || echo "(missing)"',
|
||
'echo "[DEV_CONFIG_ON_SERVER]"',
|
||
'if [ -f "$DEV" ]; then echo YES; else echo NO; fi',
|
||
].join('\n');
|
||
console.log(runSsh(config, remoteScript, { stdio: 'pipe' }).trim());
|
||
}
|
||
|
||
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 === 'dry-run') {
|
||
console.log('[DRY-RUN] remote dry-run (read-only, no file writes, no db updates)');
|
||
console.log(runRemoteWrapper(config, [ '--dry-run' ]));
|
||
return;
|
||
}
|
||
if (options.command === 'run') {
|
||
console.log('[RUN] remote real execution');
|
||
console.log(runRemoteWrapper(config, []));
|
||
return;
|
||
}
|
||
if (options.command === 'status') {
|
||
runStatus(config);
|
||
return;
|
||
}
|
||
if (options.command === 'config-check') {
|
||
runConfigCheck(config);
|
||
return;
|
||
}
|
||
throw new Error(`unsupported command: ${options.command}`);
|
||
}
|
||
|
||
main();
|