mirror of
https://gitee.com/qqtt-ah/ecom-dmb.git
synced 2026-11-24 01:19:19 +08:00
feat: 完善部署脚本
This commit is contained in:
@@ -4,10 +4,11 @@ import { join } from 'path';
|
||||
|
||||
import { Client } from 'ssh2';
|
||||
import { getBackendDir, getBackendDeployDir } from '../config.js';
|
||||
import { findMainJar, getLocalTempPath, resolveMavenCommand } from '../platform.js';
|
||||
import { uploadFile, ensureRemoteDir } from '../ssh.js';
|
||||
import { remoteBuildImage } from '../docker.js';
|
||||
import { printInfo, printSuccess } from '../ui/render.js';
|
||||
import type { Service, ServiceEnvConfig } from '../types.js';
|
||||
import type { Environment, Service, ServiceEnvConfig } from '../types.js';
|
||||
|
||||
export const serviceType: Service = 'backend';
|
||||
|
||||
@@ -15,13 +16,15 @@ export async function build(cfg: ServiceEnvConfig): Promise<string> {
|
||||
const backendDir = getBackendDir();
|
||||
if (!existsSync(backendDir)) throw new Error(`后端项目目录不存在: ${backendDir}`);
|
||||
|
||||
const mvnw = join(backendDir, 'mvnw');
|
||||
const mvnCmd = existsSync(mvnw) ? `"${mvnw}"` : 'mvn';
|
||||
const mvnCmd = resolveMavenCommand(backendDir);
|
||||
|
||||
printInfo('构建后端 (Maven)...');
|
||||
// Spring profile 在容器启动时注入,Maven 构建不使用 -P
|
||||
execSync(`${mvnCmd} clean package -DskipTests`, {
|
||||
stdio: 'inherit', cwd: backendDir,
|
||||
stdio: 'inherit',
|
||||
cwd: backendDir,
|
||||
// @types/node 22 中 shell 仅接受 string,Windows 需指定 cmd 才能执行 .cmd
|
||||
shell: process.platform === 'win32' ? (process.env.COMSPEC || 'cmd.exe') : undefined,
|
||||
});
|
||||
printSuccess('后端构建完成');
|
||||
|
||||
@@ -30,23 +33,35 @@ export async function build(cfg: ServiceEnvConfig): Promise<string> {
|
||||
return jarDir;
|
||||
}
|
||||
|
||||
export async function deploy(conn: Client, cfg: ServiceEnvConfig, buildDir: string): Promise<void> {
|
||||
export async function deploy(conn: Client, cfg: ServiceEnvConfig, buildDir: string, env: Environment): Promise<void> {
|
||||
const serviceDir = `${cfg.server.deployPath}/backend`;
|
||||
await ensureRemoteDir(conn, serviceDir);
|
||||
|
||||
const jars = execSync(`ls "${buildDir}"/*.jar 2>/dev/null`, { encoding: 'utf8' }).trim();
|
||||
if (!jars) throw new Error('未找到 JAR 文件');
|
||||
|
||||
await uploadFile(conn, jars.split('\n')[0], `${serviceDir}/app.jar`);
|
||||
const jarPath = findMainJar(buildDir);
|
||||
await uploadFile(conn, jarPath, `${serviceDir}/app.jar`);
|
||||
|
||||
const dockerfileTmp = getLocalTempPath('ecom-backend.Dockerfile');
|
||||
const dockerfileSrc = join(getBackendDeployDir(), 'Dockerfile');
|
||||
if (!existsSync(dockerfileSrc)) {
|
||||
printInfo('后端 deploy/Dockerfile 不存在,使用默认模板');
|
||||
writeFileSync('/tmp/ecom-backend.Dockerfile', 'FROM eclipse-temurin:17-jre-alpine\nWORKDIR /app\nRUN addgroup -S app && adduser -S app -G app\nCOPY app.jar app.jar\nRUN chown -R app:app /app\nUSER app\nEXPOSE 8080\nENTRYPOINT ["java", "-jar", "app.jar"]\n');
|
||||
writeFileSync(dockerfileTmp, [
|
||||
'# 默认使用 DaoCloud 镜像加速,服务器可访问 Docker Hub 时改为 eclipse-temurin:17-jre-alpine',
|
||||
'ARG BASE_IMAGE=docker.m.daocloud.io/library/eclipse-temurin:17-jre-alpine',
|
||||
'FROM ${BASE_IMAGE}',
|
||||
'WORKDIR /app',
|
||||
'RUN addgroup -S app && adduser -S app -G app',
|
||||
'COPY app.jar app.jar',
|
||||
'RUN chown -R app:app /app',
|
||||
'USER app',
|
||||
'# 实际端口由 Spring profile 决定(test:8101 / pre:8102 / prod:8103)',
|
||||
'EXPOSE 8101 8102 8103',
|
||||
'ENTRYPOINT ["java", "-jar", "app.jar"]',
|
||||
'',
|
||||
].join('\n'));
|
||||
} else {
|
||||
writeFileSync('/tmp/ecom-backend.Dockerfile', readFileSync(dockerfileSrc, 'utf8'));
|
||||
writeFileSync(dockerfileTmp, readFileSync(dockerfileSrc, 'utf8'));
|
||||
}
|
||||
await uploadFile(conn, '/tmp/ecom-backend.Dockerfile', `${serviceDir}/Dockerfile`);
|
||||
await uploadFile(conn, dockerfileTmp, `${serviceDir}/Dockerfile`);
|
||||
|
||||
await remoteBuildImage(conn, 'backend', serviceDir);
|
||||
await remoteBuildImage(conn, 'backend', serviceDir, env);
|
||||
}
|
||||
|
||||
@@ -4,9 +4,10 @@ import { join } from 'path';
|
||||
|
||||
import { Client } from 'ssh2';
|
||||
import { getFrontendDir } from '../config.js';
|
||||
import { createTarGz, getLocalTempPath } from '../platform.js';
|
||||
import { execRemote, uploadFile, ensureRemoteDir } from '../ssh.js';
|
||||
import { printInfo, printSuccess } from '../ui/render.js';
|
||||
import type { Service, ServiceEnvConfig } from '../types.js';
|
||||
import type { Environment, Service, ServiceEnvConfig } from '../types.js';
|
||||
|
||||
export const serviceType: Service = 'frontend';
|
||||
|
||||
@@ -23,16 +24,12 @@ export async function build(): Promise<string> {
|
||||
return distDir;
|
||||
}
|
||||
|
||||
export async function deploy(conn: Client, cfg: ServiceEnvConfig, buildDir: string): Promise<void> {
|
||||
export async function deploy(conn: Client, cfg: ServiceEnvConfig, buildDir: string, _env: Environment): Promise<void> {
|
||||
if (cfg.extractDir) {
|
||||
await ensureRemoteDir(conn, cfg.extractDir);
|
||||
|
||||
const tmpTar = '/tmp/ecom-frontend-build.tar.gz';
|
||||
try {
|
||||
execSync(`tar -czf "${tmpTar}" -C "${buildDir}" .`, { stdio: 'pipe' });
|
||||
} catch (e: any) {
|
||||
throw new Error(`打包失败 (${buildDir}): ${e.message}`);
|
||||
}
|
||||
const tmpTar = getLocalTempPath('ecom-frontend-build.tar.gz');
|
||||
createTarGz(buildDir, tmpTar);
|
||||
await uploadFile(conn, tmpTar, `${cfg.extractDir}/frontend.tar.gz`);
|
||||
|
||||
const { code, stderr } = await execRemote(
|
||||
@@ -47,8 +44,8 @@ export async function deploy(conn: Client, cfg: ServiceEnvConfig, buildDir: stri
|
||||
const serviceDir = `${cfg.server.deployPath}/frontend`;
|
||||
await ensureRemoteDir(conn, serviceDir);
|
||||
|
||||
const tmpTar = '/tmp/ecom-frontend-build.tar.gz';
|
||||
execSync(`tar -czf "${tmpTar}" -C "${buildDir}" .`, { stdio: 'pipe' });
|
||||
const tmpTar = getLocalTempPath('ecom-frontend-build.tar.gz');
|
||||
createTarGz(buildDir, tmpTar);
|
||||
await uploadFile(conn, tmpTar, `${serviceDir}/build.tar.gz`);
|
||||
|
||||
const { code, stderr } = await execRemote(conn, `cd "${serviceDir}" && tar -xzf build.tar.gz && rm build.tar.gz`);
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { connectWithRetry, installKeyAfterPasswordAuth, execRemote } from '../ssh.js';
|
||||
import { composeUp, composeRestart, composeLogs, composeStatus, composeDown, uploadComposeFile } from '../docker.js';
|
||||
import { composeDeploy, composeRestart, composeLogs, composeStatus, composeDown, uploadComposeFile } from '../docker.js';
|
||||
import { loadConfig, getServiceConfig, syncServerKeyAuth } from '../config.js';
|
||||
import { printError, printInfo, printSuccess } from '../ui/render.js';
|
||||
import type { Environment, Service, ServiceEnvConfig } from '../types.js';
|
||||
@@ -8,7 +8,10 @@ import * as frontendDeploy from './frontend.js';
|
||||
import * as backendDeploy from './backend.js';
|
||||
import * as licenseDeploy from './license.js';
|
||||
|
||||
const deployers: Record<Service, { build: (cfg?: ServiceEnvConfig) => Promise<string>; deploy: (conn: any, cfg: ServiceEnvConfig, buildDir: string) => Promise<void> }> = {
|
||||
const deployers: Record<Service, {
|
||||
build: (cfg?: ServiceEnvConfig) => Promise<string>;
|
||||
deploy: (conn: any, cfg: ServiceEnvConfig, buildDir: string, env: Environment) => Promise<void>;
|
||||
}> = {
|
||||
frontend: frontendDeploy as any,
|
||||
backend: backendDeploy as any,
|
||||
license: licenseDeploy as any,
|
||||
@@ -23,11 +26,17 @@ export async function buildService(service: Service, cfg: ServiceEnvConfig): Pro
|
||||
return buildDir;
|
||||
}
|
||||
|
||||
export async function deployService(conn: any, service: Service, cfg: ServiceEnvConfig, buildDir: string): Promise<void> {
|
||||
export async function deployService(
|
||||
conn: any,
|
||||
service: Service,
|
||||
cfg: ServiceEnvConfig,
|
||||
buildDir: string,
|
||||
env: Environment,
|
||||
): Promise<void> {
|
||||
const deployer = deployers[service];
|
||||
if (!deployer) throw new Error(`未知服务: ${service}`);
|
||||
printInfo(`部署 ${service} 到 ${cfg.server.host}...`);
|
||||
await deployer.deploy(conn, cfg, buildDir);
|
||||
await deployer.deploy(conn, cfg, buildDir, env);
|
||||
}
|
||||
|
||||
/** 连接 SSH;密码登录成功后自动安装公钥并持久化到 config.json */
|
||||
@@ -59,7 +68,8 @@ export async function buildAndDeployServices(
|
||||
): Promise<void> {
|
||||
for (const service of services) {
|
||||
const config = await loadConfig();
|
||||
const cfg = getServiceConfig(config, service);
|
||||
const env = config.currentEnv;
|
||||
const cfg = getServiceConfig(config, service, env);
|
||||
console.clear();
|
||||
const buildDir = await buildService(service, cfg);
|
||||
|
||||
@@ -71,11 +81,12 @@ export async function buildAndDeployServices(
|
||||
|
||||
try {
|
||||
if (cfg.extractDir) {
|
||||
await deployService(conn, service, cfg, buildDir);
|
||||
await deployService(conn, service, cfg, buildDir, env);
|
||||
} else {
|
||||
await uploadComposeFile(conn, service, cfg);
|
||||
await deployService(conn, service, cfg, buildDir);
|
||||
await composeUp(conn, cfg, service);
|
||||
await uploadComposeFile(conn, service, cfg, env);
|
||||
await deployService(conn, service, cfg, buildDir, env);
|
||||
// 镜像重建后强制 recreate,否则 :latest 内容变了容器也不会换
|
||||
await composeDeploy(conn, cfg, service, env);
|
||||
}
|
||||
} finally {
|
||||
conn.end();
|
||||
@@ -86,35 +97,40 @@ export async function buildAndDeployServices(
|
||||
|
||||
export async function restartService(service: Service, onPassword?: () => Promise<string>): Promise<void> {
|
||||
const config = await loadConfig();
|
||||
const cfg = getServiceConfig(config, service);
|
||||
const env = config.currentEnv;
|
||||
const cfg = getServiceConfig(config, service, env);
|
||||
const conn = await connectForService(cfg, onPassword);
|
||||
try { await composeRestart(conn, cfg, service); } finally { conn.end(); }
|
||||
try { await composeRestart(conn, cfg, service, env); } finally { conn.end(); }
|
||||
}
|
||||
|
||||
export async function stopService(service: Service, onPassword?: () => Promise<string>): Promise<void> {
|
||||
const config = await loadConfig();
|
||||
const cfg = getServiceConfig(config, service);
|
||||
const env = config.currentEnv;
|
||||
const cfg = getServiceConfig(config, service, env);
|
||||
const conn = await connectForService(cfg, onPassword);
|
||||
try { await composeDown(conn, cfg, service); } finally { conn.end(); }
|
||||
try { await composeDown(conn, cfg, service, env); } finally { conn.end(); }
|
||||
}
|
||||
|
||||
export async function serviceLogs(service: Service, tail = 50, onPassword?: () => Promise<string>): Promise<string> {
|
||||
const config = await loadConfig();
|
||||
const cfg = getServiceConfig(config, service);
|
||||
const env = config.currentEnv;
|
||||
const cfg = getServiceConfig(config, service, env);
|
||||
const conn = await connectForService(cfg, onPassword);
|
||||
try { return await composeLogs(conn, cfg, service, tail); } finally { conn.end(); }
|
||||
try { return await composeLogs(conn, cfg, service, env, tail); } finally { conn.end(); }
|
||||
}
|
||||
|
||||
export async function serviceStatus(service: Service, onPassword?: () => Promise<string>): Promise<string> {
|
||||
const config = await loadConfig();
|
||||
const cfg = getServiceConfig(config, service);
|
||||
const env = config.currentEnv;
|
||||
const cfg = getServiceConfig(config, service, env);
|
||||
const conn = await connectForService(cfg, onPassword);
|
||||
try { return await composeStatus(conn, cfg); } finally { conn.end(); }
|
||||
try { return await composeStatus(conn, cfg, service, env); } finally { conn.end(); }
|
||||
}
|
||||
|
||||
export async function checkRemoteDocker(service: Service, onPassword?: () => Promise<string>): Promise<boolean> {
|
||||
const config = await loadConfig();
|
||||
const cfg = getServiceConfig(config, service);
|
||||
const env = config.currentEnv;
|
||||
const cfg = getServiceConfig(config, service, env);
|
||||
try {
|
||||
const conn = await connectForService(cfg, onPassword);
|
||||
try {
|
||||
|
||||
@@ -4,10 +4,11 @@ import { join } from 'path';
|
||||
|
||||
import { Client } from 'ssh2';
|
||||
import { getLicenseDir, getLicenseDeployDir } from '../config.js';
|
||||
import { copyBuildArtifacts, createTarGz, getLocalTempPath } from '../platform.js';
|
||||
import { execRemote, uploadFile, ensureRemoteDir } from '../ssh.js';
|
||||
import { remoteBuildImage } from '../docker.js';
|
||||
import { printInfo, printSuccess } from '../ui/render.js';
|
||||
import type { Service, ServiceEnvConfig } from '../types.js';
|
||||
import type { Environment, Service, ServiceEnvConfig } from '../types.js';
|
||||
|
||||
export const serviceType: Service = 'license';
|
||||
|
||||
@@ -20,39 +21,40 @@ export async function build(): Promise<string> {
|
||||
execSync('pnpm install && pnpm build', { stdio: 'inherit', cwd: serverDir });
|
||||
printSuccess('许可证构建完成');
|
||||
|
||||
const tmpDir = '/tmp/ecom-license-build';
|
||||
const tmpDir = getLocalTempPath('ecom-license-build');
|
||||
if (existsSync(tmpDir)) rmSync(tmpDir, { recursive: true });
|
||||
mkdirSync(tmpDir, { recursive: true });
|
||||
|
||||
execSync(`cp -r "${serverDir}/dist" "${tmpDir}/dist"`, { stdio: 'pipe' });
|
||||
execSync(`cp "${serverDir}/package.json" "${tmpDir}/"`, { stdio: 'pipe' });
|
||||
execSync(`cp "${serverDir}/pnpm-lock.yaml" "${tmpDir}/" 2>/dev/null || true`, { stdio: 'pipe' });
|
||||
if (existsSync(join(serverDir, 'keys'))) execSync(`cp -r "${serverDir}/keys" "${tmpDir}/keys"`, { stdio: 'pipe' });
|
||||
execSync(`cp "${serverDir}/.env" "${tmpDir}/.env" 2>/dev/null || true`, { stdio: 'pipe' });
|
||||
copyBuildArtifacts(join(serverDir, 'dist'), join(tmpDir, 'dist'));
|
||||
copyBuildArtifacts(join(serverDir, 'package.json'), join(tmpDir, 'package.json'));
|
||||
copyBuildArtifacts(join(serverDir, 'pnpm-lock.yaml'), join(tmpDir, 'pnpm-lock.yaml'), { optional: true });
|
||||
copyBuildArtifacts(join(serverDir, 'keys'), join(tmpDir, 'keys'), { optional: true });
|
||||
copyBuildArtifacts(join(serverDir, '.env'), join(tmpDir, '.env'), { optional: true });
|
||||
|
||||
return tmpDir;
|
||||
}
|
||||
|
||||
export async function deploy(conn: Client, cfg: ServiceEnvConfig, buildDir: string): Promise<void> {
|
||||
export async function deploy(conn: Client, cfg: ServiceEnvConfig, buildDir: string, env: Environment): Promise<void> {
|
||||
const serviceDir = `${cfg.server.deployPath}/license`;
|
||||
await ensureRemoteDir(conn, serviceDir);
|
||||
|
||||
const tmpTar = '/tmp/ecom-license-build.tar.gz';
|
||||
execSync(`tar -czf "${tmpTar}" -C "${buildDir}" .`, { stdio: 'pipe' });
|
||||
const tmpTar = getLocalTempPath('ecom-license-build.tar.gz');
|
||||
createTarGz(buildDir, tmpTar);
|
||||
|
||||
const dockerfileTmp = getLocalTempPath('ecom-license.Dockerfile');
|
||||
const dockerfileSrc = join(getLicenseDeployDir(), 'Dockerfile');
|
||||
if (!existsSync(dockerfileSrc)) {
|
||||
printInfo('许可证 deploy/Dockerfile 不存在,使用默认模板');
|
||||
writeFileSync('/tmp/ecom-license.Dockerfile', 'FROM node:22-alpine\nWORKDIR /app\nRUN addgroup -S app && adduser -S app -G app\nCOPY package.json pnpm-lock.yaml ./\nRUN corepack enable && pnpm install --prod --frozen-lockfile 2>/dev/null; exit 0\nCOPY dist ./dist\nCOPY keys ./keys\nCOPY .env ./.env\nRUN chown -R app:app /app\nUSER app\nEXPOSE 3100\nCMD ["node", "dist/main.js"]\n');
|
||||
writeFileSync(dockerfileTmp, 'FROM node:22-alpine\nWORKDIR /app\nRUN addgroup -S app && adduser -S app -G app\nCOPY package.json pnpm-lock.yaml ./\nRUN corepack enable && pnpm install --prod --frozen-lockfile 2>/dev/null; exit 0\nCOPY dist ./dist\nCOPY keys ./keys\nCOPY .env ./.env\nRUN chown -R app:app /app\nUSER app\nEXPOSE 3100\nCMD ["node", "dist/main.js"]\n');
|
||||
} else {
|
||||
writeFileSync('/tmp/ecom-license.Dockerfile', readFileSync(dockerfileSrc, 'utf8'));
|
||||
writeFileSync(dockerfileTmp, readFileSync(dockerfileSrc, 'utf8'));
|
||||
}
|
||||
|
||||
await uploadFile(conn, tmpTar, `${serviceDir}/build.tar.gz`);
|
||||
await uploadFile(conn, '/tmp/ecom-license.Dockerfile', `${serviceDir}/Dockerfile`);
|
||||
await uploadFile(conn, dockerfileTmp, `${serviceDir}/Dockerfile`);
|
||||
|
||||
const { code, stderr } = await execRemote(conn, `cd "${serviceDir}" && tar -xzf build.tar.gz && rm build.tar.gz`);
|
||||
if (code !== 0) throw new Error(`解压失败: ${stderr}`);
|
||||
|
||||
await remoteBuildImage(conn, 'license', serviceDir);
|
||||
await remoteBuildImage(conn, 'license', serviceDir, env);
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user