diff --git a/.githooks/pre-commit b/.githooks/pre-commit new file mode 100644 index 0000000..6dacb0e --- /dev/null +++ b/.githooks/pre-commit @@ -0,0 +1,2 @@ +#!/bin/sh +node script/git-safety-check.cjs diff --git a/.gitignore b/.gitignore index 652759b..2f1d84b 100644 --- a/.gitignore +++ b/.gitignore @@ -13,3 +13,7 @@ run/ *.un~ typings/ .nyc_output/ +tmp/ +versioning/ +config/deploy.config.local.cjs +*.rar diff --git a/config/deploy.config.example.cjs b/config/deploy.config.example.cjs new file mode 100644 index 0000000..623ebb1 --- /dev/null +++ b/config/deploy.config.example.cjs @@ -0,0 +1,26 @@ +# services.printer 部署配置示例 +# 复制此文件为 deploy.config.local.cjs 并填入真实值 +module.exports = { + production: { + host: '__FILL_SSH_HOST__', + port: 22, + username: '__FILL_SSH_USERNAME__', + privateKeyPath: 'C:/Users/your-user/.ssh/id_rsa', + deployRoot: '/www/wwwroot/services.printer', + sharedDirs: [ 'logs', 'run', 'tmp' ], + keepBackups: 5, + preDeployCommands: [ + 'node -v', + 'npm -v', + ], + postDeployCommands: [ + 'npm install --production', + 'npm run stop || true', + 'npm start', + ], + healthCheckUrl: 'http://127.0.0.1:4051/', + sshOptions: [ + 'StrictHostKeyChecking=accept-new', + ], + }, +}; diff --git a/package.json b/package.json index d9670eb..f11db53 100644 --- a/package.json +++ b/package.json @@ -31,7 +31,14 @@ "test:local": "egg-bin test", "cov": "egg-bin cov", "lint": "eslint .", - "ci": "npm run lint && npm run cov" + "ci": "npm run lint && npm run cov", + "deploy": "node script/deploy-remote.cjs", + "deploy:precheck": "node script/deploy-precheck.cjs", + "deploy:version": "node script/deploy-version.cjs", + "deploy:ops": "node script/deploy-ops.cjs", + "deploy:rollback": "node script/rollback-remote.cjs", + "deploy:auth-check": "node script/deploy-auth-check.cjs", + "deploy:setup-hooks": "node script/setup-git-hooks.cjs" }, "repository": { "type": "git", diff --git a/script/deploy-auth-check.cjs b/script/deploy-auth-check.cjs new file mode 100644 index 0000000..c4ca5a9 --- /dev/null +++ b/script/deploy-auth-check.cjs @@ -0,0 +1,42 @@ +'use strict'; + +const { spawnSync } = require('node:child_process'); +const { loadDeployConfig } = require('./deploy-lib.cjs'); + +function main() { + const config = loadDeployConfig('production'); + + const args = [ '-vv' ]; + args.push('-p', String(config.port)); + args.push('-i', config.privateKeyPath); + for (const option of config.sshOptions) { + args.push('-o', option); + } + args.push(`${config.username}@${config.host}`); + args.push('echo AUTH_CHECK_OK'); + + const result = spawnSync('ssh', args, { + encoding: 'utf8', + stdio: 'pipe', + shell: false, + }); + + const text = `${result.stdout || ''}\n${result.stderr || ''}`; + const summary = { + keyOffered: /Offering public key:/i.test(text) || /Will attempt key:/i.test(text), + keyAccepted: /Authenticated to .* using "publickey"/i.test(text) || /AUTH_CHECK_OK/i.test(text), + authFailed: /Permission denied|Authentication failed/i.test(text), + hostKeyFailed: /Host key verification failed|REMOTE HOST IDENTIFICATION HAS CHANGED/i.test(text), + networkFailed: /Connection timed out|No route to host|Connection refused|Could not resolve hostname|Operation timed out/i.test(text), + }; + + console.log(JSON.stringify(summary, null, 2)); + + if (summary.keyAccepted) { + process.exit(0); + } + + process.exit(1); +} + +main(); diff --git a/script/deploy-lib.cjs b/script/deploy-lib.cjs new file mode 100644 index 0000000..a0ddbef --- /dev/null +++ b/script/deploy-lib.cjs @@ -0,0 +1,354 @@ +'use strict'; + +const fs = require('node:fs'); +const path = require('node:path'); +const { spawnSync } = require('node:child_process'); + +const ROOT = path.resolve(__dirname, '..'); +const LOCAL_CONFIG_PATH = path.join(ROOT, 'config', 'deploy.config.local.cjs'); +const EXAMPLE_CONFIG_PATH = path.join(ROOT, 'config', 'deploy.config.example.cjs'); +const DEFAULT_ENV = 'production'; +const DEFAULT_EGG_MINIMAL_INCLUDE_PATHS = [ + 'app.js', + 'app/**', + 'package.json', + 'package-lock.json', +]; +const DEFAULT_POST_DEPLOY_COMMANDS = [ + 'npm install --production', + 'npm run stop || true', + 'npm start', +]; + +function quoteForBash(value) { + return `'${String(value).replace(/'/g, `'"'"'`)}'`; +} + +function isGitAvailable() { + const result = spawnSync('git', [ 'rev-parse', '--git-dir' ], { + cwd: ROOT, + encoding: 'utf8', + stdio: 'pipe', + shell: false, + }); + return result.status === 0; +} + +/** + * 检查是否有未提交的更改 + */ +function hasUncommittedChanges() { + if (!isGitAvailable()) return false; + const output = runCommandSafe('git', [ 'status', '--porcelain' ]); + return output.trim().length > 0; +} + +function runCommand(command, args, options = {}) { + const result = spawnSync(command, args, { + cwd: options.cwd || ROOT, + encoding: 'utf8', + stdio: options.stdio || 'pipe', + shell: false, + }); + + if (result.error) { + throw result.error; + } + + if (result.status !== 0) { + const stderr = (result.stderr || '').trim(); + const stdout = (result.stdout || '').trim(); + throw new Error(stderr || stdout || `${command} exited with code ${result.status}`); + } + + return (result.stdout || '').trim(); +} + +/** + * 安全执行命令,失败时返回空字符串而不是抛出异常 + */ +function runCommandSafe(command, args, options = {}) { + const result = spawnSync(command, args, { + cwd: options.cwd || ROOT, + encoding: 'utf8', + stdio: 'pipe', + shell: false, + }); + + if (result.error || result.status !== 0) { + return ''; + } + + return (result.stdout || '').trim(); +} + +function ensureCommandAvailable(command, installHint) { + const result = spawnSync(command, [], { + cwd: ROOT, + encoding: 'utf8', + stdio: 'pipe', + shell: false, + }); + + if (result.error && result.error.code === 'ENOENT') { + throw new Error(`${command} 不可用。${installHint}`); + } +} + +function getNowStamp() { + const now = new Date(); + const pad = value => String(value).padStart(2, '0'); + return `${now.getFullYear()}${pad(now.getMonth() + 1)}${pad(now.getDate())}${pad(now.getHours())}${pad(now.getMinutes())}${pad(now.getSeconds())}`; +} + +function ensureTempDeployDir() { + const tempDir = path.join(ROOT, 'tmp', 'deploy'); + fs.mkdirSync(tempDir, { recursive: true }); + return tempDir; +} + +function isPlaceholder(value) { + if (!value) { + return true; + } + return String(value).includes('__FILL_'); +} + +function normalizeDeployConfig(config, envName) { + const deployRoot = config.deployRoot || '/www/wwwroot/services.printer'; + const privateKeyPath = config.privateKeyPath ? path.resolve(ROOT, config.privateKeyPath) : ''; + const sshOptions = Array.isArray(config.sshOptions) ? [ ...config.sshOptions ] : []; + const preserveDirs = Array.isArray(config.preserveDirs) ? [ ...config.preserveDirs ] : [ 'config' ]; + + if (!preserveDirs.includes('config')) { + preserveDirs.push('config'); + } + + if (!sshOptions.some(option => /^IdentitiesOnly=/i.test(option))) { + sshOptions.push('IdentitiesOnly=yes'); + } + if (!sshOptions.some(option => /^PreferredAuthentications=/i.test(option))) { + sshOptions.push('PreferredAuthentications=publickey'); + } + if (!sshOptions.some(option => /^PubkeyAuthentication=/i.test(option))) { + sshOptions.push('PubkeyAuthentication=yes'); + } + if (!sshOptions.some(option => /^PasswordAuthentication=/i.test(option))) { + sshOptions.push('PasswordAuthentication=no'); + } + if (!sshOptions.some(option => /^KbdInteractiveAuthentication=/i.test(option))) { + sshOptions.push('KbdInteractiveAuthentication=no'); + } + if (!sshOptions.some(option => /^BatchMode=/i.test(option))) { + sshOptions.push('BatchMode=yes'); + } + if (!sshOptions.some(option => /^ConnectTimeout=/i.test(option))) { + sshOptions.push('ConnectTimeout=10'); + } + + const configuredPostDeployCommands = Array.isArray(config.postDeployCommands) && config.postDeployCommands.length > 0 + ? [ ...config.postDeployCommands ] + : [ ...DEFAULT_POST_DEPLOY_COMMANDS ]; + + if (!configuredPostDeployCommands.some(cmd => /^npm\s+install\s+--production(?:\s|$)/i.test(String(cmd).trim()))) { + configuredPostDeployCommands.unshift('npm install --production'); + } + + return { + envName, + host: config.host, + port: Number(config.port || 22), + username: config.username, + privateKeyPath, + deployRoot, + controlDir: `${deployRoot}/.deploy`, + incomingDir: `${deployRoot}/.deploy/incoming`, + backupDir: `${deployRoot}/.deploy/backups`, + stateDir: `${deployRoot}/.deploy/state`, + sharedDirs: Array.isArray(config.sharedDirs) ? config.sharedDirs : [ 'logs', 'run', 'tmp' ], + preserveDirs, + keepBackups: Number(config.keepBackups || 5), + preDeployCommands: Array.isArray(config.preDeployCommands) ? config.preDeployCommands : [], + postDeployCommands: configuredPostDeployCommands, + healthCheckUrl: config.healthCheckUrl || '', + deployIncludePaths: Array.isArray(config.deployIncludePaths) && config.deployIncludePaths.length > 0 + ? config.deployIncludePaths + : DEFAULT_EGG_MINIMAL_INCLUDE_PATHS, + deployExcludePaths: Array.isArray(config.deployExcludePaths) ? config.deployExcludePaths : [ 'config/**' ], + sshOptions, + }; +} + +function validateDeployConfig(config, configPath, envName) { + if (!config) { + throw new Error(`${configPath} 中未找到 ${envName} 配置。`); + } + + const missing = []; + if (isPlaceholder(config.host)) missing.push('host'); + if (isPlaceholder(config.username)) missing.push('username'); + if (isPlaceholder(config.privateKeyPath)) missing.push('privateKeyPath'); + + if (missing.length > 0) { + throw new Error(`请先完善 SSH 配置字段: ${missing.join(', ')}。配置文件: ${configPath}`); + } + + const resolvedPrivateKeyPath = path.resolve(ROOT, config.privateKeyPath); + if (!fs.existsSync(resolvedPrivateKeyPath)) { + throw new Error(`SSH 私钥不存在: ${resolvedPrivateKeyPath}。请先修正 config/deploy.config.local.cjs 中的 privateKeyPath。`); + } +} + +function loadDeployConfig(envName = DEFAULT_ENV) { + if (!fs.existsSync(LOCAL_CONFIG_PATH)) { + throw new Error(`缺少本地部署配置 ${LOCAL_CONFIG_PATH}。请复制 ${EXAMPLE_CONFIG_PATH} 并填入 SSH 信息。`); + } + + delete require.cache[LOCAL_CONFIG_PATH]; + const loaded = require(LOCAL_CONFIG_PATH); + const config = loaded[envName]; + validateDeployConfig(config, LOCAL_CONFIG_PATH, envName); + return normalizeDeployConfig(config, envName); +} + +function buildSshBaseArgs(config) { + const args = [ '-p', String(config.port), '-i', config.privateKeyPath ]; + for (const option of config.sshOptions) { + args.push('-o', option); + } + return args; +} + +function runSsh(config, remoteScript, options = {}) { + const args = [ + ...buildSshBaseArgs(config), + `${config.username}@${config.host}`, + `bash -lc ${quoteForBash(remoteScript)}`, + ]; + + return runCommand('ssh', args, { + stdio: options.stdio || 'inherit', + }); +} + +function runScp(config, localPath, remotePath) { + const args = [ '-P', String(config.port), '-i', config.privateKeyPath ]; + for (const option of config.sshOptions) { + args.push('-o', option); + } + + args.push( + localPath, + `${config.username}@${config.host}:${remotePath}`, + ); + + return runCommand('scp', args, { stdio: 'inherit' }); +} + +function normalizeRule(rule) { + return String(rule || '').replace(/\\/g, '/').trim(); +} + +function pathMatchesRule(filePath, rule) { + const normalizedPath = String(filePath || '').replace(/\\/g, '/'); + const normalizedRule = normalizeRule(rule); + + if (!normalizedRule) { + return false; + } + if (normalizedRule.endsWith('/**')) { + const prefix = normalizedRule.slice(0, -3); + return normalizedPath === prefix || normalizedPath.startsWith(`${prefix}/`); + } + if (normalizedRule.endsWith('/')) { + return normalizedPath.startsWith(normalizedRule); + } + return normalizedPath === normalizedRule; +} + +/** + * 递归遍历目录获取所有文件(非 git 模式回退方案) + */ +function walkDir(dir, basePath) { + const results = []; + const entries = fs.readdirSync(dir, { withFileTypes: true }); + for (const entry of entries) { + const fullPath = path.join(dir, entry.name); + const relativePath = path.relative(basePath, fullPath).replace(/\\/g, '/'); + + if (entry.isDirectory()) { + const skipDirs = [ '.git', 'node_modules', 'logs', 'run', 'tmp', '.deploy', '.vscode', '.idea' ]; + if (skipDirs.includes(entry.name)) continue; + results.push(...walkDir(fullPath, basePath)); + } else { + results.push(relativePath); + } + } + return results; +} + +function listDeployableFiles(config) { + const includeRules = Array.isArray(config && config.deployIncludePaths) ? config.deployIncludePaths : DEFAULT_EGG_MINIMAL_INCLUDE_PATHS; + const excludeRules = Array.isArray(config && config.deployExcludePaths) ? config.deployExcludePaths : [ 'config/**' ]; + + let allFiles; + + if (isGitAvailable()) { + const output = runCommandSafe('git', [ 'ls-files', '--cached', '--others', '--exclude-standard' ]); + allFiles = output + .split(/\r?\n/) + .map(item => item.trim()) + .filter(Boolean) + .filter(item => !item.startsWith('.git/')) + .filter(item => fs.existsSync(path.join(ROOT, item))); + } else { + console.warn('[WARN] 未检测到 Git 仓库,使用文件系统遍历模式。建议初始化 Git 仓库以获得更精确的发布文件列表。'); + allFiles = walkDir(ROOT, ROOT); + } + + return Array.from(new Set( + allFiles + .filter(item => includeRules.some(rule => pathMatchesRule(item, rule))) + .filter(item => !excludeRules.some(rule => pathMatchesRule(item, rule))) + )); +} + +function buildArchive(stamp, config) { + const tempDir = ensureTempDeployDir(); + const listPath = path.join(tempDir, `deploy-files-${stamp}.txt`); + const archivePath = path.join(tempDir, `release-${stamp}.tar.gz`); + const files = listDeployableFiles(config); + + if (files.length === 0) { + throw new Error('git ls-files 未返回可发布文件,无法生成发布包。'); + } + + fs.writeFileSync(listPath, files.join('\n') + '\n', 'utf8'); + runCommand('tar', [ '-czf', archivePath, '-T', listPath ], { stdio: 'inherit' }); + + return { + archivePath, + listPath, + }; +} + +function buildRemoteCleanupGuard(sharedDirs, preserveDirs = []) { + const preserved = [ '.deploy', ...sharedDirs, ...preserveDirs ]; + return preserved.map(item => `! -name ${quoteForBash(item)}`).join(' '); +} + +module.exports = { + ROOT, + buildArchive, + buildRemoteCleanupGuard, + ensureCommandAvailable, + getNowStamp, + hasUncommittedChanges, + isGitAvailable, + loadDeployConfig, + quoteForBash, + runCommand, + runCommandSafe, + runScp, + runSsh, +}; diff --git a/script/deploy-ops.cjs b/script/deploy-ops.cjs new file mode 100644 index 0000000..53beae0 --- /dev/null +++ b/script/deploy-ops.cjs @@ -0,0 +1,169 @@ +'use strict'; + +const { loadDeployConfig, quoteForBash, runSsh } = require('./deploy-lib.cjs'); + +const COMMANDS = new Set([ 'inspect', 'smoke', 'verify', 'cleanup-backups', 'gateway-probe' ]); + +function parseArgs(argv) { + const options = { + envName: 'production', + command: '', + args: [], + }; + + const tokens = [ ...argv ]; + if (tokens.length === 0) { + throw new Error('缺少命令: inspect | smoke | verify | cleanup-backups | gateway-probe'); + } + + const first = tokens[0]; + if (!COMMANDS.has(first)) { + options.envName = first; + tokens.shift(); + } + + if (tokens.length === 0) { + throw new Error('缺少命令: inspect | smoke | verify | cleanup-backups | gateway-probe'); + } + + options.command = tokens[0]; + options.args = tokens.slice(1); + + if (!COMMANDS.has(options.command)) { + throw new Error(`不支持的命令: ${options.command}`); + } + + return options; +} + +function getActivePortInfo(config) { + const currentMdPath = `${config.deployRoot}/current.md`; + const remoteScript = [ + 'set -euo pipefail', + `cat ${quoteForBash(currentMdPath)} 2>/dev/null || true`, + ].join('\n'); + + const output = runSsh(config, remoteScript, { stdio: 'pipe' }); + const rawContent = String(output || '').trim(); + + if (!rawContent) { + throw new Error( + `无法读取远端 ${currentMdPath},内容为空或文件不存在。` + ); + } + + const version = rawContent.replace(/\r/g, '').trim(); + if (version !== 'v1' && version !== 'v2') { + throw new Error( + `远端 current.md 内容无效: "${rawContent}",期望值为 v1 或 v2。文件路径: ${currentMdPath}` + ); + } + + const port = version === 'v1' ? 4051 : 4052; + + return { port, version, rawContent }; +} + +function inspectState(config) { + const latestBackupFile = `${config.stateDir}/latest-backup.txt`; + const remoteScript = [ + 'set -euo pipefail', + `STATE_DIR=${quoteForBash(config.stateDir)}`, + `BACKUP_DIR=${quoteForBash(config.backupDir)}`, + `LATEST_FILE=${quoteForBash(latestBackupFile)}`, + 'printf "[STATE]\\n"', + 'ls -la "$STATE_DIR" 2>/dev/null || echo EMPTY', + 'printf "\\n[LATEST_BACKUP]\\n"', + 'if [ -f "$LATEST_FILE" ]; then cat "$LATEST_FILE"; else echo MISSING; fi', + 'printf "\\n[BACKUPS]\\n"', + 'ls -1 "$BACKUP_DIR" 2>/dev/null || echo EMPTY', + 'printf "\\n[INSTANCES]\\n"', + 'ls -la "$DEPLOY_ROOT/v1" 2>/dev/null | head -3 || echo "v1 EMPTY"', + 'ls -la "$DEPLOY_ROOT/v2" 2>/dev/null | head -3 || echo "v2 EMPTY"', + 'printf "\\n[CURRENT_MD]\\n"', + 'cat "$DEPLOY_ROOT/current.md" 2>/dev/null || echo MISSING', + ].join('\n'); + + return runSsh(config, remoteScript, { stdio: 'pipe' }).trim(); +} + +function smokeRoutes(config) { + const { port } = getActivePortInfo(config); + const remoteScript = [ + 'set -euo pipefail', + `PORT=${port}`, + 'for path in /; do', + ' code=$(curl -sS -o /dev/null -w "%{http_code}" "http://127.0.0.1:$PORT$path" || true)', + ' printf "%s %s\\n" "$path" "$code"', + 'done', + ].join('\n'); + + return runSsh(config, remoteScript, { stdio: 'pipe' }).trim(); +} + +function cleanupBackups(config, names) { + if (!names.length) { + throw new Error('cleanup-backups 需要至少一个备份文件名'); + } + + const remoteScript = [ + 'set -euo pipefail', + `BACKUP_DIR=${quoteForBash(config.backupDir)}`, + ...names.map((name, index) => `FILE_${index}=${quoteForBash(name)}`), + ...names.map((_, index) => `if [ -f "$BACKUP_DIR/$FILE_${index}" ]; then rm -f "$BACKUP_DIR/$FILE_${index}"; echo "REMOVED $FILE_${index}"; else echo "MISS $FILE_${index}"; fi`), + ].join('\n'); + + return runSsh(config, remoteScript, { stdio: 'pipe' }).trim(); +} + +function gatewayProbe(config, probePort) { + let targetPort; + if (probePort && /^\d+$/.test(probePort)) { + targetPort = Number(probePort); + } else { + targetPort = getActivePortInfo(config).port; + } + + const remoteScript = [ + 'set -euo pipefail', + `PORT=${targetPort}`, + 'echo "[GATEWAY_PROBE] port=$PORT"', + 'if curl -fsS --connect-timeout 2 --max-time 4 "http://127.0.0.1:$PORT/" >/dev/null 2>&1; then', + ' echo "GATEWAY_OK"', + 'else', + ' echo "GATEWAY_FAIL"', + 'fi', + ].join('\n'); + + return runSsh(config, remoteScript, { stdio: 'pipe' }).trim(); +} + +function main() { + const options = parseArgs(process.argv.slice(2)); + const config = loadDeployConfig(options.envName); + + switch (options.command) { + case 'inspect': + console.log(inspectState(config)); + break; + case 'smoke': + console.log(smokeRoutes(config)); + break; + case 'verify': { + const activeInfo = getActivePortInfo(config); + console.log(`ACTIVE_VERSION=${activeInfo.version}`); + console.log(`ACTIVE_PORT=${activeInfo.port}`); + break; + } + case 'cleanup-backups': + console.log(cleanupBackups(config, options.args)); + break; + case 'gateway-probe': + console.log(gatewayProbe(config, options.args[0] || '')); + break; + default: + throw new Error(`不支持的命令: ${options.command}`); + } +} + +main(); diff --git a/script/deploy-precheck.cjs b/script/deploy-precheck.cjs new file mode 100644 index 0000000..45d30f9 --- /dev/null +++ b/script/deploy-precheck.cjs @@ -0,0 +1,77 @@ +'use strict'; + +const { + loadDeployConfig, + runSsh, + ensureCommandAvailable, +} = require('./deploy-lib.cjs'); + +function main() { + try { + [ 'ssh', 'scp', 'tar', 'git' ].forEach(cmd => ensureCommandAvailable(cmd, '')); + console.log('LOCAL_TOOLS_OK'); + + const config = loadDeployConfig('production'); + const remoteScript = [ + 'set -euo pipefail', + `DEPLOY_ROOT=${JSON.stringify(config.deployRoot)}`, + 'PARENT_DIR=$(dirname "$DEPLOY_ROOT")', + 'if [ -d "$DEPLOY_ROOT" ]; then echo DEPLOY_ROOT_EXISTS; else echo DEPLOY_ROOT_MISSING; fi', + 'if [ -d "$DEPLOY_ROOT" ] && [ -w "$DEPLOY_ROOT" ]; then echo DEPLOY_ROOT_WRITABLE; else echo DEPLOY_ROOT_NOT_WRITABLE; fi', + 'if [ -d "$DEPLOY_ROOT/config" ]; then echo DEPLOY_CONFIG_EXISTS; else echo DEPLOY_CONFIG_MISSING; fi', + 'if [ -d "$PARENT_DIR" ] && [ -w "$PARENT_DIR" ]; then echo PARENT_WRITABLE; else echo PARENT_NOT_WRITABLE; fi', + 'if [ -d "$DEPLOY_ROOT/v1" ]; then echo V1_DIR_EXISTS; else echo V1_DIR_MISSING; fi', + 'if [ -d "$DEPLOY_ROOT/v2" ]; then echo V2_DIR_EXISTS; else echo V2_DIR_MISSING; fi', + 'if [ -f "$DEPLOY_ROOT/nginx-upstream.conf" ]; then echo NGINX_UPSTREAM_EXISTS; else echo NGINX_UPSTREAM_MISSING; fi', + 'if command -v node >/dev/null 2>&1; then echo REMOTE_NODE_OK; node -v; else echo REMOTE_NODE_MISSING; fi', + 'if command -v npm >/dev/null 2>&1; then echo REMOTE_NPM_OK; npm -v; else echo REMOTE_NPM_MISSING; fi', + 'if command -v tar >/dev/null 2>&1; then echo REMOTE_TAR_OK; tar --version | head -n 1; else echo REMOTE_TAR_MISSING; fi', + 'if command -v curl >/dev/null 2>&1; then', + ' CURRENT_FILE="$DEPLOY_ROOT/current.md"', + ' if [ -f "$CURRENT_FILE" ]; then', + ' ACTIVE_VERSION=$(cat "$CURRENT_FILE" | tr -d "[:space:]")', + ' if [ "$ACTIVE_VERSION" = "v1" ]; then', + ' if curl -fsS http://127.0.0.1:4051/ >/dev/null; then echo HEALTHCHECK_LOCAL_OK; else echo HEALTHCHECK_LOCAL_FAIL; fi', + ' elif [ "$ACTIVE_VERSION" = "v2" ]; then', + ' if curl -fsS http://127.0.0.1:4052/ >/dev/null; then echo HEALTHCHECK_LOCAL_OK; else echo HEALTHCHECK_LOCAL_FAIL; fi', + ' else', + ' echo HEALTHCHECK_LOCAL_SKIP_UNKNOWN_VERSION', + ' fi', + ' else', + ' V1_OK=false; V2_OK=false', + ' if curl -fsS http://127.0.0.1:4051/ >/dev/null; then V1_OK=true; fi', + ' if curl -fsS http://127.0.0.1:4052/ >/dev/null; then V2_OK=true; fi', + ' if [ "$V1_OK" = "true" ] || [ "$V2_OK" = "true" ]; then echo HEALTHCHECK_LOCAL_OK; else echo HEALTHCHECK_LOCAL_FAIL; fi', + ' fi', + 'else echo REMOTE_CURL_MISSING; fi', + ].join('\n'); + + const output = runSsh(config, remoteScript, { stdio: 'pipe' }); + for (const line of output.split(/\r?\n/)) { + if (line.trim()) { + console.log(line.trim()); + } + } + + console.log('PRECHECK_OK'); + } catch (error) { + const message = String(error && error.message ? error.message : ''); + let reason = 'UNKNOWN'; + + if (/Permission denied|Authentication failed/i.test(message)) { + reason = 'AUTH'; + } else if (/Connection timed out|No route to host|Connection refused|Could not resolve hostname/i.test(message)) { + reason = 'NETWORK'; + } else if (/Host key verification failed|REMOTE HOST IDENTIFICATION HAS CHANGED/i.test(message)) { + reason = 'HOST_KEY'; + } else if (/Operation timed out/i.test(message)) { + reason = 'TIMEOUT'; + } + + console.log('PRECHECK_FAIL'); + console.log(`PRECHECK_REASON_${reason}`); + process.exit(1); + } +} + +main(); diff --git a/script/deploy-remote.cjs b/script/deploy-remote.cjs new file mode 100644 index 0000000..2b2893b --- /dev/null +++ b/script/deploy-remote.cjs @@ -0,0 +1,437 @@ +'use strict'; + +const fs = require('node:fs'); +const path = require('node:path'); +const { + ROOT, + buildArchive, + buildRemoteCleanupGuard, + ensureCommandAvailable, + getNowStamp, + isGitAvailable, + loadDeployConfig, + quoteForBash, + runCommand, + runCommandSafe, + runScp, + runSsh, +} = require('./deploy-lib.cjs'); + +/** + * 通过 SSH 读取远端 current.md 文件,获取当前活跃版本标识(v1 或 v2) + */ +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}。请确保远端已存在 ${deployRoot}/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; +} + +function resolveTargetDir(currentVersion, deployRoot) { + if (currentVersion === 'v1') return `${deployRoot}/v2`; + return `${deployRoot}/v1`; +} + +function resolveTargetVersion(currentVersion) { + if (currentVersion === 'v1') return 'v2'; + return 'v1'; +} + +function getTargetPort(targetVersion) { + if (targetVersion === 'v1') return 4051; + return 4052; +} + +function getProcessTitle(version) { + return `egg-server-services.printer-${version}`; +} + +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. 部署前信息 + console.log('========================================'); + console.log('services.printer 蓝绿部署'); + console.log(`环境: ${envName}`); + console.log(`目标: ${config.username}@${config.host}:${config.port}`); + console.log(`远端根目录: ${config.deployRoot}`); + console.log('========================================'); + + // 检查 Git 未提交更改 + if (isGitAvailable()) { + const uncommitted = runCommandSafe('git', [ 'status', '--porcelain' ]); + if (uncommitted) { + console.warn('[WARN] 检测到未提交的更改:'); + const changes = uncommitted.split(/\r?\n/).filter(Boolean); + for (const line of changes.slice(0, 10)) { + console.warn(` ${line}`); + } + if (changes.length > 10) { + console.warn(` ... 还有 ${changes.length - 10} 处更改`); + } + console.warn('[WARN] 未提交的更改不会被包含在发布包中!'); + console.warn('[WARN] 建议先 git add && git commit 后再部署。'); + } + } + + // 2. 读取远端 current.md,确定目标目录 + const currentVersion = readRemoteCurrentVersion(config, config.deployRoot); + const targetDir = resolveTargetDir(currentVersion, config.deployRoot); + console.log(`远端当前活跃版本: ${currentVersion},目标部署目录: ${targetDir}`); + + // 3. 本地打包 + console.log('[1/8] 正在本地打包...'); + const stamp = getNowStamp(); + const packageJson = JSON.parse(fs.readFileSync(path.join(ROOT, 'package.json'), 'utf8')); + const packageVersion = String(packageJson.version || '0.0.0'); + let gitCommitShort = 'nogit'; + if (isGitAvailable()) { + gitCommitShort = runCommandSafe('git', [ 'rev-parse', '--short', 'HEAD' ]) || 'nogit'; + } + const releaseVersion = `v${packageVersion}-${stamp}-${gitCommitShort}`; + + const { archivePath } = buildArchive(stamp, config); + console.log(`[1/8] 打包完成: ${archivePath}`); + const remoteArchive = `${config.incomingDir}/release-${stamp}.tar.gz`; + + // 4. 远端创建目录结构 + console.log('[2/8] 正在远端创建目录...'); + const setupScript = [ + 'set -euo pipefail', + `mkdir -p ${quoteForBash(targetDir)} ${quoteForBash(config.incomingDir)} ${quoteForBash(config.backupDir)} ${quoteForBash(config.stateDir)}`, + ].join('\n'); + runSsh(config, setupScript); + console.log(`[2/8] 远端目录已就绪: ${targetDir}`); + + // 5. 远端备份当前目标目录 + console.log('[3/8] 正在备份远端目标目录...'); + const backupScript = [ + 'set -euo pipefail', + `TARGET_DIR=${quoteForBash(targetDir)}`, + `BACKUP_DIR=${quoteForBash(config.backupDir)}`, + `STAMP=${quoteForBash(stamp)}`, + 'if [ -f "$TARGET_DIR/package.json" ]; then', + ' BACKUP_FILE="$BACKUP_DIR/backup-${STAMP}.tar.gz"', + ' cd "$TARGET_DIR"', + ' tar -czf "$BACKUP_FILE" . --exclude="./node_modules" --exclude="./.deploy" --exclude="./logs" --exclude="./run" --exclude="./tmp" 2>/dev/null || true', + ' echo "已备份目标目录到: $BACKUP_FILE"', + 'else', + ' echo "目标目录为空,跳过备份"', + 'fi', + ].join('\n'); + try { + const backupOutput = runSsh(config, backupScript, { stdio: 'pipe' }); + console.log(String(backupOutput || '').trim()); + } catch (err) { + console.warn(`[WARN] 备份失败(非致命): ${err.message}`); + } + + // 6. SCP 上传 + console.log('[4/8] 正在上传发布包...'); + runScp(config, archivePath, remoteArchive); + console.log(`[4/8] 发布包已上传到远端: ${remoteArchive}`); + + // 7. 解压、安装依赖 + const cleanupGuard = buildRemoteCleanupGuard( + [ ...config.sharedDirs, 'node_modules' ], + config.preserveDirs + ); + + const remoteScript = [ + 'set -euo pipefail', + `TARGET_DIR=${quoteForBash(targetDir)}`, + `REMOTE_ARCHIVE=${quoteForBash(remoteArchive)}`, + `ACTIVE_DIR=${quoteForBash(`${config.deployRoot}/${currentVersion}`)}`, + // 从活跃版本复制 node_modules(蓝绿部署核心优化) + 'if [ ! -d "$TARGET_DIR/node_modules" ] && [ -d "$ACTIVE_DIR/node_modules" ]; then', + ' echo "正在从活跃版本 ($ACTIVE_DIR) 复制 node_modules ..."', + ' cp -a "$ACTIVE_DIR/node_modules" "$TARGET_DIR/node_modules"', + ' echo "node_modules 复制完成"', + 'fi', + 'cd "$TARGET_DIR"', + `find . -mindepth 1 -maxdepth 1 ${cleanupGuard} -exec rm -rf {} +`, + 'tar -xzf "$REMOTE_ARCHIVE" -C "$TARGET_DIR"', + 'rm -f "$REMOTE_ARCHIVE"', + // 保留 config 目录 + 'if [ ! -d "$TARGET_DIR/config" ]; then', + ` ACTIVE_DIR=${quoteForBash(`${config.deployRoot}/${currentVersion}`)}`, + ' if [ -d "$ACTIVE_DIR/config" ]; then', + ' cp -a "$ACTIVE_DIR/config" "$TARGET_DIR/config"', + ' echo "已从活跃版本 ($ACTIVE_DIR) 复制 config 目录"', + ' else', + ` FALLBACK_DIR=${quoteForBash(config.deployRoot)}`, + ' if [ -d "$FALLBACK_DIR/config" ]; then', + ' cp -a "$FALLBACK_DIR/config" "$TARGET_DIR/config"', + ' echo "已从根目录 ($FALLBACK_DIR) 复制 config 目录"', + ' else', + ' echo "[WARN] 未找到 config 目录来源,目标目录将缺少 config 配置!"', + ' fi', + ' fi', + 'fi', + 'npm install --production', + ].join('\n'); + + console.log('[5/8] 正在远端清理、解压、安装依赖...'); + runSsh(config, remoteScript); + console.log(`[5/8] 远端目标目录已清理、解压并安装依赖: ${targetDir}`); + + // 8. 目标版本信息 + const targetVersion = resolveTargetVersion(currentVersion); + const targetPort = getTargetPort(targetVersion); + const targetTitle = getProcessTitle(targetVersion); + const currentTitle = getProcessTitle(currentVersion); + const startLogPath = `/tmp/services.printer-${targetVersion}-start.log`; + const currentMdPath = `${config.deployRoot}/current.md`; + const oldDir = `${config.deployRoot}/${currentVersion}`; + + // 9. 停止目标目录可能残留的旧进程 + const stopTargetScript = [ + 'set -euo pipefail', + `TARGET_DIR=${quoteForBash(targetDir)}`, + `TARGET_VERSION=${quoteForBash(targetVersion)}`, + `TARGET_TITLE=${quoteForBash(targetTitle)}`, + 'TARGET_PIDS=$(ps -eo pid=,args= | awk -v root="$TARGET_DIR" \'index($0, root) && $2 ~ /node$/ { print $1 }\')', + 'TITLE_PIDS=$(ps -eo pid=,args= | awk -v t="$TARGET_TITLE" \'index($0, t) { print $1 }\')', + 'ALL_PIDS=$(echo "$TARGET_PIDS $TITLE_PIDS" | tr " " "\\n" | sort -u | grep -v "^$" | tr "\\n" " ")', + 'if [ -z "$ALL_PIDS" ]; then', + ' echo "未找到目标目录 ($TARGET_VERSION) 残留进程"', + 'else', + ' echo "正在停止目标目录 ($TARGET_VERSION) 残留进程: $ALL_PIDS"', + ' kill $ALL_PIDS || true', + ' sleep 2', + ' REMAIN=$(ps -eo pid=,args= | awk -v root="$TARGET_DIR" \'index($0, root) && $2 ~ /node$/ { print $1 }\')', + ' if [ -n "$REMAIN" ]; then', + ' kill -9 $REMAIN || true', + ' fi', + ' echo "目标目录 ($TARGET_VERSION) 残留进程已停止"', + 'fi', + ].join('\n'); + + try { + const stopTargetOutput = runSsh(config, stopTargetScript, { stdio: 'pipe' }); + console.log(String(stopTargetOutput || '').trim()); + } catch (err) { + console.warn(`[WARN] 停止目标目录残留进程失败: ${err.message}`); + } + + // 10. 检测并停止旧版根目录遗留进程(端口 4050 等) + const stopLegacyScript = [ + 'set -euo pipefail', + `ROOT_DIR=${quoteForBash(config.deployRoot)}`, + 'LEGACY_PIDS=$(ps -eo pid=,args= | awk -v root="$ROOT_DIR" \'index($0, "baseDir") && index($0, root) && !index($0, root"/v1") && !index($0, root"/v2") { print $1 }\')', + 'if [ -z "$LEGACY_PIDS" ]; then', + ' echo "未发现旧版根目录遗留进程"', + 'else', + ' echo "发现旧版根目录遗留进程: $LEGACY_PIDS,正在停止..."', + ' kill $LEGACY_PIDS || true', + ' sleep 3', + ' REMAIN=$(ps -eo pid=,args= | awk -v root="$ROOT_DIR" \'index($0, "baseDir") && index($0, root) && !index($0, root"/v1") && !index($0, root"/v2") { print $1 }\')', + ' if [ -n "$REMAIN" ]; then', + ' kill -9 $REMAIN || true', + ' fi', + ' echo "旧版根目录遗留进程已停止"', + 'fi', + ].join('\n'); + + try { + const legacyOutput = runSsh(config, stopLegacyScript, { stdio: 'pipe' }); + console.log(String(legacyOutput || '').trim()); + } catch (err) { + console.warn(`[WARN] 旧版进程清理: ${err.message}`); + } + + // 11. 启动新实例 + console.log('[6/8] 正在启动新实例...'); + const startScript = [ + 'set -euo pipefail', + `cd ${quoteForBash(targetDir)}`, + `nohup bash -lc 'npx egg-scripts start --daemon --title=${targetTitle} --sticky --port=${targetPort} --ignore-stderr' > ${quoteForBash(startLogPath)} 2>&1 &`, + `echo "已在 ${targetDir} 启动新实例 ${targetVersion} (title=${targetTitle}, 端口 ${targetPort}),启动日志: ${startLogPath}"`, + ].join('\n'); + + const startOutput = runSsh(config, startScript, { stdio: 'pipe' }); + console.log(String(startOutput || '').trim()); + + // 12. 健康检查 + console.log('[7/8] 正在进行健康检查(最多等待 60 秒)...'); + const healthCheckScript = [ + 'set -euo pipefail', + `TARGET_PORT=${targetPort}`, + 'HEALTH_OK=false', + '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, 第 $attempt 次)"`, + ' HEALTH_OK=true', + ' break', + ' fi', + ' sleep 2', + 'done', + 'if [ "$HEALTH_OK" != "true" ]; then', + ` echo "FATAL: 新实例 (${targetVersion}) 健康检查超时 (端口 $TARGET_PORT)" >&2`, + ' exit 1', + 'fi', + ].join('\n'); + + let healthPassed = false; + try { + const healthOutput = runSsh(config, healthCheckScript, { stdio: 'pipe' }); + console.log(String(healthOutput || '').trim()); + healthPassed = true; + } catch (err) { + console.error(`[FATAL] 新实例健康检查失败: ${err.message}`); + console.error(`[FATAL] 新实例 (${targetVersion}) 未能正常启动,保留当前活跃版本 (${currentVersion}) 不变。`); + console.error(`[FATAL] 请检查启动日志: ssh ${config.username}@${config.host} "cat ${startLogPath}"`); + console.error('[FATAL] 部署已中止,当前服务不受影响。'); + + // 清理失败的新实例 + const cleanupFailedScript = [ + 'set -euo pipefail', + `TARGET_DIR=${quoteForBash(targetDir)}`, + 'FAILED_PIDS=$(ps -eo pid=,args= | awk -v root="$TARGET_DIR" \'index($0, root) && $2 ~ /node$/ { print $1 }\')', + 'if [ -n "$FAILED_PIDS" ]; then kill -9 $FAILED_PIDS || true; fi', + 'echo "已清理失败的新实例进程"', + ].join('\n'); + try { + runSsh(config, cleanupFailedScript, { stdio: 'pipe' }); + } catch (_) { /* ignore */ } + + process.exit(1); + } + + // 13. 切换 current.md + console.log('[8/8] 正在切换流量...'); + const switchCurrentMdScript = [ + 'set -euo pipefail', + `printf '%s\\n' ${quoteForBash(targetVersion)} > ${quoteForBash(currentMdPath)}`, + `echo "current.md 已切换 -> ${targetVersion}"`, + ].join('\n'); + const switchOutput2 = runSsh(config, switchCurrentMdScript, { stdio: 'pipe' }); + console.log(String(switchOutput2 || '').trim()); + + // 14. 切换 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] 新实例已在端口 ${targetPort} 运行,但 Nginx 未自动切换。`); + console.warn(`[WARN] 请手动更新 ${nginxUpstreamPath} 并执行 nginx -s reload`); + } + + // 15. 停止旧实例 + const stopOldScript = [ + 'set -euo pipefail', + `OLD_DIR=${quoteForBash(oldDir)}`, + `OLD_VERSION=${quoteForBash(currentVersion)}`, + `OLD_TITLE=${quoteForBash(currentTitle)}`, + '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}) 可能仍在运行,请人工确认并停止`); + } + + // 16. 记录远端 release 状态 + const remoteStateFile = `${config.stateDir}/current-release.json`; + const remoteHistoryFile = `${config.stateDir}/release-history.jsonl`; + const releaseEntry = { + releaseVersion, + packageVersion, + gitCommitShort, + deployRoot: config.deployRoot, + targetVersion, + targetPort, + deployedAt: new Date().toISOString(), + }; + const releaseJson = JSON.stringify(releaseEntry); + + const recordReleaseScript = [ + 'set -euo pipefail', + `STATE_FILE=${quoteForBash(remoteStateFile)}`, + `HISTORY_FILE=${quoteForBash(remoteHistoryFile)}`, + `ENTRY=${quoteForBash(releaseJson)}`, + 'printf "%s\\n" "$ENTRY" > "$STATE_FILE"', + 'printf "%s\\n" "$ENTRY" >> "$HISTORY_FILE"', + 'echo "远端 release 状态已记录"', + ].join('\n'); + + try { + const recordOutput = runSsh(config, recordReleaseScript, { stdio: 'pipe' }); + console.log(String(recordOutput || '').trim()); + } catch (err) { + console.warn(`[WARN] 记录远端 release 状态失败: ${err.message}`); + } + + // 17. 清理旧备份 + const cleanupBackupsScript = [ + 'set -euo pipefail', + `BACKUP_DIR=${quoteForBash(config.backupDir)}`, + `KEEP=${Number(config.keepBackups)}`, + 'cd "$BACKUP_DIR"', + 'ls -1t backup-*.tar.gz 2>/dev/null | tail -n +$((KEEP + 1)) | while read -r f; do rm -f "$f"; echo "已清理旧备份: $f"; done', + 'echo "备份清理完成(保留最近 ${KEEP} 个)"', + ].join('\n'); + + try { + const cleanupOutput = runSsh(config, cleanupBackupsScript, { stdio: 'pipe' }); + console.log(String(cleanupOutput || '').trim()); + } catch (err) { + console.warn(`[WARN] 清理旧备份失败: ${err.message}`); + } + + // 18. 完成 + console.log('========================================'); + console.log(`发布完成: ${envName} -> ${config.username}@${config.host}:${targetDir}`); + console.log(`线上版本号: ${releaseVersion}`); + console.log(`当前活跃版本已切换为: ${targetVersion} (端口 ${targetPort})`); + console.log('========================================'); +} + +main(); diff --git a/script/deploy-version.cjs b/script/deploy-version.cjs new file mode 100644 index 0000000..1d40a3e --- /dev/null +++ b/script/deploy-version.cjs @@ -0,0 +1,165 @@ +'use strict'; + +const path = require('node:path'); +const { + ensureCommandAvailable, + loadDeployConfig, + quoteForBash, + runSsh, +} = require('./deploy-lib.cjs'); + +function parseArgs(argv) { + const options = { + history: 0, + }; + + for (const item of argv) { + if (!item) continue; + if (item.startsWith('--history=')) { + const value = Number(item.slice('--history='.length)); + if (Number.isFinite(value) && value > 0) { + options.history = Math.floor(value); + } + } + } + + return options; +} + +function queryActiveInstance(config) { + const currentMdFile = path.posix.join(config.deployRoot, 'current.md'); + const remoteScript = [ + 'set -euo pipefail', + `FILE=${quoteForBash(currentMdFile)}`, + 'if [ -f "$FILE" ]; then', + ' cat "$FILE"', + 'else', + ' echo CURRENT_MD_NOT_FOUND', + 'fi', + ].join('\n'); + + const raw = runSsh(config, remoteScript, { stdio: 'pipe' }).trim(); + if (!raw || raw === 'CURRENT_MD_NOT_FOUND') { + return null; + } + + const version = raw.replace(/[\r\n\s]/g, ''); + if (version !== 'v1' && version !== 'v2') { + return null; + } + + const port = version === 'v2' ? 4052 : 4051; + return { version, port, currentMd: raw.split('\n')[0].trim() }; +} + +function queryCurrentRelease(config) { + const releaseFile = path.posix.join(config.stateDir, 'current-release.json'); + const remoteScript = [ + 'set -euo pipefail', + `FILE=${quoteForBash(releaseFile)}`, + 'if [ -f "$FILE" ]; then', + ' cat "$FILE"', + 'else', + ' echo ONLINE_VERSION_NOT_FOUND', + 'fi', + ].join('\n'); + + const output = runSsh(config, remoteScript, { stdio: 'pipe' }).trim(); + if (!output || output === 'ONLINE_VERSION_NOT_FOUND') { + return null; + } + + try { + return JSON.parse(output); + } catch (error) { + return output; + } +} + +function queryReleaseHistory(config, limit) { + const historyFile = path.posix.join(config.stateDir, 'release-history.jsonl'); + const remoteScript = [ + 'set -euo pipefail', + `FILE=${quoteForBash(historyFile)}`, + `LIMIT=${Number(limit)}`, + 'if [ -f "$FILE" ]; then', + ' tail -n "$LIMIT" "$FILE"', + 'else', + ' echo ONLINE_VERSION_HISTORY_NOT_FOUND', + 'fi', + ].join('\n'); + + const output = runSsh(config, remoteScript, { stdio: 'pipe' }).trim(); + if (!output || output === 'ONLINE_VERSION_HISTORY_NOT_FOUND') { + return null; + } + + const records = []; + for (const line of output.split(/\r?\n/)) { + const trimmed = line.trim(); + if (!trimmed) continue; + try { + records.push(JSON.parse(trimmed)); + } catch (error) { + records.push({ raw: trimmed }); + } + } + return records; +} + +function main() { + const envName = process.argv[2] || 'production'; + const options = parseArgs(process.argv.slice(3)); + const config = loadDeployConfig(envName); + + ensureCommandAvailable('ssh', '请先安装 OpenSSH Client 并确保 ssh 在 PATH 中。'); + + const active = queryActiveInstance(config); + const currentRelease = queryCurrentRelease(config); + + console.log('========================================'); + console.log(`部署环境: ${envName}`); + console.log(`远端主机: ${config.username}@${config.host}:${config.port}`); + console.log(`部署根目录: ${config.deployRoot}`); + console.log('========================================'); + + if (active) { + console.log(`活跃版本: ${active.version} (端口 ${active.port})`); + } else { + console.log('活跃版本: 未检测到(current.md 不存在或无效)'); + } + + console.log('----------------------------------------'); + + if (currentRelease && typeof currentRelease === 'object') { + console.log('当前线上版本:'); + console.log(` 发布版本: ${currentRelease.releaseVersion || 'N/A'}`); + console.log(` package版本: ${currentRelease.packageVersion || 'N/A'}`); + console.log(` Git commit: ${currentRelease.gitCommitShort || 'N/A'}`); + console.log(` 目标版本: ${currentRelease.targetVersion || 'N/A'} (端口 ${currentRelease.targetPort || 'N/A'})`); + console.log(` 发布时间: ${currentRelease.deployedAt || 'N/A'}`); + } else if (currentRelease) { + console.log(`当前线上版本 (原始): ${String(currentRelease)}`); + } else { + console.log('当前线上版本: 未记录'); + } + + if (options.history > 0) { + console.log('----------------------------------------'); + console.log(`最近 ${options.history} 条发布记录:`); + const history = queryReleaseHistory(config, options.history); + if (history && history.length > 0) { + for (const record of history) { + if (record.releaseVersion) { + console.log(` ${record.releaseVersion} | ${record.targetVersion || '?'} | ${record.deployedAt || '?'}`); + } else { + console.log(` ${JSON.stringify(record)}`); + } + } + } else { + console.log(' (无历史记录)'); + } + } +} + +main(); diff --git a/script/git-safety-check.cjs b/script/git-safety-check.cjs new file mode 100644 index 0000000..7d6c1fa --- /dev/null +++ b/script/git-safety-check.cjs @@ -0,0 +1,44 @@ +'use strict'; + +const path = require('node:path'); +const { runCommandSafe } = require('./deploy-lib.cjs'); + +const BLOCKED_PATH_PATTERNS = [ + /^config\/config\.local\.js$/, + /^config\/deploy\.config\.local\.cjs$/, + /^tmp\/(?!deploy\/)(?!docs\/).+/, + /^logs\//, + /^run\//, + /\.pem$/i, + /\.key$/i, + /^\.env(?:\..+)?$/, +]; + +function normalizePath(filePath) { + return filePath.replace(/\\/g, '/'); +} + +function listStagedFiles() { + const output = runCommandSafe('git', [ 'diff', '--cached', '--name-only', '--diff-filter=ACMR' ]); + if (!output) return []; + return output.split(/\r?\n/).map(item => normalizePath(item.trim())).filter(Boolean); +} + +function main() { + const stagedFiles = listStagedFiles(); + const blocked = stagedFiles.filter(filePath => BLOCKED_PATH_PATTERNS.some(pattern => pattern.test(filePath))); + + if (blocked.length === 0) { + console.log('git safety check passed'); + return; + } + + console.error('以下文件禁止提交到 git,请先取消暂存:'); + for (const filePath of blocked) { + console.error(`- ${filePath}`); + } + console.error('建议使用 git restore --staged 取消暂存,再继续提交。'); + process.exit(1); +} + +main(); diff --git a/script/rollback-remote.cjs b/script/rollback-remote.cjs new file mode 100644 index 0000000..9d58da7 --- /dev/null +++ b/script/rollback-remote.cjs @@ -0,0 +1,196 @@ +'use strict'; + +const path = require('node:path'); +const { + buildRemoteCleanupGuard, + ensureCommandAvailable, + loadDeployConfig, + quoteForBash, + runSsh, +} = require('./deploy-lib.cjs'); + +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}。请确保远端已存在 ${deployRoot}/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; +} + +function getTargetPort(targetVersion) { + if (targetVersion === 'v1') return 4051; + return 4052; +} + +function parseBackupArg(argv) { + const backupArg = argv.find(item => item.startsWith('--backup=')); + if (!backupArg) return ''; + return backupArg.slice('--backup='.length).trim(); +} + +function getProcessTitle(version) { + return `egg-server-services.printer-${version}`; +} + +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 中。'); + + // 1. 读取远端 current.md + const currentVersion = readRemoteCurrentVersion(config, config.deployRoot); + const currentDir = `${config.deployRoot}/${currentVersion}`; + const currentPort = getTargetPort(currentVersion); + const currentTitle = getProcessTitle(currentVersion); + console.log(`远端当前活跃版本: ${currentVersion},活跃目录: ${currentDir},端口: ${currentPort}`); + + // 2. 确定备份包 + const latestBackupFile = path.posix.join(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 "SELECTED_BACKUP=$TARGET_BACKUP"', + 'echo "$TARGET_BACKUP"', + ].join('\n'); + + const selectedBackup = runSsh(config, selectBackupScript, { stdio: 'pipe' }).trim(); + const backupFile = selectedBackup.replace(/^SELECTED_BACKUP=/, '').split('\n').pop().trim(); + if (!backupFile || backupFile.startsWith('ERROR:')) { + throw new Error(selectedBackup); + } + console.log(`使用备份包: ${config.backupDir}/${backupFile}`); + + // 3. 停止当前活跃实例 + const stopCurrentScript = [ + 'set -euo pipefail', + `CURRENT_DIR=${quoteForBash(currentDir)}`, + `CURRENT_VERSION=${quoteForBash(currentVersion)}`, + 'CURRENT_PIDS=$(ps -eo pid=,args= | awk -v root="$CURRENT_DIR" \'index($0, root) && $2 ~ /node$/ { print $1 }\')', + 'if [ -z "$CURRENT_PIDS" ]; then', + ' echo "未找到当前实例 ($CURRENT_VERSION) 进程"', + 'else', + ' echo "正在停止当前实例 ($CURRENT_VERSION): $CURRENT_PIDS"', + ' kill $CURRENT_PIDS || true', + ' sleep 3', + ' REMAIN=$(ps -eo pid=,args= | awk -v root="$CURRENT_DIR" \'index($0, root) && $2 ~ /node$/ { print $1 }\')', + ' if [ -n "$REMAIN" ]; then', + ' kill -9 $REMAIN || true', + ' fi', + ' echo "当前实例 ($CURRENT_VERSION) 已停止"', + 'fi', + ].join('\n'); + + try { + const stopOutput = runSsh(config, stopCurrentScript, { stdio: 'pipe' }); + console.log(String(stopOutput || '').trim()); + } catch (err) { + console.warn(`[WARN] 停止当前实例失败: ${err.message}`); + } + + // 4. 清理当前活跃目录并解压备份包 + const cleanupGuard = buildRemoteCleanupGuard(config.sharedDirs, config.preserveDirs); + const rollbackScript = [ + 'set -euo pipefail', + `CURRENT_DIR=${quoteForBash(currentDir)}`, + `BACKUP_DIR=${quoteForBash(config.backupDir)}`, + `BACKUP_FILE=${quoteForBash(backupFile)}`, + 'cd "$CURRENT_DIR"', + `find . -mindepth 1 -maxdepth 1 ${cleanupGuard} -exec rm -rf {} +`, + 'tar -xzf "$BACKUP_DIR/$BACKUP_FILE" -C "$CURRENT_DIR"', + 'npm install --production', + 'echo "备份包已解压并安装依赖: $BACKUP_FILE"', + ].join('\n'); + + runSsh(config, rollbackScript); + console.log(`回滚包已解压到: ${currentDir}`); + + // 5. 重启当前实例 + const startLogPath = `/tmp/services.printer-${currentVersion}-rollback.log`; + const restartScript = [ + 'set -euo pipefail', + `cd ${quoteForBash(currentDir)}`, + `nohup bash -lc 'npx egg-scripts start --daemon --title=${currentTitle} --sticky --port=${currentPort} --ignore-stderr' > ${quoteForBash(startLogPath)} 2>&1 &`, + `echo "已在 ${currentDir} 重启实例 ${currentVersion} (title=${currentTitle}, 端口 ${currentPort}),启动日志: ${startLogPath}"`, + ].join('\n'); + + const restartOutput = runSsh(config, restartScript, { stdio: 'pipe' }); + console.log(String(restartOutput || '').trim()); + + // 6. 健康检查 + const healthCheckScript = [ + 'set -euo pipefail', + `TARGET_PORT=${currentPort}`, + '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 "回滚实例 (${currentVersion}) 健康检查通过 (端口 $TARGET_PORT)"`, + ' break', + ' fi', + ' if [ "$attempt" -eq 30 ]; then', + ` echo "回滚实例 (${currentVersion}) 健康检查超时 (端口 $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}`); + } + + // 7. 确保 Nginx upstream 指向当前端口 + const nginxUpstreamPath = `${config.deployRoot}/nginx-upstream.conf`; + const switchNginxScript = [ + 'set -euo pipefail', + `printf 'proxy_pass http://127.0.0.1:%s;\\n' ${currentPort} > ${quoteForBash(nginxUpstreamPath)}`, + 'nginx -t && nginx -s reload', + `echo "Nginx upstream 已确认指向 127.0.0.1:${currentPort}"`, + ].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.log('========================================'); + console.log(`回滚完成: ${currentVersion} (端口 ${currentPort})`); + console.log(`使用备份包: ${backupFile}`); + console.log('========================================'); +} + +main(); diff --git a/script/setup-git-hooks.cjs b/script/setup-git-hooks.cjs new file mode 100644 index 0000000..4ddd7e0 --- /dev/null +++ b/script/setup-git-hooks.cjs @@ -0,0 +1,45 @@ +'use strict'; + +const fs = require('node:fs'); +const path = require('node:path'); +const { ROOT } = require('./deploy-lib.cjs'); + +function main() { + const hooksDir = path.join(ROOT, '.githooks'); + const gitHooksDir = path.join(ROOT, '.git', 'hooks'); + + if (!fs.existsSync(hooksDir)) { + fs.mkdirSync(hooksDir, { recursive: true }); + } + + // 创建 pre-commit hook 脚本 + const preCommitPath = path.join(hooksDir, 'pre-commit'); + const preCommitContent = [ + '#!/bin/sh', + 'node script/git-safety-check.cjs', + '', + ].join('\n'); + fs.writeFileSync(preCommitPath, preCommitContent, { mode: 0o755 }); + + // 配置 git 使用 .githooks 目录 + const { execSync } = require('node:child_process'); + try { + execSync('git config core.hooksPath .githooks', { cwd: ROOT, encoding: 'utf8' }); + console.log('Git hooks 已配置: core.hooksPath = .githooks'); + } catch (error) { + console.warn('配置 git core.hooksPath 失败,请手动执行: git config core.hooksPath .githooks'); + } + + // 确保 .gitignore 中有 versioning 相关规则 + const gitignorePath = path.join(ROOT, '.gitignore'); + if (fs.existsSync(gitignorePath)) { + const content = fs.readFileSync(gitignorePath, 'utf8'); + if (!content.includes('versioning/')) { + console.warn('建议在 .gitignore 中添加 versioning/ 规则以保护本地版本记录'); + } + } + + console.log('Git hooks 设置完成。'); +} + +main(); diff --git a/script/version-history.cjs b/script/version-history.cjs new file mode 100644 index 0000000..f032de9 --- /dev/null +++ b/script/version-history.cjs @@ -0,0 +1,27 @@ +'use strict'; + +const { readVersionHistory } = require('./version-registry.cjs'); + +function parseLimit(argv) { + for (const item of argv) { + if (item.startsWith('--limit=')) { + const value = Number(item.slice('--limit='.length)); + if (Number.isFinite(value) && value > 0) { + return Math.floor(value); + } + } + } + return 20; +} + +function main() { + const limit = parseLimit(process.argv.slice(2)); + const records = readVersionHistory(limit); + if (records.length === 0) { + console.log('LOCAL_VERSION_HISTORY_EMPTY'); + return; + } + console.log(JSON.stringify(records, null, 2)); +} + +main(); diff --git a/script/version-record.cjs b/script/version-record.cjs new file mode 100644 index 0000000..bec408e --- /dev/null +++ b/script/version-record.cjs @@ -0,0 +1,24 @@ +'use strict'; + +const { recordVersionUpdate } = require('./version-registry.cjs'); + +function parseArgs(argv) { + let note = ''; + for (const item of argv) { + if (item.startsWith('--note=')) { + note = item.slice('--note='.length).trim(); + } + } + return { note }; +} + +function main() { + const options = parseArgs(process.argv.slice(2)); + const entry = recordVersionUpdate({ + source: 'version:record', + note: options.note || 'package-version-update', + }); + console.log(JSON.stringify(entry, null, 2)); +} + +main(); diff --git a/script/version-registry.cjs b/script/version-registry.cjs new file mode 100644 index 0000000..7acbc51 --- /dev/null +++ b/script/version-registry.cjs @@ -0,0 +1,95 @@ +'use strict'; + +const fs = require('node:fs'); +const path = require('node:path'); +const { ROOT, runCommand, runCommandSafe, isGitAvailable } = require('./deploy-lib.cjs'); + +const VERSION_DIR = path.join(ROOT, 'versioning'); +const VERSION_HISTORY_FILE = path.join(VERSION_DIR, 'package-version-history.jsonl'); +const VERSION_CURRENT_FILE = path.join(VERSION_DIR, 'package-version-current.json'); + +function ensureVersionDir() { + fs.mkdirSync(VERSION_DIR, { recursive: true }); +} + +function getPackageMeta() { + const pkg = JSON.parse(fs.readFileSync(path.join(ROOT, 'package.json'), 'utf8')); + const packageVersion = String(pkg.version || '0.0.0'); + + let gitCommit = ''; + let gitCommitShort = ''; + let gitBranch = ''; + if (isGitAvailable()) { + try { + gitCommit = runCommand('git', [ 'rev-parse', 'HEAD' ]); + gitCommitShort = runCommand('git', [ 'rev-parse', '--short', 'HEAD' ]); + gitBranch = runCommand('git', [ 'rev-parse', '--abbrev-ref', 'HEAD' ]); + } catch (error) { + gitCommit = ''; + gitCommitShort = ''; + gitBranch = ''; + } + } + + return { + packageVersion, + gitCommit, + gitCommitShort, + gitBranch, + }; +} + +function recordVersionUpdate(options = {}) { + ensureVersionDir(); + + const meta = getPackageMeta(); + const entry = { + recordedAt: new Date().toISOString(), + source: options.source || 'manual', + note: options.note || '', + packageVersion: meta.packageVersion, + gitCommit: meta.gitCommit, + gitCommitShort: meta.gitCommitShort, + gitBranch: meta.gitBranch, + releaseVersion: options.releaseVersion || '', + deployRoot: options.deployRoot || '', + remoteBackupFile: options.remoteBackupFile || '', + remoteStateFile: options.remoteStateFile || '', + remoteHistoryFile: options.remoteHistoryFile || '', + }; + + fs.appendFileSync(VERSION_HISTORY_FILE, `${JSON.stringify(entry)}\n`, 'utf8'); + fs.writeFileSync(VERSION_CURRENT_FILE, `${JSON.stringify(entry, null, 2)}\n`, 'utf8'); + return entry; +} + +function readVersionHistory(limit = 20) { + if (!fs.existsSync(VERSION_HISTORY_FILE)) { + return []; + } + + const lines = fs.readFileSync(VERSION_HISTORY_FILE, 'utf8') + .split(/\r?\n/) + .map(item => item.trim()) + .filter(Boolean); + + const take = Math.max(1, Number(limit || 20)); + const selected = lines.slice(-take); + const records = []; + for (const line of selected) { + try { + records.push(JSON.parse(line)); + } catch (error) { + records.push({ raw: line }); + } + } + return records; +} + +module.exports = { + VERSION_CURRENT_FILE, + VERSION_DIR, + VERSION_HISTORY_FILE, + readVersionHistory, + recordVersionUpdate, +};