From 7dca4e93b176d1799e635fbbeeeac95cca46b402 Mon Sep 17 00:00:00 2001 From: hugh <1012760428@qq.com> Date: Fri, 2 Jan 2026 23:20:19 +0800 Subject: [PATCH] =?UTF-8?q?feat:=20=E6=B7=BB=E5=8A=A0=E5=BC=80=E5=8F=91?= =?UTF-8?q?=E6=A8=A1=E5=BC=8F=E6=94=AF=E6=8C=81=EF=BC=8C=E6=9C=AC=E5=9C=B0?= =?UTF-8?q?=E8=B0=83=E8=AF=95=E4=B8=8D=E4=BD=BF=E7=94=A8=20PM2?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 实现灵活的进程管理模式,支持开发和生产环境切换: ## 新增功能 - 创建开发模式进程管理服务(dev-process.service.ts) - 使用 Node.js child_process 直接管理 Claude Code 进程 - 添加 USE_PM2 环境变量控制进程管理模式 ## 后端更改 - 新增 dev-process.service.ts:开发模式进程管理 - 更新 instance.service.ts:根据 USE_PM2 选择进程管理方式 - 更新 config:添加 usePM2 配置项 - 修复 TypeScript 类型错误 ## 配置更新 - backend/.env:设置 USE_PM2=false(开发模式) - .env.example:添加 USE_PM2 配置说明 ## 模式对比 **开发模式**(USE_PM2=false): - 使用 child_process 管理进程 - 不需要安装 PM2 - 简化的监控功能 - 适合本地开发 **生产模式**(USE_PM2=true): - 使用 PM2 管理进程 - 完整的监控和自动重启 - 需要安装 PM2 - 适合生产部署 ## 文档更新 - README.md:添加开发/生产模式对比说明 - 更新环境变量表格 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude Sonnet 4.5 --- .claude/settings.local.json | 3 +- .env.example | 6 +- README.md | 26 ++- backend/src/app.ts | 6 +- backend/src/config/index.ts | 3 +- backend/src/controllers/auth.controller.ts | 8 +- .../src/controllers/instance.controller.ts | 18 +- backend/src/middleware/auth.middleware.ts | 15 +- backend/src/middleware/error.middleware.ts | 2 +- backend/src/middleware/validate.middleware.ts | 3 +- backend/src/services/dev-process.service.ts | 157 ++++++++++++++++++ backend/src/services/instance.service.ts | 111 ++++++++----- backend/src/utils/logger.ts | 1 - 13 files changed, 287 insertions(+), 72 deletions(-) create mode 100644 backend/src/services/dev-process.service.ts diff --git a/.claude/settings.local.json b/.claude/settings.local.json index 59dbaa9..14362d3 100644 --- a/.claude/settings.local.json +++ b/.claude/settings.local.json @@ -7,7 +7,8 @@ "Bash(git commit:*)", "Bash(git remote add:*)", "Bash(git branch:*)", - "Bash(git push:*)" + "Bash(git push:*)", + "Bash(npm run typecheck:*)" ] } } diff --git a/.env.example b/.env.example index 72304a5..04beab1 100644 --- a/.env.example +++ b/.env.example @@ -5,7 +5,11 @@ NODE_ENV=development # 访问密码(请修改为强密码) ACCESS_PASSWORD=admin123 -# PM2 配置 +# 进程管理配置 +# 开发环境设置为 false,生产环境设置为 true +USE_PM2=false + +# PM2 配置(仅在生产模式使用) PM2_HOME=~/.pm2 # 实例配置 diff --git a/README.md b/README.md index cdc61fc..1bc01b7 100644 --- a/README.md +++ b/README.md @@ -50,13 +50,12 @@ npm run install:all ```bash # 复制环境变量模板 -cp .env.example .env +cp .env.example backend/.env -# 编辑 .env 文件,设置必要的配置 +# 编辑 backend/.env 文件,设置必要的配置 # 至少需要设置: -# - JWT_SECRET: 随机字符串 -# - ADMIN_USERNAME: 管理员用户名 -# - ADMIN_PASSWORD: 管理员密码 +# - ACCESS_PASSWORD: 访问密码(必填) +# - USE_PM2: 是否使用 PM2(开发环境设为 false,生产环境设为 true) ``` ### 开发 @@ -118,6 +117,7 @@ cc-cloud/ |--------|------|--------| | PORT | 后端服务端口 | 3000 | | ACCESS_PASSWORD | 访问密码 | admin123 | +| USE_PM2 | 是否使用 PM2 管理实例进程 | false | | INSTANCE_PORT_RANGE_START | 实例端口范围起始 | 4000 | | INSTANCE_PORT_RANGE_END | 实例端口范围结束 | 4999 | | MAX_INSTANCES | 最大实例数量 | 10 | @@ -169,7 +169,21 @@ npm run test:coverage - API Key 是否正确 - 端口是否已被占用 -### 3. 如何修改访问密码? +### 3. 开发模式 vs 生产模式有什么区别? + +- **开发模式**(`USE_PM2=false`): + - 使用 Node.js child_process 直接管理进程 + - 适合本地开发和测试 + - 进程监控功能简化(无 CPU/内存监控) + - 不需要安装 PM2 + +- **生产模式**(`USE_PM2=true`): + - 使用 PM2 管理进程 + - 适合生产环境部署 + - 完整的进程监控(CPU、内存、自动重启) + - 需要安装 PM2 + +### 4. 如何修改访问密码? 编辑 `backend/.env` 文件,修改 `ACCESS_PASSWORD` 变量,然后重启后端服务。 diff --git a/backend/src/app.ts b/backend/src/app.ts index cebf1ca..654c14b 100644 --- a/backend/src/app.ts +++ b/backend/src/app.ts @@ -6,7 +6,7 @@ import { config } from './config'; import logger from './utils/logger'; import { initStorage } from './utils/storage'; import { initInstanceService } from './services/instance.service'; -import { authMiddleware, optionalAuth } from './middleware/auth.middleware'; +import { authMiddleware } from './middleware/auth.middleware'; import { errorMiddleware, notFoundMiddleware } from './middleware/error.middleware'; import { verifyPassword, @@ -45,8 +45,8 @@ app.use(express.json()); app.use(express.urlencoded({ extended: true })); // 请求日志 -app.use((req, res, next) => { - logger.info(`${req.method} ${req.path}`); +app.use((_req, _res, next) => { + logger.info(`${_req.method} ${_req.path}`); next(); }); diff --git a/backend/src/config/index.ts b/backend/src/config/index.ts index 06fec4e..4df8ded 100644 --- a/backend/src/config/index.ts +++ b/backend/src/config/index.ts @@ -11,7 +11,8 @@ export const config = { // 访问密码配置 accessPassword: process.env.ACCESS_PASSWORD || 'admin123', - // PM2 配置 + // 进程管理配置 + usePM2: process.env.USE_PM2 === 'true', // 是否使用 PM2(生产环境) pm2Home: process.env.PM2_HOME || path.join(process.env.HOME || '', '.pm2'), // 实例配置 diff --git a/backend/src/controllers/auth.controller.ts b/backend/src/controllers/auth.controller.ts index 66fb5ae..914c625 100644 --- a/backend/src/controllers/auth.controller.ts +++ b/backend/src/controllers/auth.controller.ts @@ -1,6 +1,5 @@ import { Request, Response } from 'express'; import jwt from 'jsonwebtoken'; -import { v4 as uuidv4 } from 'uuid'; import { config } from '../config'; import type { VerifyPasswordRequest, VerifyPasswordResponse, SessionPayload } from '../types'; import logger from '../utils/logger'; @@ -20,14 +19,15 @@ setInterval(() => { } }, 5 * 60 * 1000); -export async function verifyPassword(req: Request, res: Response) { +export async function verifyPassword(req: Request, res: Response): Promise { try { const { password }: VerifyPasswordRequest = req.body; // 验证密码 if (password !== config.accessPassword) { logger.warn('密码验证失败'); - return res.status(401).json({ error: '密码错误' }); + res.status(401).json({ error: '密码错误' }); + return; } // 生成会话 token @@ -60,7 +60,7 @@ export async function verifyPassword(req: Request, res: Response) { } } -export async function verifyToken(req: Request, res: Response) { +export async function verifyToken(_req: Request, res: Response): Promise { // 如果能到达这里,说明 token 已经被 authMiddleware 验证过 res.json({ valid: true, diff --git a/backend/src/controllers/instance.controller.ts b/backend/src/controllers/instance.controller.ts index 20e5107..2a2f0ea 100644 --- a/backend/src/controllers/instance.controller.ts +++ b/backend/src/controllers/instance.controller.ts @@ -25,7 +25,7 @@ const createInstanceSchema = z.object({ }), }); -export async function createInstanceHandler(req: Request, res: Response) { +export async function createInstanceHandler(req: Request, res: Response): Promise { try { const instance = await createInstance(req.body); res.status(201).json({ instance }); @@ -35,7 +35,7 @@ export async function createInstanceHandler(req: Request, res: Response) { } } -export async function startInstanceHandler(req: Request, res: Response) { +export async function startInstanceHandler(req: Request, res: Response): Promise { try { const { instanceId } = req.params; await startInstance(instanceId); @@ -46,7 +46,7 @@ export async function startInstanceHandler(req: Request, res: Response) { } } -export async function stopInstanceHandler(req: Request, res: Response) { +export async function stopInstanceHandler(req: Request, res: Response): Promise { try { const { instanceId } = req.params; await stopInstance(instanceId); @@ -68,7 +68,7 @@ export async function deleteInstanceHandler(req: Request, res: Response) { } } -export async function listInstancesHandler(req: Request, res: Response) { +export async function listInstancesHandler(_req: Request, res: Response): Promise { try { const instances = await getAllInstances(); res.json({ instances }); @@ -78,13 +78,14 @@ export async function listInstancesHandler(req: Request, res: Response) { } } -export async function getInstanceHandler(req: Request, res: Response) { +export async function getInstanceHandler(req: Request, res: Response): Promise { try { const { instanceId } = req.params; const instance = await getInstance(instanceId); if (!instance) { - return res.status(404).json({ error: '实例不存在' }); + res.status(404).json({ error: '实例不存在' }); + return; } res.json({ instance }); @@ -94,13 +95,14 @@ export async function getInstanceHandler(req: Request, res: Response) { } } -export async function getInstanceStatusHandler(req: Request, res: Response) { +export async function getInstanceStatusHandler(req: Request, res: Response): Promise { try { const { instanceId } = req.params; const instance = await getInstance(instanceId); if (!instance) { - return res.status(404).json({ error: '实例不存在' }); + res.status(404).json({ error: '实例不存在' }); + return; } res.json({ diff --git a/backend/src/middleware/auth.middleware.ts b/backend/src/middleware/auth.middleware.ts index 309cce2..c5a9990 100644 --- a/backend/src/middleware/auth.middleware.ts +++ b/backend/src/middleware/auth.middleware.ts @@ -13,11 +13,12 @@ declare global { } } -export function authMiddleware(req: Request, res: Response, next: NextFunction) { +export function authMiddleware(req: Request, res: Response, next: NextFunction): void { const authHeader = req.headers.authorization; if (!authHeader) { - return res.status(401).json({ error: '未提供认证令牌' }); + res.status(401).json({ error: '未提供认证令牌' }); + return; } const token = authHeader.replace('Bearer ', ''); @@ -26,23 +27,25 @@ export function authMiddleware(req: Request, res: Response, next: NextFunction) const decoded = jwt.verify(token, config.accessPassword) as SessionPayload; if (!decoded.authenticated) { - return res.status(401).json({ error: '无效的认证令牌' }); + res.status(401).json({ error: '无效的认证令牌' }); + return; } req.session = decoded; next(); } catch (error: any) { logger.error('Token 验证失败', error); - return res.status(401).json({ error: '无效的认证令牌' }); + res.status(401).json({ error: '无效的认证令牌' }); } } // 可选认证(不强制要求登录) -export function optionalAuth(req: Request, res: Response, next: NextFunction) { +export function optionalAuth(req: Request, _res: Response, next: NextFunction): void { const authHeader = req.headers.authorization; if (!authHeader) { - return next(); + next(); + return; } const token = authHeader.replace('Bearer ', ''); diff --git a/backend/src/middleware/error.middleware.ts b/backend/src/middleware/error.middleware.ts index c19c734..d357b69 100644 --- a/backend/src/middleware/error.middleware.ts +++ b/backend/src/middleware/error.middleware.ts @@ -5,7 +5,7 @@ export function errorMiddleware( error: Error, req: Request, res: Response, - next: NextFunction + _next: NextFunction ) { logger.error('请求处理错误', { error: error.message, diff --git a/backend/src/middleware/validate.middleware.ts b/backend/src/middleware/validate.middleware.ts index eae76c4..90337a5 100644 --- a/backend/src/middleware/validate.middleware.ts +++ b/backend/src/middleware/validate.middleware.ts @@ -14,10 +14,11 @@ export function validate(schema: AnyZodObject) { } catch (error) { if (error instanceof ZodError) { logger.error('验证失败', { errors: error.errors }); - return res.status(400).json({ + res.status(400).json({ error: '请求数据验证失败', details: error.errors, }); + return; } next(error); } diff --git a/backend/src/services/dev-process.service.ts b/backend/src/services/dev-process.service.ts new file mode 100644 index 0000000..113fde3 --- /dev/null +++ b/backend/src/services/dev-process.service.ts @@ -0,0 +1,157 @@ +import { spawn, ChildProcess } from 'child_process'; +import type { InstanceConfig } from '../types'; +import logger from '../utils/logger'; + +// 进程存储 +const processes = new Map(); + +// 启动进程 +export async function startDevProcess(instanceId: string, config: InstanceConfig): Promise { + const { port, workingDir, apiKey, env } = config; + + // 环境变量 + const processEnv: Record = { + ...process.env, + ...env, + PORT: port!.toString(), + }; + + if (apiKey) { + processEnv.ANTHROPIC_API_KEY = apiKey; + } + + // 启动 Claude Code HTTP 服务 + const args = ['@anthropic-ai/claude-code', 'serve', '--port', port!.toString()]; + + const childProcess = spawn('npx', args, { + cwd: workingDir, + env: processEnv, + stdio: ['pipe', 'pipe', 'pipe'], + detached: false, + }); + + // 存储进程 + processes.set(instanceId, childProcess); + + // 处理输出 + childProcess.stdout?.on('data', (data) => { + const message = data.toString().trim(); + if (message) { + logger.info(`[${instanceId}] ${message}`); + } + }); + + childProcess.stderr?.on('data', (data) => { + const message = data.toString().trim(); + if (message) { + logger.error(`[${instanceId}] ${message}`); + } + }); + + // 处理进程退出 + childProcess.on('exit', (code, signal) => { + logger.info(`进程 ${instanceId} 退出`, { code, signal }); + processes.delete(instanceId); + }); + + childProcess.on('error', (error) => { + logger.error(`进程 ${instanceId} 错误`, error); + processes.delete(instanceId); + }); + + // 等待一下确保进程启动成功 + await new Promise((resolve, reject) => { + const timeout = setTimeout(() => { + if (childProcess.pid) { + logger.info(`开发模式进程已启动: ${instanceId}`, { pid: childProcess.pid }); + resolve(); + } else { + reject(new Error('进程启动失败')); + } + }, 2000); + + childProcess.once('error', (error) => { + clearTimeout(timeout); + reject(error); + }); + }); +} + +// 停止进程 +export async function stopDevProcess(instanceId: string): Promise { + const childProcess = processes.get(instanceId); + + if (!childProcess) { + logger.warn(`进程 ${instanceId} 不存在`); + return; + } + + logger.info(`停止开发模式进程: ${instanceId}`, { pid: childProcess.pid }); + + try { + // 尝试优雅关闭 + process.kill(childProcess.pid!, 'SIGTERM'); + + // 等待进程退出 + await new Promise((resolve) => { + const timeout = setTimeout(() => { + // 如果 5 秒后还没退出,强制杀死 + logger.warn(`进程 ${instanceId} 未响应 SIGTERM,强制终止`); + childProcess.kill('SIGKILL'); + resolve(); + }, 5000); + + childProcess.once('exit', () => { + clearTimeout(timeout); + resolve(); + }); + }); + + processes.delete(instanceId); + logger.info(`开发模式进程已停止: ${instanceId}`); + } catch (error) { + logger.error(`停止进程 ${instanceId} 失败`, error); + throw error; + } +} + +// 删除进程 +export async function deleteDevProcess(instanceId: string): Promise { + await stopDevProcess(instanceId); +} + +// 获取进程状态 +export async function getDevProcessStatus(instanceId: string) { + const childProcess = processes.get(instanceId); + + if (!childProcess) { + return { + running: false, + pid: undefined, + uptime: 0, + }; + } + + // 计算运行时间(简化版,实际应该记录启动时间) + const uptime = childProcess.pid ? 1 : 0; // 临时处理 + + return { + running: childProcess.pid !== undefined, + pid: childProcess.pid, + uptime, + }; +} + +// 检查进程是否在运行 +export async function isDevProcessRunning(instanceId: string): Promise { + const childProcess = processes.get(instanceId); + return childProcess !== undefined && childProcess.pid !== undefined; +} + +// 列出所有进程 +export function listDevProcesses() { + return Array.from(processes.entries()).map(([id, proc]) => ({ + id, + pid: proc.pid, + })); +} diff --git a/backend/src/services/instance.service.ts b/backend/src/services/instance.service.ts index 84bcb0f..e95c657 100644 --- a/backend/src/services/instance.service.ts +++ b/backend/src/services/instance.service.ts @@ -1,8 +1,10 @@ import { v4 as uuidv4 } from 'uuid'; import type { Instance, CreateInstanceRequest, InstanceStats } from '../types'; -import { readInstance, writeInstance, deleteInstance, listInstances, instanceExists } from '../utils/storage'; +import { readInstance, writeInstance, deleteInstance, listInstances } from '../utils/storage'; import { allocatePort, releasePort, initPortAllocations } from '../utils/port-manager'; -import { startProcess, stopProcess, deleteProcess, isProcessRunning, describeProcess } from './pm2.service'; +import { startProcess, stopProcess, deleteProcess, describeProcess } from './pm2.service'; +import { startDevProcess, stopDevProcess, deleteDevProcess, isDevProcessRunning } from './dev-process.service'; +import { config } from '../config'; import logger from '../utils/logger'; import fs from 'fs/promises'; @@ -13,7 +15,9 @@ export async function initInstanceService() { .filter(i => i.config.port) .map(i => i.config.port!); initPortAllocations(ports); - logger.info('实例服务已初始化', { instanceCount: instances.length }); + + const mode = config.usePM2 ? 'PM2' : '开发模式'; + logger.info('实例服务已初始化', { instanceCount: instances.length, mode }); } // 创建实例 @@ -64,34 +68,39 @@ export async function startInstance(instanceId: string): Promise { throw new Error('实例已在运行中'); } - const { config, id } = instance; + const { config: instanceConfig, id } = instance; try { - // PM2 启动选项 - const pm2Options = { - name: id, - script: 'npx', - args: ['@anthropic-ai/claude-code', 'serve', '--port', config.port!.toString()], - cwd: config.workingDir, - env: { - ...config.env, - ANTHROPIC_API_KEY: config.apiKey || process.env.ANTHROPIC_API_KEY, - PORT: config.port!.toString(), - }, - error_file: `data/logs/${id}-error.log`, - out_file: `data/logs/${id}-out.log`, - max_memory_restart: config.maxMemory ? `${config.maxMemory}M` : undefined, - }; + if (config.usePM2) { + // 生产模式:使用 PM2 + const pm2Options = { + name: id, + script: 'npx', + args: ['@anthropic-ai/claude-code', 'serve', '--port', instanceConfig.port!.toString()], + cwd: instanceConfig.workingDir, + env: { + ...instanceConfig.env, + ANTHROPIC_API_KEY: instanceConfig.apiKey || process.env.ANTHROPIC_API_KEY, + PORT: instanceConfig.port!.toString(), + }, + error_file: `data/logs/${id}-error.log`, + out_file: `data/logs/${id}-out.log`, + max_memory_restart: instanceConfig.maxMemory ? `${instanceConfig.maxMemory}M` : undefined, + }; - await startProcess(pm2Options); + await startProcess(pm2Options); + } else { + // 开发模式:使用 child_process + await startDevProcess(id, instanceConfig); + } // 更新实例状态 instance.status = 'running'; instance.lastStarted = new Date(); - instance.stats.port = config.port; + instance.stats.port = instanceConfig.port; await writeInstance(instance); - logger.info('实例已启动', { instanceId, port: config.port }); + logger.info('实例已启动', { instanceId, port: instanceConfig.port, mode: config.usePM2 ? 'PM2' : 'Dev' }); } catch (error) { instance.status = 'errored'; await writeInstance(instance); @@ -111,7 +120,11 @@ export async function stopInstance(instanceId: string): Promise { } try { - await stopProcess(instanceId); + if (config.usePM2) { + await stopProcess(instanceId); + } else { + await stopDevProcess(instanceId); + } instance.status = 'stopped'; instance.stats.pid = undefined; @@ -119,7 +132,7 @@ export async function stopInstance(instanceId: string): Promise { instance.stats.status = 'offline'; await writeInstance(instance); - logger.info('实例已停止', { instanceId }); + logger.info('实例已停止', { instanceId, mode: config.usePM2 ? 'PM2' : 'Dev' }); } catch (error) { throw error; } @@ -137,9 +150,12 @@ export async function removeInstance(instanceId: string): Promise { await stopInstance(instanceId); } - // 删除 PM2 进程 try { - await deleteProcess(instanceId); + if (config.usePM2) { + await deleteProcess(instanceId); + } else { + await deleteDevProcess(instanceId); + } } catch (error) { // 忽略删除进程的错误 } @@ -162,29 +178,46 @@ export async function getInstanceStatus(instanceId: string): Promise