mirror of
https://gitee.com/qqtt-ah/ecom-dmb.git
synced 2026-11-24 01:19:19 +08:00
feat: 将 Agent 接入运行时镜像挂载式部署
This commit is contained in:
+18
-1
@@ -8,7 +8,7 @@ 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'];
|
||||
const ALL_SERVICES: Service[] = ['frontend', 'backend', 'license', 'agent'];
|
||||
|
||||
/** 确保 artifacts 根目录及子目录存在 */
|
||||
export function ensureArtifactsDirs(): void {
|
||||
@@ -50,6 +50,13 @@ export function syncLicenseArtifacts(srcDir: string): string {
|
||||
return getArtifactDir('license');
|
||||
}
|
||||
|
||||
/** 同步 Agent 源码到 artifacts/agent */
|
||||
export function syncAgentArtifacts(srcDir: string): string {
|
||||
clearArtifactDir('agent');
|
||||
cpSync(srcDir, getArtifactDir('agent'), { recursive: true });
|
||||
return getArtifactDir('agent');
|
||||
}
|
||||
|
||||
/** 部署前检查本地产物是否就绪 */
|
||||
export function assertArtifactsExist(service: Service): void {
|
||||
const dir = getArtifactDir(service);
|
||||
@@ -64,6 +71,16 @@ export function assertArtifactsExist(service: Service): void {
|
||||
return;
|
||||
}
|
||||
|
||||
if (service === 'agent') {
|
||||
if (!existsSync(join(dir, 'requirements.txt')) || !existsSync(join(dir, 'api'))) {
|
||||
throw new Error(`Agent 产物不完整: ${dir},请先编译智能体`);
|
||||
}
|
||||
if (!existsSync(join(dir, '.deps'))) {
|
||||
throw new Error(`缺少 ${join(dir, '.deps')},请先编译智能体以安装依赖`);
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
const files = readdirSync(dir);
|
||||
if (files.length === 0) {
|
||||
throw new Error(`产物目录为空: ${dir},请先编译 ${service}`);
|
||||
|
||||
+42
-1
@@ -44,14 +44,35 @@ function defaultConfig(): DeployConfig {
|
||||
pre: { ...defaultServiceConfig('192.168.1.101', 3100), nodeEnv: 'pre', licenseDbUrl: '' },
|
||||
prod: { ...defaultServiceConfig('license.prod.com', 3100), nodeEnv: 'prod', licenseDbUrl: '' },
|
||||
},
|
||||
agent: {
|
||||
test: defaultServiceConfig('192.168.3.101', 8201),
|
||||
pre: defaultServiceConfig('192.168.3.101', 8202),
|
||||
prod: defaultServiceConfig('agent.prod.com', 8203),
|
||||
},
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
/** 旧 config.json 缺服务时补默认项并写回 */
|
||||
function mergeMissingServices(cfg: DeployConfig): { config: DeployConfig; dirty: boolean } {
|
||||
const defaults = defaultConfig();
|
||||
let dirty = false;
|
||||
for (const service of Object.keys(defaults.services) as Service[]) {
|
||||
if (!cfg.services[service]) {
|
||||
cfg.services[service] = defaults.services[service];
|
||||
dirty = true;
|
||||
}
|
||||
}
|
||||
return { config: cfg, dirty };
|
||||
}
|
||||
|
||||
export async function loadConfig(): Promise<DeployConfig> {
|
||||
try {
|
||||
const raw = await readFile(CONFIG_PATH, 'utf8');
|
||||
return JSON.parse(raw) as DeployConfig;
|
||||
const parsed = JSON.parse(raw) as DeployConfig;
|
||||
const { config, dirty } = mergeMissingServices(parsed);
|
||||
if (dirty) await saveConfig(config);
|
||||
return config;
|
||||
} catch {
|
||||
const cfg = defaultConfig();
|
||||
await saveConfig(cfg);
|
||||
@@ -169,6 +190,18 @@ export function resolveBackendPort(env: Environment): number {
|
||||
}
|
||||
}
|
||||
|
||||
/** Agent 各环境监听端口(开发本机仍用 8200) */
|
||||
export function resolveAgentPort(env: Environment): number {
|
||||
switch (env) {
|
||||
case 'test':
|
||||
return 8201;
|
||||
case 'pre':
|
||||
return 8202;
|
||||
case 'prod':
|
||||
return 8203;
|
||||
}
|
||||
}
|
||||
|
||||
/** 部署环境 pre 对应 Spring profile pre(application-pre.yml) */
|
||||
export function resolveSpringProfile(profile?: string): string {
|
||||
return profile || 'prod';
|
||||
@@ -224,6 +257,10 @@ export function getLicenseDir(): string {
|
||||
return join(PROJECT_ROOT, 'apps', 'license-server');
|
||||
}
|
||||
|
||||
export function getAgentDir(): string {
|
||||
return join(PROJECT_ROOT, 'apps', 'agent');
|
||||
}
|
||||
|
||||
export function getFrontendDeployDir(): string {
|
||||
return join(PROJECT_ROOT, 'apps', 'web', 'deploy');
|
||||
}
|
||||
@@ -235,3 +272,7 @@ export function getBackendDeployDir(): string {
|
||||
export function getLicenseDeployDir(): string {
|
||||
return join(PROJECT_ROOT, 'apps', 'license-server', 'deploy');
|
||||
}
|
||||
|
||||
export function getAgentDeployDir(): string {
|
||||
return join(PROJECT_ROOT, 'apps', 'agent', 'deploy');
|
||||
}
|
||||
|
||||
@@ -0,0 +1,132 @@
|
||||
import { execSync } from 'child_process';
|
||||
import { existsSync, mkdirSync, rmSync } from 'fs';
|
||||
import { join } from 'path';
|
||||
|
||||
import { Client } from 'ssh2';
|
||||
import { syncAgentArtifacts, uploadArtifactDirectory } from '../artifacts.js';
|
||||
import { getAgentDir, getArtifactDir, getRemoteAppDir } from '../config.js';
|
||||
import { copyBuildArtifacts, getLocalTempPath } 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 = 'agent';
|
||||
|
||||
/** 同步到产物的源码目录(不含 .venv / .env*) */
|
||||
const AGENT_SOURCE_DIRS = [
|
||||
'api',
|
||||
'agent',
|
||||
'application',
|
||||
'config',
|
||||
'domain',
|
||||
'infrastructure',
|
||||
] as const;
|
||||
|
||||
/**
|
||||
* 「编译」:同步源码到 artifacts/agent,并 pip install --target .deps
|
||||
* (用系统 python -m uvicorn 加载,避免 venv shebang 路径不可移植)
|
||||
*/
|
||||
export async function build(): Promise<string> {
|
||||
const agentDir = getAgentDir();
|
||||
if (!existsSync(agentDir)) throw new Error(`Agent 项目目录不存在: ${agentDir}`);
|
||||
if (!existsSync(join(agentDir, 'requirements.txt'))) {
|
||||
throw new Error(`缺少 requirements.txt: ${agentDir}`);
|
||||
}
|
||||
|
||||
printInfo('同步 Agent 源码...');
|
||||
const tmpDir = getLocalTempPath('ecom-agent-build');
|
||||
if (existsSync(tmpDir)) rmSync(tmpDir, { recursive: true });
|
||||
mkdirSync(tmpDir, { recursive: true });
|
||||
|
||||
for (const dir of AGENT_SOURCE_DIRS) {
|
||||
copyBuildArtifacts(join(agentDir, dir), join(tmpDir, dir));
|
||||
}
|
||||
copyBuildArtifacts(join(agentDir, 'requirements.txt'), join(tmpDir, 'requirements.txt'));
|
||||
|
||||
// 去掉缓存,避免打进产物
|
||||
execSync(
|
||||
`find "${tmpDir}" -type d \\( -name __pycache__ -o -name .pytest_cache -o -name .mypy_cache -o -name .ruff_cache \\) -exec rm -rf {} + 2>/dev/null || true`,
|
||||
);
|
||||
|
||||
const artifactDir = syncAgentArtifacts(tmpDir);
|
||||
rmSync(tmpDir, { recursive: true, force: true });
|
||||
|
||||
printInfo('安装 Agent 依赖到 .deps(pip --target)...');
|
||||
execSync('python3 -m pip install -r requirements.txt --target .deps --upgrade', {
|
||||
stdio: 'inherit',
|
||||
cwd: artifactDir,
|
||||
shell: process.platform === 'win32' ? (process.env.COMSPEC || 'cmd.exe') : undefined,
|
||||
});
|
||||
|
||||
printSuccess(`Agent 构建完成,产物: ${artifactDir}`);
|
||||
return artifactDir;
|
||||
}
|
||||
|
||||
/** 远程环境配置文件名:.env.test / .env.pre / .env.prod */
|
||||
function remoteEnvFileName(env: Environment): string {
|
||||
return `.env.${env}`;
|
||||
}
|
||||
|
||||
/** 首次部署:若远程尚无 .env.{env},从仓库模板初始化(后续部署不覆盖) */
|
||||
async function seedRemoteEnvIfMissing(
|
||||
conn: Client,
|
||||
remoteAppDir: string,
|
||||
env: Environment,
|
||||
): Promise<void> {
|
||||
const name = remoteEnvFileName(env);
|
||||
const remoteEnv = `${remoteAppDir}/${name}`;
|
||||
const { code } = await execRemote(conn, `test -f "${remoteEnv}"`);
|
||||
if (code === 0) return;
|
||||
|
||||
const local = join(getAgentDir(), name);
|
||||
if (!existsSync(local)) {
|
||||
printInfo(`远程尚无 ${name},且本地无模板 ${local},请手动创建`);
|
||||
return;
|
||||
}
|
||||
await uploadFile(conn, local, remoteEnv);
|
||||
printInfo(`已初始化配置(仅首次): ${remoteEnv},请按环境核对 JWT/Mongo/Redis/Server`);
|
||||
}
|
||||
|
||||
/**
|
||||
* 上传前备份远程全部 .env*,清空上传后恢复,避免密钥被制品覆盖。
|
||||
*/
|
||||
async function preserveRemoteEnvAroundUpload(
|
||||
conn: Client,
|
||||
remoteAppDir: string,
|
||||
env: Environment,
|
||||
upload: () => Promise<void>,
|
||||
): Promise<void> {
|
||||
const bakDir = `/tmp/ecom-agent-env-${Date.now()}`;
|
||||
await execRemote(
|
||||
conn,
|
||||
`mkdir -p "${bakDir}" && sh -c 'cd "${remoteAppDir}" && ls -A .env* >/dev/null 2>&1 && cp -a .env* "${bakDir}/" || true'`,
|
||||
);
|
||||
|
||||
await upload();
|
||||
|
||||
const { code } = await execRemote(conn, `ls -A "${bakDir}"/.env* >/dev/null 2>&1`);
|
||||
if (code === 0) {
|
||||
await execRemote(conn, `cp -a "${bakDir}"/.env* "${remoteAppDir}/" && rm -rf "${bakDir}"`);
|
||||
} else {
|
||||
await execRemote(conn, `rm -rf "${bakDir}"`);
|
||||
await seedRemoteEnvIfMissing(conn, remoteAppDir, env);
|
||||
}
|
||||
}
|
||||
|
||||
/** 上传 artifacts/agent 到远程挂载目录 */
|
||||
export async function deploy(
|
||||
conn: Client,
|
||||
cfg: ServiceEnvConfig,
|
||||
_buildDir: string,
|
||||
env: Environment,
|
||||
): Promise<void> {
|
||||
const artifactDir = getArtifactDir('agent');
|
||||
const remoteAppDir = getRemoteAppDir(cfg, 'agent', env);
|
||||
await ensureRemoteDir(conn, remoteAppDir);
|
||||
|
||||
await preserveRemoteEnvAroundUpload(conn, remoteAppDir, env, async () => {
|
||||
await uploadArtifactDirectory(conn, artifactDir, remoteAppDir);
|
||||
});
|
||||
|
||||
printSuccess(`Agent 产物已上传到 ${remoteAppDir}`);
|
||||
}
|
||||
@@ -17,6 +17,7 @@ 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';
|
||||
import * as agentDeploy from './agent.js';
|
||||
|
||||
const deployers: Record<Service, {
|
||||
build: (cfg?: ServiceEnvConfig) => Promise<string>;
|
||||
@@ -25,6 +26,7 @@ const deployers: Record<Service, {
|
||||
frontend: frontendDeploy as any,
|
||||
backend: backendDeploy as any,
|
||||
license: licenseDeploy as any,
|
||||
agent: agentDeploy as any,
|
||||
};
|
||||
|
||||
export async function buildService(service: Service, cfg: ServiceEnvConfig): Promise<string> {
|
||||
|
||||
+27
-5
@@ -3,10 +3,12 @@ import { join } from 'path';
|
||||
|
||||
import { Client } from 'ssh2';
|
||||
import {
|
||||
getAgentDeployDir,
|
||||
getBackendDeployDir,
|
||||
getDockerResourceNames,
|
||||
getLicenseDeployDir,
|
||||
getRemoteServiceDir,
|
||||
resolveAgentPort,
|
||||
resolveBackendPort,
|
||||
resolveEnvDeployDir,
|
||||
resolveSpringProfile,
|
||||
@@ -29,6 +31,10 @@ function resolveBridgePorts(service: Service, cfg: ServiceEnvConfig, env: Enviro
|
||||
const port = resolveBackendPort(env);
|
||||
return { hostPort: port, containerPort: port };
|
||||
}
|
||||
if (service === 'agent') {
|
||||
const port = resolveAgentPort(env);
|
||||
return { hostPort: port, containerPort: port };
|
||||
}
|
||||
return { hostPort: cfg.port, containerPort: cfg.port };
|
||||
}
|
||||
|
||||
@@ -61,6 +67,12 @@ export function generateComposeFile(service: Service, cfg: ServiceEnvConfig, env
|
||||
` - PORT=${containerPort}`,
|
||||
cfg.licenseDbUrl ? ` - DB_URL=${cfg.licenseDbUrl}` : '',
|
||||
].filter(Boolean).join('\n');
|
||||
} else if (service === 'agent') {
|
||||
// AGENT_ENV 决定加载 .env.{env};PORT 与桥接端口对齐
|
||||
envBlock = [
|
||||
` - PORT=${containerPort}`,
|
||||
` - AGENT_ENV=${env}`,
|
||||
].join('\n');
|
||||
}
|
||||
|
||||
const volumeBlock = service === 'backend'
|
||||
@@ -95,13 +107,16 @@ networks:
|
||||
|
||||
/** 读取运行时 Dockerfile 内容 */
|
||||
function readRuntimeDockerfile(service: Service): string {
|
||||
const dockerfileSrc = service === 'backend'
|
||||
? join(getBackendDeployDir(), 'Dockerfile')
|
||||
: join(getLicenseDeployDir(), 'Dockerfile');
|
||||
return readFileSync(dockerfileSrc, 'utf8');
|
||||
if (service === 'backend') {
|
||||
return readFileSync(join(getBackendDeployDir(), 'Dockerfile'), 'utf8');
|
||||
}
|
||||
if (service === 'agent') {
|
||||
return readFileSync(join(getAgentDeployDir(), 'Dockerfile'), 'utf8');
|
||||
}
|
||||
return readFileSync(join(getLicenseDeployDir(), 'Dockerfile'), 'utf8');
|
||||
}
|
||||
|
||||
/** 上传运行时 Dockerfile 到远程环境目录 */
|
||||
/** 上传运行时 Dockerfile 到远程环境目录(Agent 另需 entrypoint.sh) */
|
||||
export async function uploadRuntimeDockerfile(
|
||||
conn: Client,
|
||||
service: Service,
|
||||
@@ -113,6 +128,13 @@ export async function uploadRuntimeDockerfile(
|
||||
const tmp = getLocalTempPath(`ecom-${service}-Dockerfile`);
|
||||
writeFileSync(tmp, readRuntimeDockerfile(service), 'utf8');
|
||||
await uploadFile(conn, tmp, `${serviceDir}/Dockerfile`);
|
||||
|
||||
if (service === 'agent') {
|
||||
const entrySrc = join(getAgentDeployDir(), 'entrypoint.sh');
|
||||
const tmpEntry = getLocalTempPath('ecom-agent-entrypoint.sh');
|
||||
writeFileSync(tmpEntry, readFileSync(entrySrc, 'utf8'), 'utf8');
|
||||
await uploadFile(conn, tmpEntry, `${serviceDir}/entrypoint.sh`);
|
||||
}
|
||||
}
|
||||
|
||||
/** 检查远程运行时镜像是否已存在 */
|
||||
|
||||
+4
-2
@@ -27,7 +27,7 @@ import { printBanner, printBox, printError, printInfo, printSuccess } from './ui
|
||||
import { ENV_LABELS, SERVICE_LABELS } from './types.js';
|
||||
import type { DeployConfig, Environment, Service } from './types.js';
|
||||
|
||||
const ALL_SERVICES: Service[] = ['frontend', 'backend', 'license'];
|
||||
const ALL_SERVICES: Service[] = ['frontend', 'backend', 'license', 'agent'];
|
||||
|
||||
async function pause() {
|
||||
await input({ message: '按 Enter 返回主菜单' });
|
||||
@@ -59,6 +59,7 @@ async function selectService(): Promise<Service | Nav> {
|
||||
{ name: '前端', value: 'frontend' as Service },
|
||||
{ name: '后端', value: 'backend' as Service },
|
||||
{ name: '许可证', value: 'license' as Service },
|
||||
{ name: '智能体', value: 'agent' as Service },
|
||||
],
|
||||
});
|
||||
}
|
||||
@@ -68,7 +69,7 @@ async function selectServicesMulti(): Promise<Service[] | Nav> {
|
||||
const scope = await selectNav({
|
||||
message: '部署范围',
|
||||
choices: [
|
||||
{ name: '全部服务', value: 'all' as const, description: '前端 + 后端 + 许可证' },
|
||||
{ name: '全部服务', value: 'all' as const, description: '前端 + 后端 + 许可证 + 智能体' },
|
||||
{ name: '指定服务…', value: 'pick' as const, description: '空格多选' },
|
||||
],
|
||||
});
|
||||
@@ -81,6 +82,7 @@ async function selectServicesMulti(): Promise<Service[] | Nav> {
|
||||
{ name: '前端', value: 'frontend' as Service },
|
||||
{ name: '后端', value: 'backend' as Service },
|
||||
{ name: '许可证', value: 'license' as Service },
|
||||
{ name: '智能体', value: 'agent' as Service },
|
||||
],
|
||||
required: true,
|
||||
});
|
||||
|
||||
+2
-1
@@ -1,5 +1,5 @@
|
||||
export type Environment = 'test' | 'pre' | 'prod';
|
||||
export type Service = 'frontend' | 'backend' | 'license';
|
||||
export type Service = 'frontend' | 'backend' | 'license' | 'agent';
|
||||
|
||||
export interface ServerConfig {
|
||||
host: string;
|
||||
@@ -35,6 +35,7 @@ export const SERVICE_LABELS: Record<Service, string> = {
|
||||
frontend: '前端',
|
||||
backend: '后端',
|
||||
license: '许可证',
|
||||
agent: '智能体',
|
||||
};
|
||||
|
||||
export const ENV_LABELS: Record<Environment, string> = {
|
||||
|
||||
Reference in New Issue
Block a user