mirror of
https://gitee.com/qqtt-ah/ecom-dmb.git
synced 2026-11-24 03:19:18 +08:00
refacor: 重构目录架构
This commit is contained in:
@@ -0,0 +1,115 @@
|
||||
import { cpSync, existsSync, mkdirSync, readdirSync, rmSync } from 'fs';
|
||||
import { join } from 'path';
|
||||
|
||||
import { Client } from 'ssh2';
|
||||
import { getArtifactDir, getArtifactsRoot, getBackendDir } from './config.js';
|
||||
import { createTarGz, getLocalTempPath } from './platform.js';
|
||||
import { ensureRemoteDir, execRemote, uploadFile } from './ssh.js';
|
||||
import { printInfo } from './ui/render.js';
|
||||
import type { Service } from './types.js';
|
||||
|
||||
const ALL_SERVICES: Service[] = ['frontend', 'backend', 'license'];
|
||||
|
||||
/** 确保 artifacts 根目录及子目录存在 */
|
||||
export function ensureArtifactsDirs(): void {
|
||||
mkdirSync(getArtifactsRoot(), { recursive: true });
|
||||
for (const service of ALL_SERVICES) {
|
||||
mkdirSync(getArtifactDir(service), { recursive: true });
|
||||
}
|
||||
}
|
||||
|
||||
/** 清空并重建某服务的产物目录 */
|
||||
export function clearArtifactDir(service: Service): void {
|
||||
const dir = getArtifactDir(service);
|
||||
if (existsSync(dir)) rmSync(dir, { recursive: true });
|
||||
mkdirSync(dir, { recursive: true });
|
||||
}
|
||||
|
||||
/** 同步后端 JAR 与 static 到 artifacts/backend/ */
|
||||
export function syncBackendArtifact(jarPath: string): string {
|
||||
clearArtifactDir('backend');
|
||||
cpSync(jarPath, join(getArtifactDir('backend'), 'app.jar'));
|
||||
const staticSrc = join(getBackendDir(), 'src/main/resources/static');
|
||||
if (existsSync(staticSrc)) {
|
||||
cpSync(staticSrc, join(getArtifactDir('backend'), 'static'), { recursive: true });
|
||||
}
|
||||
return getArtifactDir('backend');
|
||||
}
|
||||
|
||||
/** 同步前端 dist 到 artifacts/frontend */
|
||||
export function syncFrontendArtifacts(distDir: string): string {
|
||||
clearArtifactDir('frontend');
|
||||
cpSync(distDir, getArtifactDir('frontend'), { recursive: true });
|
||||
return getArtifactDir('frontend');
|
||||
}
|
||||
|
||||
/** 同步许可证构建产物到 artifacts/license */
|
||||
export function syncLicenseArtifacts(srcDir: string): string {
|
||||
clearArtifactDir('license');
|
||||
cpSync(srcDir, getArtifactDir('license'), { recursive: true });
|
||||
return getArtifactDir('license');
|
||||
}
|
||||
|
||||
/** 部署前检查本地产物是否就绪 */
|
||||
export function assertArtifactsExist(service: Service): void {
|
||||
const dir = getArtifactDir(service);
|
||||
if (!existsSync(dir)) {
|
||||
throw new Error(`产物目录不存在: ${dir},请先执行「仅编译产物」`);
|
||||
}
|
||||
|
||||
if (service === 'backend') {
|
||||
if (!existsSync(join(dir, 'app.jar'))) {
|
||||
throw new Error(`缺少 ${join(dir, 'app.jar')},请先编译后端`);
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
const files = readdirSync(dir);
|
||||
if (files.length === 0) {
|
||||
throw new Error(`产物目录为空: ${dir},请先编译 ${service}`);
|
||||
}
|
||||
}
|
||||
|
||||
/** 打包并上传目录到远程 app 目录 */
|
||||
export async function uploadArtifactDirectory(
|
||||
conn: Client,
|
||||
localDir: string,
|
||||
remoteAppDir: string,
|
||||
): Promise<void> {
|
||||
await ensureRemoteDir(conn, remoteAppDir);
|
||||
const parentDir = remoteAppDir.replace(/\/app\/?$/, '');
|
||||
const tmpTar = getLocalTempPath(`ecom-upload-${Date.now()}.tar.gz`);
|
||||
const remoteTar = `${parentDir}/upload.tar.gz`;
|
||||
|
||||
printInfo(`上传产物到 ${remoteAppDir} ...`);
|
||||
createTarGz(localDir, tmpTar);
|
||||
await uploadFile(conn, tmpTar, remoteTar);
|
||||
|
||||
const { code, stderr } = await execRemote(
|
||||
conn,
|
||||
`mkdir -p "${remoteAppDir}" && rm -rf "${remoteAppDir}"/* && tar -xzf "${remoteTar}" -C "${remoteAppDir}" && rm -f "${remoteTar}"`,
|
||||
);
|
||||
if (code !== 0) throw new Error(`远程解压失败: ${stderr}`);
|
||||
}
|
||||
|
||||
/** 将本地目录打包解压到远程目录(合并,不清空目标) */
|
||||
export async function uploadDirectoryMerge(
|
||||
conn: Client,
|
||||
localDir: string,
|
||||
remoteDir: string,
|
||||
): Promise<void> {
|
||||
if (!existsSync(localDir)) return;
|
||||
await ensureRemoteDir(conn, remoteDir);
|
||||
const parentDir = remoteDir.replace(/\/+$/, '');
|
||||
const tmpTar = getLocalTempPath(`ecom-merge-${Date.now()}.tar.gz`);
|
||||
const remoteTar = `${parentDir}/merge-upload.tar.gz`;
|
||||
|
||||
createTarGz(localDir, tmpTar);
|
||||
await uploadFile(conn, tmpTar, remoteTar);
|
||||
|
||||
const { code, stderr } = await execRemote(
|
||||
conn,
|
||||
`mkdir -p "${remoteDir}" && tar -xzf "${remoteTar}" -C "${remoteDir}" && rm -f "${remoteTar}"`,
|
||||
);
|
||||
if (code !== 0) throw new Error(`远程合并解压失败: ${stderr}`);
|
||||
}
|
||||
@@ -0,0 +1,241 @@
|
||||
import { readFile, writeFile } from 'fs/promises';
|
||||
import { homedir } from 'os';
|
||||
import { dirname, join } from 'path';
|
||||
import { fileURLToPath } from 'url';
|
||||
|
||||
import type { DeployConfig, Environment, Service, ServiceEnvConfig, ServerConfig } from './types.js';
|
||||
|
||||
const __dirname = dirname(fileURLToPath(import.meta.url));
|
||||
const CONFIG_PATH = process.env.ECOM_DEPLOY_CONFIG || join(__dirname, '..', 'config.json');
|
||||
const ARTIFACTS_ROOT = join(__dirname, '..', 'artifacts');
|
||||
const SSH_KEY_PATH = join(homedir(), '.ssh', 'ecom-deploy');
|
||||
|
||||
export function getSshKeyPath(): string {
|
||||
return SSH_KEY_PATH;
|
||||
}
|
||||
|
||||
/** 远程统一根目录名:{deployPath}/ecom-dmb/{service}/{env} */
|
||||
export const REMOTE_APP_ROOT = 'ecom-dmb';
|
||||
|
||||
function defaultServiceConfig(host: string, port: number, options?: { staticDeploy?: boolean }): ServiceEnvConfig {
|
||||
return {
|
||||
server: { host, port: 22, username: 'root', deployPath: '/opt', authType: 'password' },
|
||||
port,
|
||||
...(options?.staticDeploy ? { staticDeploy: true } : {}),
|
||||
};
|
||||
}
|
||||
|
||||
function defaultConfig(): DeployConfig {
|
||||
return {
|
||||
currentEnv: 'test',
|
||||
services: {
|
||||
frontend: {
|
||||
test: defaultServiceConfig('192.168.1.100', 80, { staticDeploy: true }),
|
||||
pre: defaultServiceConfig('192.168.1.101', 80, { staticDeploy: true }),
|
||||
prod: defaultServiceConfig('frontend.prod.com', 80, { staticDeploy: true }),
|
||||
},
|
||||
backend: {
|
||||
test: { ...defaultServiceConfig('192.168.1.100', 8101), springProfile: 'test', dbUrl: '', redisUrl: '' },
|
||||
pre: { ...defaultServiceConfig('192.168.1.101', 8102), springProfile: 'pre', dbUrl: '', redisUrl: '' },
|
||||
prod: { ...defaultServiceConfig('backend.prod.com', 8103), springProfile: 'prod', dbUrl: '', redisUrl: '' },
|
||||
},
|
||||
license: {
|
||||
test: { ...defaultServiceConfig('192.168.1.100', 3100), nodeEnv: 'test', licenseDbUrl: '' },
|
||||
pre: { ...defaultServiceConfig('192.168.1.101', 3100), nodeEnv: 'pre', licenseDbUrl: '' },
|
||||
prod: { ...defaultServiceConfig('license.prod.com', 3100), nodeEnv: 'prod', licenseDbUrl: '' },
|
||||
},
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
export async function loadConfig(): Promise<DeployConfig> {
|
||||
try {
|
||||
const raw = await readFile(CONFIG_PATH, 'utf8');
|
||||
return JSON.parse(raw) as DeployConfig;
|
||||
} catch {
|
||||
const cfg = defaultConfig();
|
||||
await saveConfig(cfg);
|
||||
return cfg;
|
||||
}
|
||||
}
|
||||
|
||||
export async function saveConfig(config: DeployConfig): Promise<void> {
|
||||
await writeFile(CONFIG_PATH, JSON.stringify(config, null, 2), 'utf8');
|
||||
}
|
||||
|
||||
export function getServiceConfig(config: DeployConfig, service: Service, env?: Environment): ServiceEnvConfig {
|
||||
return config.services[service][env || config.currentEnv];
|
||||
}
|
||||
|
||||
export async function updateServiceServerConfig(
|
||||
service: Service,
|
||||
env: Environment,
|
||||
updates: Partial<ServerConfig>,
|
||||
): Promise<DeployConfig> {
|
||||
const config = await loadConfig();
|
||||
config.services[service][env].server = { ...config.services[service][env].server, ...updates };
|
||||
await saveConfig(config);
|
||||
return config;
|
||||
}
|
||||
|
||||
export async function updateServiceEnvConfig(
|
||||
service: Service,
|
||||
env: Environment,
|
||||
updates: Partial<ServiceEnvConfig>,
|
||||
): Promise<DeployConfig> {
|
||||
const config = await loadConfig();
|
||||
config.services[service][env] = { ...config.services[service][env], ...updates };
|
||||
await saveConfig(config);
|
||||
return config;
|
||||
}
|
||||
|
||||
export function getConfigPath(): string {
|
||||
return CONFIG_PATH;
|
||||
}
|
||||
|
||||
/** 本地编译产物根目录 ecom-deploy/artifacts */
|
||||
export function getArtifactsRoot(): string {
|
||||
return ARTIFACTS_ROOT;
|
||||
}
|
||||
|
||||
export function getArtifactDir(service: Service): string {
|
||||
return join(ARTIFACTS_ROOT, service);
|
||||
}
|
||||
|
||||
/** 规范化部署根目录(去掉末尾斜杠) */
|
||||
export function normalizeDeployRoot(deployPath: string): string {
|
||||
return deployPath.replace(/\/+$/, '') || '/';
|
||||
}
|
||||
|
||||
/**
|
||||
* 远程环境部署目录(后端 / 授权):
|
||||
* {deployPath}/ecom-dmb/{service}/{env}
|
||||
* 例:/opt/ecom-dmb/backend/test
|
||||
*/
|
||||
export function resolveEnvDeployDir(cfg: ServiceEnvConfig, service: Service, env: Environment): string {
|
||||
return `${normalizeDeployRoot(cfg.server.deployPath)}/${REMOTE_APP_ROOT}/${service}/${env}`;
|
||||
}
|
||||
|
||||
/**
|
||||
* 前端静态部署目录(按环境后缀区分,不走 service 子路径):
|
||||
* {deployPath}/ecom-dmb-{env}/index
|
||||
* 例:/opt/ecom-dmb-test/index
|
||||
*/
|
||||
export function resolveFrontendDeployDir(cfg: ServiceEnvConfig, env: Environment): string {
|
||||
return `${normalizeDeployRoot(cfg.server.deployPath)}/${REMOTE_APP_ROOT}-${env}`;
|
||||
}
|
||||
|
||||
export function resolveFrontendIndexDir(cfg: ServiceEnvConfig, env: Environment): string {
|
||||
return `${resolveFrontendDeployDir(cfg, env)}/index`;
|
||||
}
|
||||
|
||||
/** 展示用:解析服务实际部署路径 */
|
||||
export function resolveServiceDeployPath(cfg: ServiceEnvConfig, service: Service, env: Environment): string {
|
||||
if (service === 'frontend') {
|
||||
return resolveFrontendIndexDir(cfg, env);
|
||||
}
|
||||
return resolveEnvDeployDir(cfg, service, env);
|
||||
}
|
||||
|
||||
/** 远程服务目录(含 Dockerfile、compose、data),等价于环境部署目录 */
|
||||
export function getRemoteServiceDir(cfg: ServiceEnvConfig, service: Service, env: Environment): string {
|
||||
return resolveEnvDeployDir(cfg, service, env);
|
||||
}
|
||||
|
||||
/** 远程业务产物目录(宿主 app/,挂载到容器 /app) */
|
||||
export function getRemoteAppDir(cfg: ServiceEnvConfig, service: Service, env: Environment): string {
|
||||
return `${resolveEnvDeployDir(cfg, service, env)}/app`;
|
||||
}
|
||||
|
||||
/** @deprecated 使用 getRemoteAppDir */
|
||||
export function getRemoteDataDir(cfg: ServiceEnvConfig, service: Service, env: Environment): string {
|
||||
return getRemoteAppDir(cfg, service, env);
|
||||
}
|
||||
|
||||
/** 是否仅静态部署(不走 Docker),兼容旧字段 extractDir */
|
||||
export function isStaticDeploy(cfg: ServiceEnvConfig): boolean {
|
||||
return cfg.staticDeploy === true || Boolean(cfg.extractDir);
|
||||
}
|
||||
|
||||
/** 与 application-{profile}.yml 中 server.port 保持一致 */
|
||||
export function resolveBackendPort(env: Environment): number {
|
||||
switch (env) {
|
||||
case 'test':
|
||||
return 8101;
|
||||
case 'pre':
|
||||
return 8102;
|
||||
case 'prod':
|
||||
return 8103;
|
||||
}
|
||||
}
|
||||
|
||||
/** 部署环境 pre 对应 Spring profile pre(application-pre.yml) */
|
||||
export function resolveSpringProfile(profile?: string): string {
|
||||
return profile || 'prod';
|
||||
}
|
||||
|
||||
/** 部署环境后缀:test / pre / prod */
|
||||
export function resolveEnvSuffix(env: Environment): string {
|
||||
return env;
|
||||
}
|
||||
|
||||
/** Docker 镜像、容器、Compose 服务/项目名(含环境后缀) */
|
||||
export function getDockerResourceNames(service: Service, env: Environment) {
|
||||
const suffix = resolveEnvSuffix(env);
|
||||
const base = `ecom-${service}-${suffix}`;
|
||||
return {
|
||||
composeService: base,
|
||||
containerName: base,
|
||||
imageTag: `${base}:latest`,
|
||||
composeProject: base,
|
||||
};
|
||||
}
|
||||
|
||||
/** 同一 host+username 的服务共享 SSH 密钥配置 */
|
||||
export async function syncServerKeyAuth(
|
||||
host: string,
|
||||
username: string,
|
||||
updates: Partial<ServerConfig>,
|
||||
): Promise<DeployConfig> {
|
||||
const config = await loadConfig();
|
||||
for (const service of Object.keys(config.services) as Service[]) {
|
||||
for (const env of Object.keys(config.services[service]) as Environment[]) {
|
||||
const srv = config.services[service][env].server;
|
||||
if (srv.host === host && srv.username === username) {
|
||||
config.services[service][env].server = { ...srv, ...updates };
|
||||
}
|
||||
}
|
||||
}
|
||||
await saveConfig(config);
|
||||
return config;
|
||||
}
|
||||
|
||||
const PROJECT_ROOT = join(__dirname, '..', '..');
|
||||
|
||||
export function getFrontendDir(): string {
|
||||
return join(PROJECT_ROOT, 'ecom-dmb-frontend');
|
||||
}
|
||||
|
||||
export function getBackendDir(): string {
|
||||
return join(PROJECT_ROOT, 'ecom-dmb-backend');
|
||||
}
|
||||
|
||||
export function getLicenseDir(): string {
|
||||
return join(PROJECT_ROOT, 'ecom-license');
|
||||
}
|
||||
|
||||
function getProjectDeployDir(project: string): string {
|
||||
return join(PROJECT_ROOT, project, 'deploy');
|
||||
}
|
||||
|
||||
export function getFrontendDeployDir(): string {
|
||||
return getProjectDeployDir('ecom-dmb-frontend');
|
||||
}
|
||||
|
||||
export function getBackendDeployDir(): string {
|
||||
return getProjectDeployDir('ecom-dmb-backend');
|
||||
}
|
||||
|
||||
export function getLicenseDeployDir(): string {
|
||||
return getProjectDeployDir('ecom-license');
|
||||
}
|
||||
@@ -0,0 +1,87 @@
|
||||
import { execSync } from 'child_process';
|
||||
import { existsSync } from 'fs';
|
||||
import { join } from 'path';
|
||||
|
||||
import { Client } from 'ssh2';
|
||||
import { syncBackendArtifact, uploadDirectoryMerge } from '../artifacts.js';
|
||||
import {
|
||||
getArtifactDir,
|
||||
getBackendDir,
|
||||
getRemoteAppDir,
|
||||
resolveSpringProfile,
|
||||
} from '../config.js';
|
||||
import { findMainJar, resolveMavenCommand } from '../platform.js';
|
||||
import { ensureRemoteDir, execRemote, uploadFile } from '../ssh.js';
|
||||
import { printInfo, printSuccess } from '../ui/render.js';
|
||||
import type { Environment, Service, ServiceEnvConfig } from '../types.js';
|
||||
|
||||
export const serviceType: Service = 'backend';
|
||||
|
||||
export async function build(_cfg: ServiceEnvConfig): Promise<string> {
|
||||
const backendDir = getBackendDir();
|
||||
if (!existsSync(backendDir)) throw new Error(`后端项目目录不存在: ${backendDir}`);
|
||||
|
||||
const mvnCmd = resolveMavenCommand(backendDir);
|
||||
|
||||
printInfo('构建后端 (Maven)...');
|
||||
execSync(`${mvnCmd} clean package -DskipTests`, {
|
||||
stdio: 'inherit',
|
||||
cwd: backendDir,
|
||||
shell: process.platform === 'win32' ? (process.env.COMSPEC || 'cmd.exe') : undefined,
|
||||
});
|
||||
|
||||
const jarPath = findMainJar(join(backendDir, 'target'));
|
||||
const artifactDir = syncBackendArtifact(jarPath);
|
||||
printSuccess(`后端构建完成,产物: ${artifactDir}/app.jar`);
|
||||
return artifactDir;
|
||||
}
|
||||
|
||||
/** 远程尚无文件时初始化环境 yml(app 根目录)与 config/ 下的 license 相关文件 */
|
||||
async function seedRemoteConfigIfMissing(
|
||||
conn: Client,
|
||||
cfg: ServiceEnvConfig,
|
||||
remoteAppDir: string,
|
||||
): Promise<void> {
|
||||
const profile = resolveSpringProfile(cfg.springProfile);
|
||||
const backendDir = getBackendDir();
|
||||
const envYml = `application-${profile}.yml`;
|
||||
const seeds: { local: string; remote: string }[] = [
|
||||
{
|
||||
local: join(backendDir, 'src/main/resources', envYml),
|
||||
remote: `${remoteAppDir}/${envYml}`,
|
||||
},
|
||||
{
|
||||
local: join(backendDir, 'src/main/resources/config/channel-pdd.yml'),
|
||||
remote: `${remoteAppDir}/config/channel-pdd.yml`,
|
||||
},
|
||||
];
|
||||
|
||||
await ensureRemoteDir(conn, `${remoteAppDir}/config`);
|
||||
for (const { local, remote } of seeds) {
|
||||
if (!existsSync(local)) continue;
|
||||
const { code } = await execRemote(conn, `test -f "${remote}"`);
|
||||
if (code === 0) continue;
|
||||
await uploadFile(conn, local, remote);
|
||||
printInfo(`已初始化配置(仅首次): ${remote}`);
|
||||
}
|
||||
}
|
||||
|
||||
/** 上传 artifacts/backend 到远程 app/(jar + static;config/uploads 保留宿主机数据) */
|
||||
export async function deploy(conn: Client, cfg: ServiceEnvConfig, _buildDir: string, env: Environment): Promise<void> {
|
||||
const artifactDir = getArtifactDir('backend');
|
||||
const remoteAppDir = getRemoteAppDir(cfg, 'backend', env);
|
||||
|
||||
await ensureRemoteDir(conn, remoteAppDir);
|
||||
await ensureRemoteDir(conn, `${remoteAppDir}/uploads`);
|
||||
await seedRemoteConfigIfMissing(conn, cfg, remoteAppDir);
|
||||
|
||||
await uploadFile(conn, join(artifactDir, 'app.jar'), `${remoteAppDir}/app.jar`);
|
||||
|
||||
const localStatic = join(artifactDir, 'static');
|
||||
if (existsSync(localStatic)) {
|
||||
printInfo('同步 static/ 到远程(合并,不删除 uploads/ 与宿主机配置)...');
|
||||
await uploadDirectoryMerge(conn, localStatic, `${remoteAppDir}/static`);
|
||||
}
|
||||
|
||||
printSuccess(`后端产物已上传到 ${remoteAppDir}`);
|
||||
}
|
||||
@@ -0,0 +1,51 @@
|
||||
import { execSync } from 'child_process';
|
||||
import { existsSync } from 'fs';
|
||||
import { join } from 'path';
|
||||
|
||||
import { Client } from 'ssh2';
|
||||
import { syncFrontendArtifacts } from '../artifacts.js';
|
||||
import { getArtifactDir, getFrontendDir, resolveFrontendDeployDir, resolveFrontendIndexDir } 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 { Environment, Service, ServiceEnvConfig } from '../types.js';
|
||||
|
||||
export const serviceType: Service = 'frontend';
|
||||
|
||||
export async function build(): Promise<string> {
|
||||
const frontendDir = getFrontendDir();
|
||||
if (!existsSync(frontendDir)) throw new Error(`前端项目目录不存在: ${frontendDir}`);
|
||||
|
||||
printInfo('构建前端...');
|
||||
execSync('pnpm install && pnpm build', { stdio: 'inherit', cwd: frontendDir });
|
||||
printSuccess('前端构建完成');
|
||||
|
||||
const distDir = join(frontendDir, 'apps', 'web-antd', 'dist');
|
||||
if (!existsSync(distDir)) throw new Error(`构建产物目录不存在: ${distDir}`);
|
||||
|
||||
const artifactDir = syncFrontendArtifacts(distDir);
|
||||
printSuccess(`前端产物: ${artifactDir}`);
|
||||
return artifactDir;
|
||||
}
|
||||
|
||||
/**
|
||||
* 上传静态产物到 {deployPath}/ecom-dmb-{env}/index/
|
||||
* 例:/opt/ecom-dmb-test/index
|
||||
*/
|
||||
export async function deploy(conn: Client, cfg: ServiceEnvConfig, _buildDir: string, env: Environment): Promise<void> {
|
||||
const buildDir = getArtifactDir('frontend');
|
||||
const siteDir = resolveFrontendDeployDir(cfg, env);
|
||||
const indexDir = resolveFrontendIndexDir(cfg, env);
|
||||
await ensureRemoteDir(conn, siteDir);
|
||||
|
||||
const tmpTar = getLocalTempPath('ecom-frontend-build.tar.gz');
|
||||
createTarGz(buildDir, tmpTar);
|
||||
await uploadFile(conn, tmpTar, `${siteDir}/frontend.tar.gz`);
|
||||
|
||||
const { code, stderr } = await execRemote(
|
||||
conn,
|
||||
`cd "${siteDir}" && rm -rf index && mkdir index && tar -xzf frontend.tar.gz -C index && rm frontend.tar.gz`,
|
||||
);
|
||||
if (code !== 0) throw new Error(`解压失败: ${stderr}`);
|
||||
printSuccess(`前端文件已部署到 ${indexDir}`);
|
||||
}
|
||||
@@ -0,0 +1,209 @@
|
||||
import { connectWithRetry, installKeyAfterPasswordAuth, execRemote } from '../ssh.js';
|
||||
import {
|
||||
composeRestartAfterUpload,
|
||||
initServiceRuntime,
|
||||
remoteImageExists,
|
||||
uploadComposeFile,
|
||||
composeRestart,
|
||||
composeLogs,
|
||||
composeStatus,
|
||||
composeDown,
|
||||
} from '../docker.js';
|
||||
import { assertArtifactsExist, ensureArtifactsDirs } from '../artifacts.js';
|
||||
import { getArtifactDir, loadConfig, getServiceConfig, syncServerKeyAuth, isStaticDeploy } from '../config.js';
|
||||
import { printError, printInfo, printSuccess } from '../ui/render.js';
|
||||
import type { Environment, Service, ServiceEnvConfig } from '../types.js';
|
||||
|
||||
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, env: Environment) => Promise<void>;
|
||||
}> = {
|
||||
frontend: frontendDeploy as any,
|
||||
backend: backendDeploy as any,
|
||||
license: licenseDeploy as any,
|
||||
};
|
||||
|
||||
export async function buildService(service: Service, cfg: ServiceEnvConfig): Promise<string> {
|
||||
ensureArtifactsDirs();
|
||||
const deployer = deployers[service];
|
||||
if (!deployer) throw new Error(`未知服务: ${service}`);
|
||||
printInfo(`构建 ${service}...`);
|
||||
const buildDir = await deployer.build(cfg);
|
||||
printSuccess(`${service} 构建完成 → ${getArtifactDir(service)}`);
|
||||
return buildDir;
|
||||
}
|
||||
|
||||
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, env);
|
||||
}
|
||||
|
||||
/** 连接 SSH;密码登录成功后自动安装公钥 */
|
||||
async function connectForService(
|
||||
cfg: ServiceEnvConfig,
|
||||
onPassword?: () => Promise<string>,
|
||||
): Promise<any> {
|
||||
const { conn, authMethod } = await connectWithRetry(cfg.server, undefined, onPassword);
|
||||
|
||||
if (authMethod === 'password') {
|
||||
printInfo('首次密码登录成功,正在配置 SSH 密钥免密...');
|
||||
const keyPath = await installKeyAfterPasswordAuth(conn, cfg.server);
|
||||
await syncServerKeyAuth(cfg.server.host, cfg.server.username, {
|
||||
authType: 'key',
|
||||
keyPath,
|
||||
lastPassword: undefined,
|
||||
});
|
||||
cfg.server.authType = 'key';
|
||||
cfg.server.keyPath = keyPath;
|
||||
printSuccess(`已配置免密登录 (${cfg.server.host}),后续部署不再询问密码`);
|
||||
}
|
||||
|
||||
return conn;
|
||||
}
|
||||
|
||||
/** Docker 服务:上传产物后,首次 init 镜像,后续仅重启 */
|
||||
async function finishDockerDeploy(conn: any, service: Service, cfg: ServiceEnvConfig, env: Environment): Promise<void> {
|
||||
const exists = await remoteImageExists(conn, service, env);
|
||||
if (!exists) {
|
||||
await initServiceRuntime(conn, service, cfg, env);
|
||||
} else {
|
||||
await uploadComposeFile(conn, service, cfg, env);
|
||||
await composeRestartAfterUpload(conn, cfg, service, env);
|
||||
}
|
||||
}
|
||||
|
||||
/** 仅编译到 artifacts/,不上传 */
|
||||
export async function buildServicesOnly(services: Service[]): Promise<void> {
|
||||
ensureArtifactsDirs();
|
||||
for (const service of services) {
|
||||
const config = await loadConfig();
|
||||
const cfg = getServiceConfig(config, service);
|
||||
console.clear();
|
||||
await buildService(service, cfg);
|
||||
}
|
||||
}
|
||||
|
||||
/** 从 artifacts/ 上传并重启(不编译) */
|
||||
export async function deployArtifactsOnly(
|
||||
services: Service[],
|
||||
onPassword?: (service: Service) => Promise<string>,
|
||||
): Promise<void> {
|
||||
ensureArtifactsDirs();
|
||||
for (const service of services) {
|
||||
assertArtifactsExist(service);
|
||||
const config = await loadConfig();
|
||||
const env = config.currentEnv;
|
||||
const cfg = getServiceConfig(config, service, env);
|
||||
console.clear();
|
||||
|
||||
const conn = await connectForService(
|
||||
cfg,
|
||||
onPassword ? () => onPassword(service) : undefined,
|
||||
);
|
||||
|
||||
try {
|
||||
if (isStaticDeploy(cfg)) {
|
||||
await deployService(conn, service, cfg, getArtifactDir(service), env);
|
||||
} else {
|
||||
await deployService(conn, service, cfg, getArtifactDir(service), env);
|
||||
await finishDockerDeploy(conn, service, cfg, env);
|
||||
}
|
||||
} finally {
|
||||
conn.end();
|
||||
}
|
||||
printSuccess(`${service} 产物已上传并重启`);
|
||||
}
|
||||
}
|
||||
|
||||
/** 自动部署:编译 → 上传 → 重启(不重建镜像) */
|
||||
export async function buildAndDeployServices(
|
||||
services: Service[],
|
||||
onPassword?: (service: Service) => Promise<string>,
|
||||
): Promise<void> {
|
||||
ensureArtifactsDirs();
|
||||
for (const service of services) {
|
||||
const config = await loadConfig();
|
||||
const env = config.currentEnv;
|
||||
const cfg = getServiceConfig(config, service, env);
|
||||
console.clear();
|
||||
await buildService(service, cfg);
|
||||
|
||||
const conn = await connectForService(
|
||||
cfg,
|
||||
onPassword ? () => onPassword(service) : undefined,
|
||||
);
|
||||
|
||||
try {
|
||||
if (isStaticDeploy(cfg)) {
|
||||
await deployService(conn, service, cfg, getArtifactDir(service), env);
|
||||
} else {
|
||||
await deployService(conn, service, cfg, getArtifactDir(service), env);
|
||||
await finishDockerDeploy(conn, service, cfg, env);
|
||||
}
|
||||
} finally {
|
||||
conn.end();
|
||||
}
|
||||
printSuccess(`${service} 部署完成`);
|
||||
}
|
||||
}
|
||||
|
||||
export async function restartService(service: Service, onPassword?: () => Promise<string>): Promise<void> {
|
||||
const config = await loadConfig();
|
||||
const env = config.currentEnv;
|
||||
const cfg = getServiceConfig(config, service, env);
|
||||
const conn = await connectForService(cfg, onPassword);
|
||||
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 env = config.currentEnv;
|
||||
const cfg = getServiceConfig(config, service, env);
|
||||
const conn = await connectForService(cfg, onPassword);
|
||||
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 env = config.currentEnv;
|
||||
const cfg = getServiceConfig(config, service, env);
|
||||
const conn = await connectForService(cfg, onPassword);
|
||||
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 env = config.currentEnv;
|
||||
const cfg = getServiceConfig(config, service, env);
|
||||
const conn = await connectForService(cfg, onPassword);
|
||||
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 env = config.currentEnv;
|
||||
const cfg = getServiceConfig(config, service, env);
|
||||
try {
|
||||
const conn = await connectForService(cfg, onPassword);
|
||||
try {
|
||||
const { stdout } = await execRemote(conn, 'docker --version && docker compose version');
|
||||
printInfo(stdout.trim());
|
||||
return true;
|
||||
} finally { conn.end(); }
|
||||
} catch (e: any) {
|
||||
printError(`Docker 检查失败: ${e.message}`);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,56 @@
|
||||
import { execSync } from 'child_process';
|
||||
import { existsSync, mkdirSync, rmSync } from 'fs';
|
||||
import { join } from 'path';
|
||||
|
||||
import { Client } from 'ssh2';
|
||||
import { syncLicenseArtifacts, uploadArtifactDirectory } from '../artifacts.js';
|
||||
import { getArtifactDir, getLicenseDir, getRemoteAppDir } from '../config.js';
|
||||
import { copyBuildArtifacts, getLocalTempPath } from '../platform.js';
|
||||
import { ensureRemoteDir } from '../ssh.js';
|
||||
import { printInfo, printSuccess } from '../ui/render.js';
|
||||
import type { Environment, Service, ServiceEnvConfig } from '../types.js';
|
||||
|
||||
export const serviceType: Service = 'license';
|
||||
|
||||
export async function build(): Promise<string> {
|
||||
const licenseDir = getLicenseDir();
|
||||
const serverDir = join(licenseDir, 'server');
|
||||
if (!existsSync(serverDir)) throw new Error(`许可证项目目录不存在: ${serverDir}`);
|
||||
|
||||
printInfo('构建许可证 (NestJS)...');
|
||||
execSync('pnpm install && pnpm build', { stdio: 'inherit', cwd: serverDir });
|
||||
|
||||
// 先收集到临时目录,再同步到 artifacts/license
|
||||
const tmpDir = getLocalTempPath('ecom-license-build');
|
||||
if (existsSync(tmpDir)) rmSync(tmpDir, { recursive: true });
|
||||
mkdirSync(tmpDir, { recursive: true });
|
||||
|
||||
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 });
|
||||
|
||||
const artifactDir = syncLicenseArtifacts(tmpDir);
|
||||
rmSync(tmpDir, { recursive: true, force: true });
|
||||
|
||||
// 本地安装生产依赖,一并打入产物目录
|
||||
printInfo('安装许可证生产依赖...');
|
||||
execSync('corepack enable && pnpm install --prod --frozen-lockfile', {
|
||||
stdio: 'inherit',
|
||||
cwd: artifactDir,
|
||||
shell: process.platform === 'win32' ? (process.env.COMSPEC || 'cmd.exe') : undefined,
|
||||
});
|
||||
|
||||
printSuccess(`许可证构建完成,产物: ${artifactDir}`);
|
||||
return artifactDir;
|
||||
}
|
||||
|
||||
/** 上传 artifacts/license 到远程挂载目录 */
|
||||
export async function deploy(conn: Client, cfg: ServiceEnvConfig, _buildDir: string, env: Environment): Promise<void> {
|
||||
const artifactDir = getArtifactDir('license');
|
||||
const remoteAppDir = getRemoteAppDir(cfg, 'license', env);
|
||||
await ensureRemoteDir(conn, remoteAppDir);
|
||||
await uploadArtifactDirectory(conn, artifactDir, remoteAppDir);
|
||||
printSuccess(`许可证产物已上传到 ${remoteAppDir}`);
|
||||
}
|
||||
@@ -0,0 +1,252 @@
|
||||
import { readFileSync, writeFileSync } from 'fs';
|
||||
import { join } from 'path';
|
||||
|
||||
import { Client } from 'ssh2';
|
||||
import {
|
||||
getBackendDeployDir,
|
||||
getDockerResourceNames,
|
||||
getLicenseDeployDir,
|
||||
getRemoteServiceDir,
|
||||
resolveBackendPort,
|
||||
resolveEnvDeployDir,
|
||||
resolveSpringProfile,
|
||||
} from './config.js';
|
||||
import { getLocalTempPath } from './platform.js';
|
||||
import { execRemote, ensureRemoteDir, uploadFile } from './ssh.js';
|
||||
import { printInfo, printSuccess } from './ui/render.js';
|
||||
import type { Environment, Service, ServiceEnvConfig } from './types.js';
|
||||
|
||||
/** 远程 compose 命令前缀(工作目录为环境部署目录) */
|
||||
function composeCmd(cfg: ServiceEnvConfig, env: Environment, service: Service): string {
|
||||
const { composeProject } = getDockerResourceNames(service, env);
|
||||
const envDir = resolveEnvDeployDir(cfg, service, env);
|
||||
return `cd "${envDir}" && docker compose -p ${composeProject}`;
|
||||
}
|
||||
|
||||
/** 桥接模式端口 */
|
||||
function resolveBridgePorts(service: Service, cfg: ServiceEnvConfig, env: Environment): { hostPort: number; containerPort: number } {
|
||||
if (service === 'backend') {
|
||||
const port = resolveBackendPort(env);
|
||||
return { hostPort: port, containerPort: port };
|
||||
}
|
||||
return { hostPort: cfg.port, containerPort: cfg.port };
|
||||
}
|
||||
|
||||
function backendComposeVolumes(profile: string): string {
|
||||
return [
|
||||
' - ./app/app.jar:/app/app.jar:ro',
|
||||
` - ./app/application-${profile}.yml:/app/application-${profile}.yml:ro`,
|
||||
' - ./app/config:/app/config:ro',
|
||||
' - ./app/uploads:/app/uploads:rw',
|
||||
' - ./app/static:/app/static:ro',
|
||||
].join('\n');
|
||||
}
|
||||
|
||||
export function generateComposeFile(service: Service, cfg: ServiceEnvConfig, env: Environment): string {
|
||||
const { composeService, containerName, imageTag } = getDockerResourceNames(service, env);
|
||||
const { hostPort, containerPort } = resolveBridgePorts(service, cfg, env);
|
||||
|
||||
let envBlock = '';
|
||||
if (service === 'frontend') {
|
||||
envBlock = ` - NGINX_PORT=${containerPort}`;
|
||||
} else if (service === 'backend') {
|
||||
envBlock = [
|
||||
` - SPRING_PROFILES_ACTIVE=${resolveSpringProfile(cfg.springProfile)}`,
|
||||
cfg.dbUrl ? ` - DB_URL=${cfg.dbUrl}` : '',
|
||||
cfg.redisUrl ? ` - REDIS_URL=${cfg.redisUrl}` : '',
|
||||
].filter(Boolean).join('\n');
|
||||
} else if (service === 'license') {
|
||||
envBlock = [
|
||||
` - NODE_ENV=${cfg.nodeEnv || 'prod'}`,
|
||||
` - PORT=${containerPort}`,
|
||||
cfg.licenseDbUrl ? ` - DB_URL=${cfg.licenseDbUrl}` : '',
|
||||
].filter(Boolean).join('\n');
|
||||
}
|
||||
|
||||
const volumeBlock = service === 'backend'
|
||||
? backendComposeVolumes(resolveSpringProfile(cfg.springProfile))
|
||||
: ' - ./app:/app:ro';
|
||||
|
||||
return `services:
|
||||
${composeService}:
|
||||
image: ${imageTag}
|
||||
container_name: ${containerName}
|
||||
pull_policy: never
|
||||
ports:
|
||||
- "${hostPort}:${containerPort}"
|
||||
volumes:
|
||||
${volumeBlock}
|
||||
environment:
|
||||
${envBlock}
|
||||
restart: unless-stopped
|
||||
networks:
|
||||
- default
|
||||
logging:
|
||||
driver: "json-file"
|
||||
options:
|
||||
max-size: "10m"
|
||||
max-file: "3"
|
||||
|
||||
networks:
|
||||
default:
|
||||
driver: bridge
|
||||
`;
|
||||
}
|
||||
|
||||
/** 读取运行时 Dockerfile 内容 */
|
||||
function readRuntimeDockerfile(service: Service): string {
|
||||
const dockerfileSrc = service === 'backend'
|
||||
? join(getBackendDeployDir(), 'Dockerfile')
|
||||
: join(getLicenseDeployDir(), 'Dockerfile');
|
||||
return readFileSync(dockerfileSrc, 'utf8');
|
||||
}
|
||||
|
||||
/** 上传运行时 Dockerfile 到远程环境目录 */
|
||||
export async function uploadRuntimeDockerfile(
|
||||
conn: Client,
|
||||
service: Service,
|
||||
cfg: ServiceEnvConfig,
|
||||
env: Environment,
|
||||
): Promise<void> {
|
||||
const serviceDir = getRemoteServiceDir(cfg, service, env);
|
||||
await ensureRemoteDir(conn, serviceDir);
|
||||
const tmp = getLocalTempPath(`ecom-${service}-Dockerfile`);
|
||||
writeFileSync(tmp, readRuntimeDockerfile(service), 'utf8');
|
||||
await uploadFile(conn, tmp, `${serviceDir}/Dockerfile`);
|
||||
}
|
||||
|
||||
/** 检查远程运行时镜像是否已存在 */
|
||||
export async function remoteImageExists(conn: Client, service: Service, env: Environment): Promise<boolean> {
|
||||
const { imageTag } = getDockerResourceNames(service, env);
|
||||
const { code } = await execRemote(conn, `docker image inspect ${imageTag} >/dev/null 2>&1`);
|
||||
return code === 0;
|
||||
}
|
||||
|
||||
/** 首次初始化:构建运行时镜像(不含业务代码) */
|
||||
export async function remoteBuildRuntimeImage(
|
||||
conn: Client,
|
||||
service: Service,
|
||||
cfg: ServiceEnvConfig,
|
||||
env: Environment,
|
||||
): Promise<void> {
|
||||
const { imageTag } = getDockerResourceNames(service, env);
|
||||
const serviceDir = getRemoteServiceDir(cfg, service, env);
|
||||
const { code, stdout, stderr } = await execRemote(
|
||||
conn,
|
||||
`cd "${serviceDir}" && docker build -t ${imageTag} . 2>&1`,
|
||||
);
|
||||
if (code !== 0) {
|
||||
throw new Error(`${service} 运行时镜像构建失败:\n${stdout || stderr}`);
|
||||
}
|
||||
printSuccess(`${service} 运行时镜像已构建 (${imageTag})`);
|
||||
}
|
||||
|
||||
export async function uploadComposeFile(
|
||||
conn: Client,
|
||||
service: Service,
|
||||
cfg: ServiceEnvConfig,
|
||||
env: Environment,
|
||||
): Promise<void> {
|
||||
const envDir = resolveEnvDeployDir(cfg, service, env);
|
||||
const tmpCompose = getLocalTempPath(`ecom-${service}-${env}-docker-compose.yml`);
|
||||
writeFileSync(tmpCompose, generateComposeFile(service, cfg, env), 'utf8');
|
||||
await ensureRemoteDir(conn, envDir);
|
||||
await uploadFile(conn, tmpCompose, `${envDir}/docker-compose.yml`);
|
||||
}
|
||||
|
||||
/** 首次启动容器 */
|
||||
export async function composeUp(conn: Client, cfg: ServiceEnvConfig, service: Service, env: Environment): Promise<void> {
|
||||
const { composeService } = getDockerResourceNames(service, env);
|
||||
const { code, stdout, stderr } = await execRemote(
|
||||
conn,
|
||||
`${composeCmd(cfg, env, service)} up -d ${composeService} 2>&1`,
|
||||
);
|
||||
if (code !== 0) {
|
||||
throw new Error(`${service} 启动失败:\n${stdout || stderr}`);
|
||||
}
|
||||
printSuccess(`${composeService} 已启动`);
|
||||
}
|
||||
|
||||
/** 更新部署:上传产物后重启容器(不重建镜像) */
|
||||
export async function composeRestartAfterUpload(
|
||||
conn: Client,
|
||||
cfg: ServiceEnvConfig,
|
||||
service: Service,
|
||||
env: Environment,
|
||||
): Promise<void> {
|
||||
const { composeService, containerName } = getDockerResourceNames(service, env);
|
||||
const { stdout: psOut } = await execRemote(conn, `docker ps -q -f name=^/${containerName}$`);
|
||||
const running = psOut.trim().length > 0;
|
||||
|
||||
if (running) {
|
||||
const cmd = composeCmd(cfg, env, service);
|
||||
const upCmd = `${cmd} up -d ${composeService} 2>&1`;
|
||||
const { code, stdout, stderr } = await execRemote(conn, upCmd);
|
||||
if (code !== 0) throw new Error(`${service} 应用 compose 失败:\n${stdout || stderr}`);
|
||||
// 仅 up -d 不会 reload 挂载的 app.jar;必须 restart 后 JVM 才读新包
|
||||
const restartCmd = `${cmd} restart ${composeService} 2>&1`;
|
||||
const restarted = await execRemote(conn, restartCmd);
|
||||
if (restarted.code !== 0) {
|
||||
throw new Error(`${service} 重启失败:\n${restarted.stdout || restarted.stderr}`);
|
||||
}
|
||||
printSuccess(`${composeService} 已更新配置并重启`);
|
||||
return;
|
||||
}
|
||||
|
||||
printInfo(`${composeService} 未运行,正在启动...`);
|
||||
await composeUp(conn, cfg, service, env);
|
||||
}
|
||||
|
||||
/** 首次初始化运行时环境:Dockerfile + 镜像 + compose */
|
||||
export async function initServiceRuntime(
|
||||
conn: Client,
|
||||
service: Service,
|
||||
cfg: ServiceEnvConfig,
|
||||
env: Environment,
|
||||
): Promise<void> {
|
||||
printInfo(`${service} 首次部署,初始化运行时镜像...`);
|
||||
await uploadRuntimeDockerfile(conn, service, cfg, env);
|
||||
await uploadComposeFile(conn, service, cfg, env);
|
||||
await remoteBuildRuntimeImage(conn, service, cfg, env);
|
||||
await composeUp(conn, cfg, service, env);
|
||||
}
|
||||
|
||||
export async function composeDown(
|
||||
conn: Client,
|
||||
cfg: ServiceEnvConfig,
|
||||
service: Service,
|
||||
env: Environment,
|
||||
): Promise<void> {
|
||||
const { composeService } = getDockerResourceNames(service, env);
|
||||
await execRemote(conn, `${composeCmd(cfg, env, service)} down ${composeService}`);
|
||||
printSuccess(`${composeService} 已停止`);
|
||||
}
|
||||
|
||||
export async function composeRestart(
|
||||
conn: Client,
|
||||
cfg: ServiceEnvConfig,
|
||||
service: Service,
|
||||
env: Environment,
|
||||
): Promise<void> {
|
||||
await composeRestartAfterUpload(conn, cfg, service, env);
|
||||
}
|
||||
|
||||
export async function composeLogs(
|
||||
conn: Client,
|
||||
cfg: ServiceEnvConfig,
|
||||
service: Service,
|
||||
env: Environment,
|
||||
tail = 50,
|
||||
): Promise<string> {
|
||||
const { composeService } = getDockerResourceNames(service, env);
|
||||
const { stdout } = await execRemote(
|
||||
conn,
|
||||
`${composeCmd(cfg, env, service)} logs --tail=${tail} ${composeService}`,
|
||||
);
|
||||
return stdout;
|
||||
}
|
||||
|
||||
export async function composeStatus(conn: Client, cfg: ServiceEnvConfig, service: Service, env: Environment): Promise<string> {
|
||||
const { stdout } = await execRemote(conn, `${composeCmd(cfg, env, service)} ps`);
|
||||
return stdout;
|
||||
}
|
||||
@@ -0,0 +1,357 @@
|
||||
#!/usr/bin/env node
|
||||
import { input, password as pwPrompt, select } from '@inquirer/prompts';
|
||||
|
||||
import { loadConfig, saveConfig, updateServiceServerConfig, getServiceConfig, getSshKeyPath, syncServerKeyAuth, resolveServiceDeployPath } from './config.js';
|
||||
import {
|
||||
buildAndDeployServices,
|
||||
buildServicesOnly,
|
||||
deployArtifactsOnly,
|
||||
checkRemoteDocker,
|
||||
restartService,
|
||||
serviceLogs,
|
||||
serviceStatus,
|
||||
stopService,
|
||||
} from './deploy/index.js';
|
||||
import { getArtifactsRoot } from './config.js';
|
||||
import { ensureKeyPair, setupSSHKey, testConnection } from './ssh.js';
|
||||
import { printBanner, printBox, printError, printInfo, printSuccess } from './ui/render.js';
|
||||
import { ENV_LABELS, SERVICE_LABELS } from './types.js';
|
||||
import type { Environment, Service } from './types.js';
|
||||
|
||||
async function pause() {
|
||||
await input({ message: '按 Enter 返回' });
|
||||
}
|
||||
|
||||
async function selectEnv(): Promise<Environment> {
|
||||
const config = await loadConfig();
|
||||
const env = await select({
|
||||
message: '选择环境',
|
||||
choices: (['test', 'pre', 'prod'] as Environment[]).map((e) => ({
|
||||
name: `${e === config.currentEnv ? '● ' : ' '}${ENV_LABELS[e]}`,
|
||||
value: e,
|
||||
})),
|
||||
});
|
||||
config.currentEnv = env;
|
||||
await saveConfig(config);
|
||||
return env;
|
||||
}
|
||||
|
||||
async function selectService(): Promise<Service> {
|
||||
return await select({
|
||||
message: '选择服务',
|
||||
choices: [
|
||||
{ name: '前端', value: 'frontend' },
|
||||
{ name: '后端', value: 'backend' },
|
||||
{ name: '许可证服务', value: 'license' },
|
||||
],
|
||||
}) as Service;
|
||||
}
|
||||
|
||||
async function selectServices(): Promise<Service[]> {
|
||||
const selected = await select({
|
||||
message: '选择服务',
|
||||
choices: [
|
||||
{ name: '全部服务', value: 'all' as any },
|
||||
{ name: '前端', value: 'frontend' },
|
||||
{ name: '后端', value: 'backend' },
|
||||
{ name: '许可证服务', value: 'license' },
|
||||
],
|
||||
});
|
||||
if (selected === 'all') return ['frontend', 'backend', 'license'];
|
||||
return [selected as Service];
|
||||
}
|
||||
|
||||
function showServiceHosts(config: Awaited<ReturnType<typeof loadConfig>>): string {
|
||||
const env = config.currentEnv;
|
||||
const services: Service[] = ['frontend', 'backend', 'license'];
|
||||
return services.map((s) => {
|
||||
const cfg = config.services[s][env];
|
||||
const resolved = resolveServiceDeployPath(cfg, s, env);
|
||||
return ` ${SERVICE_LABELS[s]}: ${cfg.server.host} → ${resolved}`;
|
||||
}).join('\n');
|
||||
}
|
||||
|
||||
async function configureService() {
|
||||
const config = await loadConfig();
|
||||
const service = await selectService();
|
||||
const env = await selectEnv();
|
||||
const cfg = config.services[service][env];
|
||||
const srv = cfg.server;
|
||||
|
||||
console.clear();
|
||||
printBox(`${SERVICE_LABELS[service]} · ${ENV_LABELS[env]} 配置`, [
|
||||
`服务器: ${srv.host}:${srv.port}`,
|
||||
`用户: ${srv.username}`,
|
||||
`部署根目录: ${srv.deployPath}`,
|
||||
`实际目录: ${resolveServiceDeployPath(cfg, service, env)}`,
|
||||
`端口: ${cfg.port}`,
|
||||
`认证方式: ${srv.authType === 'key' ? '密钥' : '密码'}`,
|
||||
].join('\n'));
|
||||
|
||||
const action = await select({
|
||||
message: '配置操作',
|
||||
choices: [
|
||||
{ name: '修改服务器地址', value: 'host' },
|
||||
{ name: '修改端口', value: 'port' },
|
||||
{ name: '修改服务端口', value: 'svcPort' },
|
||||
{ name: '修改用户名', value: 'username' },
|
||||
{ name: '修改部署根目录', value: 'deployPath' },
|
||||
{ name: '测试 SSH 连接', value: 'test' },
|
||||
{ name: '配置 SSH 密钥 (首次免密)', value: 'setupKey' },
|
||||
{ name: '返回', value: 'back' },
|
||||
],
|
||||
});
|
||||
|
||||
switch (action) {
|
||||
case 'host': {
|
||||
const host = await input({ message: '服务器地址', default: srv.host });
|
||||
await updateServiceServerConfig(service, env, { host });
|
||||
break;
|
||||
}
|
||||
case 'port': {
|
||||
const p = await input({ message: 'SSH 端口', default: String(srv.port) });
|
||||
await updateServiceServerConfig(service, env, { port: Number(p) });
|
||||
break;
|
||||
}
|
||||
case 'svcPort': {
|
||||
const p = await input({ message: '服务端口', default: String(cfg.port) });
|
||||
const { updateServiceEnvConfig } = await import('./config.js');
|
||||
await updateServiceEnvConfig(service, env, { port: Number(p) });
|
||||
break;
|
||||
}
|
||||
case 'username': {
|
||||
const u = await input({ message: 'SSH 用户', default: srv.username });
|
||||
await updateServiceServerConfig(service, env, { username: u });
|
||||
break;
|
||||
}
|
||||
case 'deployPath': {
|
||||
const hint = service === 'frontend'
|
||||
? `部署根目录(实际为 根目录/ecom-dmb-${env}/index)`
|
||||
: `部署根目录(实际为 根目录/ecom-dmb/${service}/${env})`;
|
||||
const d = await input({
|
||||
message: hint,
|
||||
default: srv.deployPath,
|
||||
});
|
||||
await updateServiceServerConfig(service, env, { deployPath: d });
|
||||
break;
|
||||
}
|
||||
case 'test': {
|
||||
const ok = await testConnection(srv);
|
||||
if (ok) printSuccess('SSH 连接成功');
|
||||
else printError('SSH 连接失败');
|
||||
break;
|
||||
}
|
||||
case 'setupKey': {
|
||||
const pwd = await pwPrompt({ message: `输入 ${srv.host} 的 SSH 密码`, mask: true });
|
||||
try {
|
||||
await setupSSHKey(srv, pwd);
|
||||
await syncServerKeyAuth(srv.host, srv.username, { authType: 'key', keyPath: getSshKeyPath() });
|
||||
} catch (e: any) {
|
||||
printError(`密钥配置失败: ${e.message}`);
|
||||
}
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async function deployMenu() {
|
||||
const config = await loadConfig();
|
||||
const env = config.currentEnv;
|
||||
printBox('当前环境', `${ENV_LABELS[env]}\n${showServiceHosts(config)}`, 'yellow');
|
||||
|
||||
const deployMode = await select({
|
||||
message: '部署方式',
|
||||
choices: [
|
||||
{ name: '自动部署(编译 + 上传 + 重启)', value: 'auto' },
|
||||
{ name: '仅编译产物(不上传,输出到 artifacts/)', value: 'buildOnly' },
|
||||
{ name: '上传产物并重启(从 artifacts/,不编译)', value: 'uploadOnly' },
|
||||
{ name: '取消', value: 'cancel' },
|
||||
],
|
||||
});
|
||||
if (deployMode === 'cancel') return;
|
||||
|
||||
const services = await selectServices();
|
||||
printBox('待部署服务', services.map((s) => `${SERVICE_LABELS[s]} → ${config.services[s][env].server.host}`).join('\n'), 'cyan');
|
||||
|
||||
if (deployMode === 'buildOnly') {
|
||||
printInfo(`产物目录: ${getArtifactsRoot()}`);
|
||||
}
|
||||
|
||||
const ok = await select({
|
||||
message: '确认执行?',
|
||||
choices: [{ name: '开始', value: 'go' }, { name: '取消', value: 'cancel' }],
|
||||
});
|
||||
if (ok === 'cancel') return;
|
||||
|
||||
const onPassword = async (s: Service) => {
|
||||
const cfg = config.services[s][env];
|
||||
return await pwPrompt({ message: `输入 ${cfg.server.host} 的 SSH 密码`, mask: true });
|
||||
};
|
||||
|
||||
try {
|
||||
console.clear();
|
||||
if (deployMode === 'auto') {
|
||||
await buildAndDeployServices(services, onPassword);
|
||||
} else if (deployMode === 'buildOnly') {
|
||||
await buildServicesOnly(services);
|
||||
printSuccess(`编译完成,产物位于 ${getArtifactsRoot()}`);
|
||||
} else {
|
||||
await deployArtifactsOnly(services, onPassword);
|
||||
}
|
||||
} catch (e: any) {
|
||||
printError(`操作失败: ${e.message}`);
|
||||
}
|
||||
}
|
||||
|
||||
async function serviceMenu() {
|
||||
const service = await selectService();
|
||||
const config = await loadConfig();
|
||||
const cfg = getServiceConfig(config, service);
|
||||
const srv = cfg.server;
|
||||
|
||||
const action = await select({
|
||||
message: `${SERVICE_LABELS[service]} 管理 (${srv.host})`,
|
||||
choices: [
|
||||
{ name: '查看状态', value: 'status' },
|
||||
{ name: '查看日志', value: 'logs' },
|
||||
{ name: '重启服务', value: 'restart' },
|
||||
{ name: '停止服务', value: 'stop' },
|
||||
{ name: '检查 Docker 环境', value: 'checkDocker' },
|
||||
{ name: '返回', value: 'back' },
|
||||
],
|
||||
});
|
||||
if (action === 'back') return;
|
||||
|
||||
console.clear();
|
||||
const onPassword = async () => await pwPrompt({ message: `输入 ${srv.host} 的 SSH 密码`, mask: true });
|
||||
|
||||
try {
|
||||
switch (action) {
|
||||
case 'status': {
|
||||
const ps = await serviceStatus(service, onPassword);
|
||||
console.log(ps || '暂无运行的服务');
|
||||
break;
|
||||
}
|
||||
case 'logs': {
|
||||
const lines = await input({ message: '日志行数', default: '50' });
|
||||
const logs = await serviceLogs(service, Number(lines) || 50, onPassword);
|
||||
console.log(logs || '(无日志)');
|
||||
break;
|
||||
}
|
||||
case 'restart':
|
||||
await restartService(service, onPassword);
|
||||
break;
|
||||
case 'stop':
|
||||
await stopService(service, onPassword);
|
||||
break;
|
||||
case 'checkDocker':
|
||||
await checkRemoteDocker(service, onPassword);
|
||||
break;
|
||||
}
|
||||
} catch (e: any) {
|
||||
printError(`操作失败: ${e.message}`);
|
||||
}
|
||||
}
|
||||
|
||||
async function sshMenu() {
|
||||
const config = await loadConfig();
|
||||
const service = await selectService();
|
||||
const env = config.currentEnv;
|
||||
const srv = config.services[service][env].server;
|
||||
|
||||
const action = await select({
|
||||
message: `${SERVICE_LABELS[service]} SSH 管理 (${srv.host})`,
|
||||
choices: [
|
||||
{ name: '查看 SSH 密钥状态', value: 'status' },
|
||||
{ name: '生成 SSH 密钥对', value: 'genKey' },
|
||||
{ name: '上传公钥到服务器', value: 'uploadKey' },
|
||||
{ name: '测试连接', value: 'test' },
|
||||
{ name: '返回', value: 'back' },
|
||||
],
|
||||
});
|
||||
if (action === 'back') return;
|
||||
|
||||
console.clear();
|
||||
switch (action) {
|
||||
case 'status': {
|
||||
const { existsSync } = await import('fs');
|
||||
if (existsSync(getSshKeyPath())) printSuccess(`密钥存在: ${getSshKeyPath()}`);
|
||||
else printInfo('尚未生成 SSH 密钥对');
|
||||
break;
|
||||
}
|
||||
case 'genKey': {
|
||||
ensureKeyPair();
|
||||
printSuccess('SSH 密钥对已生成');
|
||||
break;
|
||||
}
|
||||
case 'uploadKey': {
|
||||
const pwd = await pwPrompt({ message: `输入 ${srv.host} 的 SSH 密码`, mask: true });
|
||||
try {
|
||||
await setupSSHKey(srv, pwd);
|
||||
await syncServerKeyAuth(srv.host, srv.username, { authType: 'key', keyPath: getSshKeyPath() });
|
||||
} catch (e: any) {
|
||||
printError(`上传失败: ${e.message}`);
|
||||
}
|
||||
break;
|
||||
}
|
||||
case 'test': {
|
||||
const pwd = srv.authType === 'password'
|
||||
? await pwPrompt({ message: `输入 ${srv.host} 的 SSH 密码`, mask: true })
|
||||
: undefined;
|
||||
const ok = await testConnection(srv, pwd);
|
||||
if (ok) printSuccess('SSH 连接成功');
|
||||
else printError('SSH 连接失败');
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async function mainMenu() {
|
||||
console.clear();
|
||||
printBanner();
|
||||
|
||||
const config = await loadConfig();
|
||||
const env = config.currentEnv;
|
||||
printInfo(`当前环境: ${ENV_LABELS[env]}`);
|
||||
console.log(showServiceHosts(config));
|
||||
|
||||
const action = await select({
|
||||
message: '主菜单',
|
||||
choices: [
|
||||
{ name: '部署服务', value: 'deploy' },
|
||||
{ name: '服务管理', value: 'service' },
|
||||
{ name: '配置服务', value: 'config' },
|
||||
{ name: 'SSH 密钥管理', value: 'ssh' },
|
||||
{ name: '切换环境', value: 'switchEnv' },
|
||||
{ name: '退出', value: 'exit' },
|
||||
],
|
||||
});
|
||||
|
||||
switch (action) {
|
||||
case 'deploy': console.clear(); await deployMenu(); break;
|
||||
case 'service': console.clear(); await serviceMenu(); break;
|
||||
case 'config': await configureService(); break;
|
||||
case 'ssh': await sshMenu(); break;
|
||||
case 'switchEnv': {
|
||||
const newEnv = await selectEnv();
|
||||
printSuccess(`已切换到: ${ENV_LABELS[newEnv]}`);
|
||||
break;
|
||||
}
|
||||
case 'exit': process.exit(0);
|
||||
}
|
||||
}
|
||||
|
||||
async function main() {
|
||||
while (true) {
|
||||
try {
|
||||
await mainMenu();
|
||||
await pause();
|
||||
} catch (e: any) {
|
||||
if (e?.name === 'ExitPromptError') process.exit(0);
|
||||
printError(String(e?.message || e));
|
||||
await pause();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
main();
|
||||
@@ -0,0 +1,49 @@
|
||||
import { execSync } from 'child_process';
|
||||
import { cpSync, existsSync, readdirSync } from 'fs';
|
||||
import { tmpdir } from 'os';
|
||||
import { join } from 'path';
|
||||
|
||||
/** 本地临时目录(跨平台,替代 /tmp) */
|
||||
export function getLocalTempPath(name: string): string {
|
||||
return join(tmpdir(), name);
|
||||
}
|
||||
|
||||
/** 解析 Maven 命令:Windows 用 mvnw.cmd,Unix 用 mvnw */
|
||||
export function resolveMavenCommand(projectDir: string): string {
|
||||
if (process.platform === 'win32') {
|
||||
const mvnwCmd = join(projectDir, 'mvnw.cmd');
|
||||
if (existsSync(mvnwCmd)) return `"${mvnwCmd}"`;
|
||||
} else {
|
||||
const mvnw = join(projectDir, 'mvnw');
|
||||
if (existsSync(mvnw)) return `"${mvnw}"`;
|
||||
}
|
||||
return 'mvn';
|
||||
}
|
||||
|
||||
/** 在 target 目录查找主 JAR(排除 *-original.jar) */
|
||||
export function findMainJar(targetDir: string): string {
|
||||
const jars = readdirSync(targetDir).filter(
|
||||
(f) => f.endsWith('.jar') && !f.endsWith('-original.jar'),
|
||||
);
|
||||
if (jars.length === 0) throw new Error(`未找到 JAR 文件: ${targetDir}`);
|
||||
return join(targetDir, jars[0]);
|
||||
}
|
||||
|
||||
/** 将目录打包为 tar.gz(Windows 10+ / Linux / macOS 均内置 tar) */
|
||||
export function createTarGz(sourceDir: string, destPath: string): void {
|
||||
try {
|
||||
execSync(`tar -czf "${destPath}" -C "${sourceDir}" .`, { stdio: 'pipe' });
|
||||
} catch (e: unknown) {
|
||||
const msg = e instanceof Error ? e.message : String(e);
|
||||
throw new Error(`打包失败 (${sourceDir}): ${msg}`);
|
||||
}
|
||||
}
|
||||
|
||||
/** 递归复制目录/文件到临时构建目录 */
|
||||
export function copyBuildArtifacts(src: string, dest: string, opts?: { optional?: boolean }): void {
|
||||
if (!existsSync(src)) {
|
||||
if (opts?.optional) return;
|
||||
throw new Error(`源路径不存在: ${src}`);
|
||||
}
|
||||
cpSync(src, dest, { recursive: true });
|
||||
}
|
||||
@@ -0,0 +1,234 @@
|
||||
import { execSync } from 'child_process';
|
||||
import { existsSync, mkdirSync, readFileSync } from 'fs';
|
||||
import { homedir } from 'os';
|
||||
import { join } from 'path';
|
||||
import { Client } from 'ssh2';
|
||||
|
||||
import { printInfo, printSuccess } from './ui/render.js';
|
||||
import type { ServerConfig } from './types.js';
|
||||
import { getSshKeyPath } from './config.js';
|
||||
|
||||
export interface SSHExecResult {
|
||||
stdout: string;
|
||||
stderr: string;
|
||||
code: number;
|
||||
}
|
||||
|
||||
export interface SSHConnectResult {
|
||||
conn: Client;
|
||||
/** 本次连接使用的认证方式 */
|
||||
authMethod: 'key' | 'password';
|
||||
}
|
||||
|
||||
export function resolveKeyPath(config: ServerConfig): string {
|
||||
return config.keyPath || getSshKeyPath();
|
||||
}
|
||||
|
||||
export function ensureKeyPair(keyPath: string = getSshKeyPath()): { publicKey: string; privateKeyPath: string } {
|
||||
if (existsSync(keyPath)) {
|
||||
const publicKeyPath = `${keyPath}.pub`;
|
||||
const publicKey = existsSync(publicKeyPath) ? readFileSync(publicKeyPath, 'utf8').trim() : '';
|
||||
return { publicKey, privateKeyPath: keyPath };
|
||||
}
|
||||
|
||||
const dir = join(homedir(), '.ssh');
|
||||
mkdirSync(dir, { recursive: true });
|
||||
|
||||
execSync(`ssh-keygen -t ed25519 -f "${keyPath}" -N "" -C "ecom-deploy"`, { stdio: 'pipe' });
|
||||
const publicKey = readFileSync(`${keyPath}.pub`, 'utf8').trim();
|
||||
printSuccess(`SSH 密钥已生成: ${keyPath}.pub`);
|
||||
|
||||
return { publicKey, privateKeyPath: keyPath };
|
||||
}
|
||||
|
||||
function sshConnect(config: ServerConfig, password?: string, keyPath?: string): Promise<Client> {
|
||||
return new Promise((resolve, reject) => {
|
||||
const conn = new Client();
|
||||
const privateKeyPath = keyPath || resolveKeyPath(config);
|
||||
|
||||
const opts: any = {
|
||||
host: config.host,
|
||||
port: config.port,
|
||||
username: config.username,
|
||||
readyTimeout: 15000,
|
||||
keepaliveInterval: 10000,
|
||||
};
|
||||
|
||||
if (password) {
|
||||
opts.password = password;
|
||||
opts.tryKeyboard = true;
|
||||
} else if (existsSync(privateKeyPath)) {
|
||||
opts.privateKey = readFileSync(privateKeyPath, 'utf8');
|
||||
}
|
||||
|
||||
conn.on('ready', () => resolve(conn));
|
||||
conn.on('error', (err) => reject(err));
|
||||
conn.on('keyboard-interactive', (_name, _instructions, _instructionsLang, _prompts, finish) => {
|
||||
finish([password || '']);
|
||||
});
|
||||
|
||||
conn.connect(opts);
|
||||
});
|
||||
}
|
||||
|
||||
export async function connectWithRetry(
|
||||
config: ServerConfig,
|
||||
password?: string,
|
||||
onPassword?: () => Promise<string>,
|
||||
): Promise<SSHConnectResult> {
|
||||
let lastError: Error | null = null;
|
||||
const keyPath = resolveKeyPath(config);
|
||||
|
||||
// 优先尝试密钥(只要本地密钥文件存在)
|
||||
if (existsSync(keyPath)) {
|
||||
try {
|
||||
const conn = await sshConnect(config, undefined, keyPath);
|
||||
return { conn, authMethod: 'key' };
|
||||
} catch (e: any) {
|
||||
lastError = e;
|
||||
printInfo(`密钥认证失败 (${e.message}),尝试密码...`);
|
||||
}
|
||||
}
|
||||
|
||||
if (password || config.lastPassword) {
|
||||
try {
|
||||
const conn = await sshConnect(config, password || config.lastPassword);
|
||||
return { conn, authMethod: 'password' };
|
||||
} catch (e: any) {
|
||||
lastError = e;
|
||||
}
|
||||
}
|
||||
|
||||
if (onPassword) {
|
||||
password = await onPassword();
|
||||
try {
|
||||
const conn = await sshConnect(config, password);
|
||||
return { conn, authMethod: 'password' };
|
||||
} catch (e: any) {
|
||||
lastError = e;
|
||||
throw new Error(`SSH 连接失败: ${lastError?.message || '未知错误'}`);
|
||||
}
|
||||
}
|
||||
|
||||
throw new Error(`SSH 连接失败: ${lastError?.message || '无法连接'}`);
|
||||
}
|
||||
|
||||
/** 远程 shell 初始化:passwd home 不可用时回退到 /tmp,避免 docker 等命令 mkdir home 失败 */
|
||||
export const REMOTE_SHELL_INIT = `
|
||||
PASSWD_HOME=$(getent passwd "$(whoami)" | cut -d: -f6)
|
||||
FALLBACK_HOME="/tmp/ecom-deploy-$(whoami)"
|
||||
if [ -n "$PASSWD_HOME" ] && [ -d "$PASSWD_HOME" ] && [ -w "$PASSWD_HOME" ]; then
|
||||
export HOME="$PASSWD_HOME"
|
||||
elif [ -n "$PASSWD_HOME" ] && mkdir -p "$PASSWD_HOME" 2>/dev/null && [ -w "$PASSWD_HOME" ]; then
|
||||
export HOME="$PASSWD_HOME"
|
||||
else
|
||||
mkdir -p "$FALLBACK_HOME"
|
||||
export HOME="$FALLBACK_HOME"
|
||||
fi
|
||||
`.trim();
|
||||
|
||||
export function wrapRemoteCommand(command: string): string {
|
||||
return `${REMOTE_SHELL_INIT}\n${command}`;
|
||||
}
|
||||
|
||||
export async function execRemote(conn: Client, command: string): Promise<SSHExecResult> {
|
||||
return new Promise((resolve, reject) => {
|
||||
let stdout = '';
|
||||
let stderr = '';
|
||||
conn.exec(wrapRemoteCommand(command), (err, stream) => {
|
||||
if (err) return reject(err);
|
||||
stream.on('close', (code: number) => {
|
||||
resolve({ stdout, stderr, code });
|
||||
});
|
||||
stream.on('data', (data: Buffer) => {
|
||||
stdout += data.toString();
|
||||
});
|
||||
stream.stderr.on('data', (data: Buffer) => {
|
||||
stderr += data.toString();
|
||||
});
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
export async function uploadFile(conn: Client, localPath: string, remotePath: string): Promise<void> {
|
||||
return new Promise((resolve, reject) => {
|
||||
conn.sftp((err, sftp) => {
|
||||
if (err) return reject(new Error(`SFTP 连接失败: ${err.message}`));
|
||||
sftp.fastPut(localPath, remotePath, (err2) => {
|
||||
sftp.end();
|
||||
if (err2) reject(new Error(`上传失败 ${localPath} → ${remotePath}: ${err2.message}`));
|
||||
else resolve();
|
||||
});
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
export async function ensureRemoteDir(conn: Client, dir: string): Promise<void> {
|
||||
const { code, stderr } = await execRemote(conn, `mkdir -p "${dir}"`);
|
||||
if (code !== 0) throw new Error(`创建远程目录失败 ${dir}: ${stderr}`);
|
||||
}
|
||||
|
||||
/** 将公钥写入远程 authorized_keys(必须能创建 passwd 中的 home 目录,sshd 才认密钥) */
|
||||
export async function uploadPublicKey(conn: Client, publicKey: string): Promise<void> {
|
||||
const keyBody = publicKey.trim().split(/\s+/)[1] || publicKey.trim().slice(0, 32);
|
||||
const escapedKey = publicKey.trim().replace(/'/g, `'\\''`);
|
||||
|
||||
const script = `
|
||||
PASSWD_HOME=$(getent passwd "$(whoami)" | cut -d: -f6)
|
||||
if [ -z "$PASSWD_HOME" ]; then echo "ERR: 无法解析用户 home 目录"; exit 1; fi
|
||||
if ! mkdir -p "$PASSWD_HOME/.ssh" 2>/dev/null; then
|
||||
echo "ERR: 无法创建 $PASSWD_HOME/.ssh"
|
||||
echo "请在服务器执行: sudo mkdir -p $PASSWD_HOME && sudo chown $(whoami):$(whoami) $PASSWD_HOME"
|
||||
exit 1
|
||||
fi
|
||||
chmod 700 "$PASSWD_HOME/.ssh"
|
||||
AUTH_FILE="$PASSWD_HOME/.ssh/authorized_keys"
|
||||
touch "$AUTH_FILE" && chmod 600 "$AUTH_FILE"
|
||||
if grep -Fq '${keyBody}' "$AUTH_FILE" 2>/dev/null; then
|
||||
echo "公钥已存在"
|
||||
else
|
||||
printf '%s\\n' '${escapedKey}' >> "$AUTH_FILE"
|
||||
echo "公钥已写入"
|
||||
fi
|
||||
`.trim();
|
||||
|
||||
const { code, stdout, stderr } = await execRemote(conn, script);
|
||||
if (code !== 0) {
|
||||
throw new Error(`上传公钥失败: ${stderr || stdout}`);
|
||||
}
|
||||
if (stdout.includes('公钥已存在')) {
|
||||
printInfo('公钥已存在,跳过');
|
||||
} else {
|
||||
printSuccess('公钥已上传到服务器');
|
||||
}
|
||||
}
|
||||
|
||||
/** 密码登录成功后自动安装公钥,供后续免密连接 */
|
||||
export async function installKeyAfterPasswordAuth(conn: Client, config: ServerConfig): Promise<string> {
|
||||
const { publicKey, privateKeyPath } = ensureKeyPair(resolveKeyPath(config));
|
||||
await uploadPublicKey(conn, publicKey);
|
||||
return privateKeyPath;
|
||||
}
|
||||
|
||||
export async function setupSSHKey(config: ServerConfig, password: string): Promise<void> {
|
||||
const { conn } = await connectWithRetry(config, password);
|
||||
try {
|
||||
await installKeyAfterPasswordAuth(conn, config);
|
||||
config.authType = 'key';
|
||||
config.keyPath = resolveKeyPath(config);
|
||||
config.lastPassword = undefined;
|
||||
printSuccess('SSH 密钥认证已配置完成');
|
||||
} finally {
|
||||
conn.end();
|
||||
}
|
||||
}
|
||||
|
||||
export async function testConnection(config: ServerConfig, password?: string): Promise<boolean> {
|
||||
try {
|
||||
const { conn } = await connectWithRetry(config, password);
|
||||
conn.end();
|
||||
return true;
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,44 @@
|
||||
export type Environment = 'test' | 'pre' | 'prod';
|
||||
export type Service = 'frontend' | 'backend' | 'license';
|
||||
|
||||
export interface ServerConfig {
|
||||
host: string;
|
||||
port: number;
|
||||
username: string;
|
||||
/** 部署根目录;实际路径为 {deployPath}/ecom-dmb/{service}/{env} */
|
||||
deployPath: string;
|
||||
authType: 'password' | 'key';
|
||||
keyPath?: string;
|
||||
lastPassword?: string;
|
||||
}
|
||||
|
||||
export interface ServiceEnvConfig {
|
||||
server: ServerConfig;
|
||||
port: number;
|
||||
springProfile?: string;
|
||||
nodeEnv?: string;
|
||||
dbUrl?: string;
|
||||
redisUrl?: string;
|
||||
licenseDbUrl?: string;
|
||||
/** 仅静态文件部署(不启动 Docker),前端常用 */
|
||||
staticDeploy?: boolean;
|
||||
/** @deprecated 改用 staticDeploy;若存在则仍视为静态部署 */
|
||||
extractDir?: string;
|
||||
}
|
||||
|
||||
export interface DeployConfig {
|
||||
currentEnv: Environment;
|
||||
services: Record<Service, Record<Environment, ServiceEnvConfig>>;
|
||||
}
|
||||
|
||||
export const SERVICE_LABELS: Record<Service, string> = {
|
||||
frontend: '前端',
|
||||
backend: '后端',
|
||||
license: '许可证服务',
|
||||
};
|
||||
|
||||
export const ENV_LABELS: Record<Environment, string> = {
|
||||
test: '测试环境',
|
||||
pre: '预发布环境',
|
||||
prod: '生产环境',
|
||||
};
|
||||
@@ -0,0 +1,54 @@
|
||||
import boxen from 'boxen';
|
||||
import chalk from 'chalk';
|
||||
import gradient from 'gradient-string';
|
||||
import ora, { type Ora } from 'ora';
|
||||
|
||||
export function printBanner() {
|
||||
const title = gradient.pastel('Ecom Deploy');
|
||||
console.log(
|
||||
boxen(`${title}\n${chalk.gray('部署管理工具 · Docker 编排')}`, {
|
||||
padding: 1,
|
||||
borderColor: 'cyan',
|
||||
borderStyle: 'round',
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
export function printSuccess(msg: string) {
|
||||
console.log(chalk.green('✔'), msg);
|
||||
}
|
||||
|
||||
export function printError(msg: string) {
|
||||
console.error(chalk.red('✖'), msg);
|
||||
}
|
||||
|
||||
export function printInfo(msg: string) {
|
||||
console.log(chalk.blue('ℹ'), msg);
|
||||
}
|
||||
|
||||
export function printBox(title: string, content: string, borderColor: 'green' | 'cyan' | 'yellow' = 'cyan') {
|
||||
console.log(
|
||||
boxen(content, {
|
||||
title: chalk.bold(title),
|
||||
padding: 1,
|
||||
borderColor,
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
let activeSpinner: Ora | null = null;
|
||||
|
||||
export async function runSpinner<T>(fn: () => Promise<T>, text: string): Promise<T> {
|
||||
const spinner = ora(text).start();
|
||||
activeSpinner = spinner;
|
||||
try {
|
||||
const result = await fn();
|
||||
spinner.succeed();
|
||||
return result;
|
||||
} catch (e) {
|
||||
spinner.fail();
|
||||
throw e;
|
||||
} finally {
|
||||
activeSpinner = null;
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user