packServer/backend/scripts/deploy/rollback-remote.cjs
liufumingren 228723e0c3 设备端扫码上报 + 桌面端/Android 正式包发布脚手架
AndroidStation(原中控改造为纯设备端)
- 只做三件事:UDP 48899 被桌面端发现、TCP 8087 推送 USB 扫码结果、离线语音播报
- 扫码不再经过 UI:去掉逐键重绘,50ms 自动提交,同一码重复扫码也一律上报
- 离线语音种子(数字/字母/“开始打包”/欢迎语)随包安装,MediaPlayer 播放,启动把音量拉满
- 启动播报「欢迎使用溯源系统,初始化已经完成,扫码即可开始打包」
- 移除 Device Owner / 设备管理员 / lock task / 网络与 IP 设置等非普通应用能力(仅保留开机自启)
- 正式签名 keystore + release 签名配置,versionName/versionCode 可由打包脚本覆盖

发布脚手架
- backend/android_client:Android 正式包构建(build.ps1 + package.config.json)
- backend/scripts/deploy/publish-android.cjs + npm run android:build / android:publish
- 桌面端安装包改为 download/desktop,Android 为 download/android_client;
  version.json 仍走 /download/version.json(老客户端写死),新增 /download/android_client/version.json
- 谷歌插件随桌面端 MSI 安装到 <安装目录>\extension,工具菜单新增「复制谷歌插件地址」
- git-safety-check 增加仓库级禁区(keystore.properties / *.jks / local.properties)

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
2026-10-21 05:53:27 +08:00

405 lines
14 KiB
JavaScript
Raw Permalink 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 {
buildHealthCheckScript,
buildKillPortScript,
buildNginxSwitchScript,
buildPinnedPathGuardLines,
buildRemoteCleanupGuard,
buildRemoteJsonWriteLines,
buildStartScript,
buildStopDirScript,
ensureCommandAvailable,
getRemoteEnvFile,
loadDeployConfig,
quoteForBash,
runSsh,
} = require('./deploy-lib.cjs');
const { recordVersionUpdate } = require('./version-registry.cjs');
function readRemoteCurrentVersion(config) {
const currentMdPath = `${config.deployRoot}/current.md`;
const output = runSsh(config, `cat ${quoteForBash(currentMdPath)} 2>/dev/null || true`, { stdio: 'pipe' });
const rawVersion = String(output || '').trim();
if (!rawVersion) {
throw new Error(`无法读取远端当前版本文件: ${currentMdPath}。`);
}
const normalized = rawVersion.replace(/\r/g, '').trim();
if (normalized !== 'v1' && normalized !== 'v2') {
throw new Error(`远端 current.md 内容无效: "${rawVersion}",期望值为 v1 或 v2。`);
}
return normalized;
}
function otherVersion(version) {
return version === 'v1' ? 'v2' : 'v1';
}
function parseBackupArg(argv) {
const backupArg = argv.find(item => item.startsWith('--backup='));
if (!backupArg) {
return '';
}
return backupArg.slice('--backup='.length).trim();
}
/**
* 读取目标版本的 package.json 版本号与历史发布记录(用于回退后保留 releaseVersion 等信息)
*
* @param {object} config - 部署配置
* @param {string} version - 版本标识 v1 / v2
* @param {string} dir - 版本目录
* @return {object} 可合并进发布状态的字段
*/
function readReleaseContext(config, version, dir) {
const script = [
'set -euo pipefail',
`PKG=${quoteForBash(`${dir}/package.json`)}`,
`HIST=${quoteForBash(`${config.stateDir}/release-history.jsonl`)}`,
'echo "__PKG__"',
'if [ -f "$PKG" ]; then node -e "console.log(require(process.argv[1]).version)" "$PKG" 2>/dev/null || true; fi',
'echo "__HIST__"',
'if [ -f "$HIST" ]; then tail -n 50 "$HIST"; fi',
].join('\n');
try {
const output = runSsh(config, script, { stdio: 'pipe' });
const [ pkgPart, histPart ] = output.split('__HIST__');
const packageVersion = String(pkgPart || '').replace('__PKG__', '').trim();
const entries = String(histPart || '')
.split(/\r?\n/)
.map(line => line.trim())
.filter(Boolean)
.map(line => {
try {
return JSON.parse(line);
} catch (error) {
return null;
}
})
.filter(entry => entry && entry.activeVersion === version);
const context = entries.reduce((acc, entry) => ({ ...acc, ...entry }), {});
return { ...context, packageVersion: packageVersion || context.packageVersion || '' };
} catch (error) {
return {};
}
}
function writeRemoteState(config, record) {
runSsh(config, [
'set -euo pipefail',
`STATE_DIR=${quoteForBash(config.stateDir)}`,
'mkdir -p "$STATE_DIR"',
...buildRemoteJsonWriteLines(config.stateDir, 'current-release.json', record, false),
...buildRemoteJsonWriteLines(config.stateDir, 'release-history.jsonl', record, true),
].join('\n'), { stdio: 'pipe' });
}
function recordLocally(config, note) {
try {
recordVersionUpdate({ source: 'rollback', note, deployRoot: config.deployRoot });
} catch (err) {
console.warn(`[WARN] 本地版本记录失败: ${err.message}`);
}
}
/** 蓝绿回退:切回另一个版本目录(上一个发布版本) */
function rollbackBySwitch(config, currentVersion) {
const targetVersion = otherVersion(currentVersion);
const targetDir = `${config.deployRoot}/${targetVersion}`;
const targetPort = config.ports[targetVersion];
const startLogPath = `/tmp/pack-service-${targetVersion}-rollback.log`;
const currentMdPath = `${config.deployRoot}/current.md`;
const exists = runSsh(config, [
'set -euo pipefail',
`if [ -f ${quoteForBash(`${targetDir}/package.json`)} ]; then echo TARGET_OK; else echo TARGET_MISSING; fi`,
].join('\n'), { stdio: 'pipe' }).trim();
if (exists !== 'TARGET_OK') {
throw new Error(
`上一个版本目录不可用: ${targetDir}。如需用备份包回退,请执行: npm run rollback -- --backup=backup-<时间戳>.tar.gz`
);
}
console.log(`蓝绿回退: ${currentVersion} -> ${targetVersion}(${targetDir},端口 ${targetPort})`);
runSsh(config, [
'set -euo pipefail',
`TARGET_DIR=${quoteForBash(targetDir)}`,
`SHARED_CONFIG_DIR=${quoteForBash(config.sharedConfigDir)}`,
'if [ -n "$SHARED_CONFIG_DIR" ] && [ -d "$SHARED_CONFIG_DIR" ]; then',
' for FILE_NAME in config.prod.js config.local.js; do',
' if [ -f "$SHARED_CONFIG_DIR/$FILE_NAME" ]; then',
' mkdir -p "$TARGET_DIR/config"',
' cp -a "$SHARED_CONFIG_DIR/$FILE_NAME" "$TARGET_DIR/config/$FILE_NAME"',
' fi',
' done',
'fi',
].join('\n'), { stdio: 'pipe' });
try {
const killPortOutput = runSsh(config, buildKillPortScript(targetPort), { stdio: 'pipe' });
console.log(String(killPortOutput || '').trim());
} catch (err) {
console.warn(`[WARN] 端口 ${targetPort} 清理失败: ${err.message}`);
}
runSsh(config, buildStartScript({
dir: targetDir,
port: targetPort,
envFile: getRemoteEnvFile(config),
logPath: startLogPath,
}), { stdio: 'pipe' });
try {
const healthOutput = runSsh(config, buildHealthCheckScript({
port: targetPort,
healthPath: config.healthCheckPath,
attempts: config.healthCheckAttempts,
interval: config.healthCheckInterval,
}), { stdio: 'pipe' });
console.log(String(healthOutput || '').trim());
} catch (err) {
console.error(`[ERROR] 回退目标实例健康检查失败: ${err.message}`);
try {
runSsh(config, buildStopDirScript(targetDir, `回退目标 (${targetVersion})`), { stdio: 'pipe' });
} catch (killErr) {
console.error(`[ERROR] 清理回退目标失败: ${killErr.message}`);
}
console.error(`[ERROR] current.md 未修改,旧实例 (${currentVersion}) 仍在提供服务`);
process.exit(1);
}
const switchOutput = runSsh(config, [
'set -euo pipefail',
`printf '%s\\n' ${quoteForBash(targetVersion)} > ${quoteForBash(currentMdPath)}`,
`echo "已更新 current.md -> ${targetVersion}"`,
].join('\n'), { stdio: 'pipe' });
console.log(String(switchOutput || '').trim());
try {
rollbackFrontend(config);
} catch (err) {
console.warn(`[WARN] 前端回退失败: ${err.message}`);
}
let nginxSwitched = true;
if (config.nginxUpstreamFile) {
try {
const nginxOutput = runSsh(config, buildNginxSwitchScript(config.nginxUpstreamFile, targetPort), { stdio: 'pipe' });
console.log(String(nginxOutput || '').trim());
} catch (err) {
nginxSwitched = false;
console.warn(`[WARN] Nginx upstream 切换失败: ${err.message}`);
console.warn(`[WARN] 为保留线上服务,暂不停止原实例 (${currentVersion});请修复 Nginx 后执行 nginx -t && nginx -s reload`);
}
}
if (!nginxSwitched) {
console.warn(`[WARN] 当前同时运行 ${currentVersion} / ${targetVersion},确认 Nginx 指到 ${targetPort} 后再停旧实例`);
} else {
try {
const stopOutput = runSsh(config, buildStopDirScript(
`${config.deployRoot}/${currentVersion}`,
`原实例 (${currentVersion})`
), { stdio: 'pipe' });
console.log(String(stopOutput || '').trim());
} catch (err) {
console.warn(`[WARN] 停止原实例失败: ${err.message}`);
}
}
const record = {
...readReleaseContext(config, targetVersion, targetDir),
rolledBackAt: new Date().toISOString(),
source: 'rollback',
activeVersion: targetVersion,
port: targetPort,
dir: targetDir,
previousVersion: currentVersion,
rolledBackBy: process.env.USERNAME || process.env.USER || '',
};
try {
writeRemoteState(config, record);
} catch (err) {
console.warn(`[WARN] 远端回退状态记录失败: ${err.message}`);
}
recordLocally(config, `rollback ${currentVersion} -> ${targetVersion}`);
console.log(`回退完成:当前活跃版本 ${targetVersion}(端口 ${targetPort})`);
}
/** 备份包回退:把指定备份解压回当前活跃目录并重启 */
function rollbackByBackup(config, currentVersion, currentPort, backupName) {
const currentDir = `${config.deployRoot}/${currentVersion}`;
const startLogPath = `/tmp/pack-service-${currentVersion}-rollback.log`;
const latestBackupFile = `${config.stateDir}/latest-backup.txt`;
const selectBackupScript = [
'set -euo pipefail',
`BACKUP_DIR=${quoteForBash(config.backupDir)}`,
`LATEST_BACKUP_FILE=${quoteForBash(latestBackupFile)}`,
`REQUESTED_BACKUP=${quoteForBash(backupName)}`,
'if [ -n "$REQUESTED_BACKUP" ]; then',
' TARGET_BACKUP="$REQUESTED_BACKUP"',
'elif [ -f "$LATEST_BACKUP_FILE" ]; then',
' TARGET_BACKUP="$(cat "$LATEST_BACKUP_FILE")"',
'else',
' echo "ERROR: 未找到最近一次发布备份,请通过 --backup=backup-时间戳.tar.gz 指定回退包。" >&2',
' exit 1',
'fi',
'if [ ! -f "$BACKUP_DIR/$TARGET_BACKUP" ]; then',
' echo "ERROR: 回退包不存在: $BACKUP_DIR/$TARGET_BACKUP" >&2',
' exit 1',
'fi',
'echo "$TARGET_BACKUP"',
].join('\n');
const targetBackup = runSsh(config, selectBackupScript, { stdio: 'pipe' }).trim();
console.log(`备份包回退: ${targetBackup} -> ${currentDir}`);
try {
const stopOutput = runSsh(config, buildStopDirScript(currentDir, `当前实例 (${currentVersion})`), { stdio: 'pipe' });
console.log(String(stopOutput || '').trim());
} catch (err) {
console.warn(`[WARN] 停止当前实例失败: ${err.message}`);
}
const pinnedStashDir = `/tmp/pack-service-pinned-rollback-${currentVersion}`;
const pinnedGuard = buildPinnedPathGuardLines('CURRENT_DIR', 'PINNED_DIR', config.preservePaths);
const cleanupGuard = buildRemoteCleanupGuard(config.sharedDirs);
runSsh(config, [
'set -euo pipefail',
`CURRENT_DIR=${quoteForBash(currentDir)}`,
`BACKUP_DIR=${quoteForBash(config.backupDir)}`,
`TARGET_BACKUP=${quoteForBash(targetBackup)}`,
`PINNED_DIR=${quoteForBash(pinnedStashDir)}`,
`SHARED_CONFIG_DIR=${quoteForBash(config.sharedConfigDir)}`,
...pinnedGuard.stash,
'cd "$CURRENT_DIR"',
`find . -mindepth 1 -maxdepth 1 ${cleanupGuard} -exec rm -rf {} +`,
'echo "旧代码已清理完成"',
'tar -xzf "$BACKUP_DIR/$TARGET_BACKUP" -C "$CURRENT_DIR"',
'echo "备份包已解压到 $CURRENT_DIR"',
...pinnedGuard.restore,
'if [ -n "$SHARED_CONFIG_DIR" ] && [ -d "$SHARED_CONFIG_DIR" ]; then',
' for FILE_NAME in config.prod.js config.local.js; do',
' if [ -f "$SHARED_CONFIG_DIR/$FILE_NAME" ]; then',
' mkdir -p "$CURRENT_DIR/config"',
' cp -a "$SHARED_CONFIG_DIR/$FILE_NAME" "$CURRENT_DIR/config/$FILE_NAME"',
' echo "SHARED_CONFIG_APPLIED $FILE_NAME"',
' fi',
' done',
'fi',
'mkdir -p "$CURRENT_DIR/app/public/download" "$CURRENT_DIR/app/public/version"',
'mkdir -p "$CURRENT_DIR/logs" "$CURRENT_DIR/run" "$CURRENT_DIR/temp"',
'npm install --production',
'echo "生产依赖安装完成"',
].join('\n'));
runSsh(config, buildStartScript({
dir: currentDir,
port: currentPort,
envFile: getRemoteEnvFile(config),
logPath: startLogPath,
}), { stdio: 'pipe' });
try {
const healthOutput = runSsh(config, buildHealthCheckScript({
port: currentPort,
healthPath: config.healthCheckPath,
attempts: config.healthCheckAttempts,
interval: config.healthCheckInterval,
}), { stdio: 'pipe' });
console.log(String(healthOutput || '').trim());
} catch (err) {
console.error(`[ERROR] 备份包回退后健康检查失败: ${err.message}`);
console.error(`[ERROR] 请检查启动日志: ${startLogPath}`);
process.exit(1);
}
if (config.nginxUpstreamFile) {
try {
const nginxOutput = runSsh(config, buildNginxSwitchScript(config.nginxUpstreamFile, currentPort), { stdio: 'pipe' });
console.log(String(nginxOutput || '').trim());
} catch (err) {
console.warn(`[WARN] Nginx upstream 切换失败: ${err.message}`);
}
}
const record = {
...readReleaseContext(config, currentVersion, currentDir),
rolledBackAt: new Date().toISOString(),
source: 'rollback-backup',
activeVersion: currentVersion,
port: currentPort,
dir: currentDir,
backup: targetBackup,
rolledBackBy: process.env.USERNAME || process.env.USER || '',
};
try {
writeRemoteState(config, record);
} catch (err) {
console.warn(`[WARN] 远端回退状态记录失败: ${err.message}`);
}
recordLocally(config, `rollback-backup ${targetBackup}`);
console.log(`回退完成:${currentVersion} 已恢复为备份包 ${targetBackup} 的内容`);
}
/** 回退前端静态目录:frontend ↔ frontend.prev 互换 */
function rollbackFrontend(config) {
if (!config.buildFrontend) {
return;
}
runSsh(config, [
'set -euo pipefail',
`FRONTEND_DIR=${quoteForBash(config.frontendDeployDir)}`,
`PREV_DIR=${quoteForBash(config.frontendPrevDir)}`,
'if [ -d "$PREV_DIR" ]; then',
' TMP_DIR="${FRONTEND_DIR}.rollback-$$"',
' rm -rf "$TMP_DIR"',
' if [ -d "$FRONTEND_DIR" ]; then mv "$FRONTEND_DIR" "$TMP_DIR"; fi',
' mv "$PREV_DIR" "$FRONTEND_DIR"',
' if [ -d "$TMP_DIR" ]; then mv "$TMP_DIR" "$PREV_DIR"; fi',
' find "$FRONTEND_DIR" -type d -exec chmod 755 {} +',
' find "$FRONTEND_DIR" -type f -exec chmod 644 {} +',
' echo "FRONTEND_ROLLED_BACK $FRONTEND_DIR"',
'else',
' echo "FRONTEND_PREV_MISSING 跳过前端回退"',
'fi',
].join('\n'), { stdio: 'pipe' });
}
function main() {
const envName = process.argv[2] || 'production';
const config = loadDeployConfig(envName);
const backupName = parseBackupArg(process.argv.slice(3));
ensureCommandAvailable('ssh', '请先安装 OpenSSH Client 并确保 ssh 在 PATH 中。');
const currentVersion = readRemoteCurrentVersion(config);
const currentPort = config.ports[currentVersion];
console.log(`远端当前活跃版本: ${currentVersion}(端口 ${currentPort})`);
if (backupName) {
rollbackByBackup(config, currentVersion, currentPort, backupName);
return;
}
rollbackBySwitch(config, currentVersion);
}
try {
main();
} catch (err) {
console.error(`[ERROR] ${err && err.message ? err.message : err}`);
process.exit(1);
}