feat: 添加开发模式支持,本地调试不使用 PM2

实现灵活的进程管理模式,支持开发和生产环境切换:

## 新增功能
- 创建开发模式进程管理服务(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 <noreply@anthropic.com>
This commit is contained in:
hughhuangandClaude Sonnet 4.5 committed 2026-01-02 23:20:19 +08:00
1 parent 903dc1e61f
commit 7dca4e93b1
13 files changed
+265 -50

No files matched your search

+2 -1
View File
@@ -7,7 +7,8 @@
"Bash(git commit:*)", "Bash(git commit:*)",
"Bash(git remote add:*)", "Bash(git remote add:*)",
"Bash(git branch:*)", "Bash(git branch:*)",
"Bash(git push:*)" "Bash(git push:*)",
"Bash(npm run typecheck:*)"
] ]
} }
} }
+5 -1
View File
@@ -5,7 +5,11 @@ NODE_ENV=development
# 访问密码(请修改为强密码) # 访问密码(请修改为强密码)
ACCESS_PASSWORD=admin123 ACCESS_PASSWORD=admin123
# PM2 配置 # 进程管理配置
# 开发环境设置为 false,生产环境设置为 true
USE_PM2=false
# PM2 配置(仅在生产模式使用)
PM2_HOME=~/.pm2 PM2_HOME=~/.pm2
# 实例配置 # 实例配置
+20 -6
View File
@@ -50,13 +50,12 @@ npm run install:all
```bash ```bash
# 复制环境变量模板 # 复制环境变量模板
cp .env.example .env cp .env.example backend/.env
# 编辑 .env 文件,设置必要的配置 # 编辑 backend/.env 文件,设置必要的配置
# 至少需要设置: # 至少需要设置:
# - JWT_SECRET: 随机字符串 # - ACCESS_PASSWORD: 访问密码(必填)
# - ADMIN_USERNAME: 管理员用户名 # - USE_PM2: 是否使用 PM2(开发环境设为 false,生产环境设为 true)
# - ADMIN_PASSWORD: 管理员密码
``` ```
### 开发 ### 开发
@@ -118,6 +117,7 @@ cc-cloud/
|--------|------|--------| |--------|------|--------|
| PORT | 后端服务端口 | 3000 | | PORT | 后端服务端口 | 3000 |
| ACCESS_PASSWORD | 访问密码 | admin123 | | ACCESS_PASSWORD | 访问密码 | admin123 |
| USE_PM2 | 是否使用 PM2 管理实例进程 | false |
| INSTANCE_PORT_RANGE_START | 实例端口范围起始 | 4000 | | INSTANCE_PORT_RANGE_START | 实例端口范围起始 | 4000 |
| INSTANCE_PORT_RANGE_END | 实例端口范围结束 | 4999 | | INSTANCE_PORT_RANGE_END | 实例端口范围结束 | 4999 |
| MAX_INSTANCES | 最大实例数量 | 10 | | MAX_INSTANCES | 最大实例数量 | 10 |
@@ -169,7 +169,21 @@ npm run test:coverage
- API Key 是否正确 - 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` 变量,然后重启后端服务。 编辑 `backend/.env` 文件,修改 `ACCESS_PASSWORD` 变量,然后重启后端服务。
+3 -3
View File
@@ -6,7 +6,7 @@ import { config } from './config';
import logger from './utils/logger'; import logger from './utils/logger';
import { initStorage } from './utils/storage'; import { initStorage } from './utils/storage';
import { initInstanceService } from './services/instance.service'; 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 { errorMiddleware, notFoundMiddleware } from './middleware/error.middleware';
import { import {
verifyPassword, verifyPassword,
@@ -45,8 +45,8 @@ app.use(express.json());
app.use(express.urlencoded({ extended: true })); app.use(express.urlencoded({ extended: true }));
// 请求日志 // 请求日志
app.use((req, res, next) => { app.use((_req, _res, next) => {
logger.info(`${req.method} ${req.path}`); logger.info(`${_req.method} ${_req.path}`);
next(); next();
}); });
+2 -1
View File
@@ -11,7 +11,8 @@ export const config = {
// 访问密码配置 // 访问密码配置
accessPassword: process.env.ACCESS_PASSWORD || 'admin123', 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'), pm2Home: process.env.PM2_HOME || path.join(process.env.HOME || '', '.pm2'),
// 实例配置 // 实例配置
+4 -4
View File
@@ -1,6 +1,5 @@
import { Request, Response } from 'express'; import { Request, Response } from 'express';
import jwt from 'jsonwebtoken'; import jwt from 'jsonwebtoken';
import { v4 as uuidv4 } from 'uuid';
import { config } from '../config'; import { config } from '../config';
import type { VerifyPasswordRequest, VerifyPasswordResponse, SessionPayload } from '../types'; import type { VerifyPasswordRequest, VerifyPasswordResponse, SessionPayload } from '../types';
import logger from '../utils/logger'; import logger from '../utils/logger';
@@ -20,14 +19,15 @@ setInterval(() => {
} }
}, 5 * 60 * 1000); }, 5 * 60 * 1000);
export async function verifyPassword(req: Request, res: Response) { export async function verifyPassword(req: Request, res: Response): Promise<void> {
try { try {
const { password }: VerifyPasswordRequest = req.body; const { password }: VerifyPasswordRequest = req.body;
// 验证密码 // 验证密码
if (password !== config.accessPassword) { if (password !== config.accessPassword) {
logger.warn('密码验证失败'); logger.warn('密码验证失败');
return res.status(401).json({ error: '密码错误' }); res.status(401).json({ error: '密码错误' });
return;
} }
// 生成会话 token // 生成会话 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<void> {
// 如果能到达这里,说明 token 已经被 authMiddleware 验证过 // 如果能到达这里,说明 token 已经被 authMiddleware 验证过
res.json({ res.json({
valid: true, valid: true,
+10 -8
View File
@@ -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<void> {
try { try {
const instance = await createInstance(req.body); const instance = await createInstance(req.body);
res.status(201).json({ instance }); 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<void> {
try { try {
const { instanceId } = req.params; const { instanceId } = req.params;
await startInstance(instanceId); 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<void> {
try { try {
const { instanceId } = req.params; const { instanceId } = req.params;
await stopInstance(instanceId); 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<void> {
try { try {
const instances = await getAllInstances(); const instances = await getAllInstances();
res.json({ instances }); 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<void> {
try { try {
const { instanceId } = req.params; const { instanceId } = req.params;
const instance = await getInstance(instanceId); const instance = await getInstance(instanceId);
if (!instance) { if (!instance) {
return res.status(404).json({ error: '实例不存在' }); res.status(404).json({ error: '实例不存在' });
return;
} }
res.json({ instance }); 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<void> {
try { try {
const { instanceId } = req.params; const { instanceId } = req.params;
const instance = await getInstance(instanceId); const instance = await getInstance(instanceId);
if (!instance) { if (!instance) {
return res.status(404).json({ error: '实例不存在' }); res.status(404).json({ error: '实例不存在' });
return;
} }
res.json({ res.json({
+9 -6
View File
@@ -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; const authHeader = req.headers.authorization;
if (!authHeader) { if (!authHeader) {
return res.status(401).json({ error: '未提供认证令牌' }); res.status(401).json({ error: '未提供认证令牌' });
return;
} }
const token = authHeader.replace('Bearer ', ''); 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; const decoded = jwt.verify(token, config.accessPassword) as SessionPayload;
if (!decoded.authenticated) { if (!decoded.authenticated) {
return res.status(401).json({ error: '无效的认证令牌' }); res.status(401).json({ error: '无效的认证令牌' });
return;
} }
req.session = decoded; req.session = decoded;
next(); next();
} catch (error: any) { } catch (error: any) {
logger.error('Token 验证失败', error); 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; const authHeader = req.headers.authorization;
if (!authHeader) { if (!authHeader) {
return next(); next();
return;
} }
const token = authHeader.replace('Bearer ', ''); const token = authHeader.replace('Bearer ', '');
+1 -1
View File
@@ -5,7 +5,7 @@ export function errorMiddleware(
error: Error, error: Error,
req: Request, req: Request,
res: Response, res: Response,
next: NextFunction _next: NextFunction
) { ) {
logger.error('请求处理错误', { logger.error('请求处理错误', {
error: error.message, error: error.message,
@@ -14,10 +14,11 @@ export function validate(schema: AnyZodObject) {
} catch (error) { } catch (error) {
if (error instanceof ZodError) { if (error instanceof ZodError) {
logger.error('验证失败', { errors: error.errors }); logger.error('验证失败', { errors: error.errors });
return res.status(400).json({ res.status(400).json({
error: '请求数据验证失败', error: '请求数据验证失败',
details: error.errors, details: error.errors,
}); });
return;
} }
next(error); next(error);
} }
+157
View File
@@ -0,0 +1,157 @@
import { spawn, ChildProcess } from 'child_process';
import type { InstanceConfig } from '../types';
import logger from '../utils/logger';
// 进程存储
const processes = new Map<string, ChildProcess>();
// 启动进程
export async function startDevProcess(instanceId: string, config: InstanceConfig): Promise<void> {
const { port, workingDir, apiKey, env } = config;
// 环境变量
const processEnv: Record<string, string> = {
...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<void>((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<void> {
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<void>((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<void> {
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<boolean> {
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,
}));
}
+50 -17
View File
@@ -1,8 +1,10 @@
import { v4 as uuidv4 } from 'uuid'; import { v4 as uuidv4 } from 'uuid';
import type { Instance, CreateInstanceRequest, InstanceStats } from '../types'; 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 { 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 logger from '../utils/logger';
import fs from 'fs/promises'; import fs from 'fs/promises';
@@ -13,7 +15,9 @@ export async function initInstanceService() {
.filter(i => i.config.port) .filter(i => i.config.port)
.map(i => i.config.port!); .map(i => i.config.port!);
initPortAllocations(ports); 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<void> {
throw new Error('实例已在运行中'); throw new Error('实例已在运行中');
} }
const { config, id } = instance; const { config: instanceConfig, id } = instance;
try { try {
// PM2 启动选项 if (config.usePM2) {
// 生产模式:使用 PM2
const pm2Options = { const pm2Options = {
name: id, name: id,
script: 'npx', script: 'npx',
args: ['@anthropic-ai/claude-code', 'serve', '--port', config.port!.toString()], args: ['@anthropic-ai/claude-code', 'serve', '--port', instanceConfig.port!.toString()],
cwd: config.workingDir, cwd: instanceConfig.workingDir,
env: { env: {
...config.env, ...instanceConfig.env,
ANTHROPIC_API_KEY: config.apiKey || process.env.ANTHROPIC_API_KEY, ANTHROPIC_API_KEY: instanceConfig.apiKey || process.env.ANTHROPIC_API_KEY,
PORT: config.port!.toString(), PORT: instanceConfig.port!.toString(),
}, },
error_file: `data/logs/${id}-error.log`, error_file: `data/logs/${id}-error.log`,
out_file: `data/logs/${id}-out.log`, out_file: `data/logs/${id}-out.log`,
max_memory_restart: config.maxMemory ? `${config.maxMemory}M` : undefined, 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.status = 'running';
instance.lastStarted = new Date(); instance.lastStarted = new Date();
instance.stats.port = config.port; instance.stats.port = instanceConfig.port;
await writeInstance(instance); await writeInstance(instance);
logger.info('实例已启动', { instanceId, port: config.port }); logger.info('实例已启动', { instanceId, port: instanceConfig.port, mode: config.usePM2 ? 'PM2' : 'Dev' });
} catch (error) { } catch (error) {
instance.status = 'errored'; instance.status = 'errored';
await writeInstance(instance); await writeInstance(instance);
@@ -111,7 +120,11 @@ export async function stopInstance(instanceId: string): Promise<void> {
} }
try { try {
if (config.usePM2) {
await stopProcess(instanceId); await stopProcess(instanceId);
} else {
await stopDevProcess(instanceId);
}
instance.status = 'stopped'; instance.status = 'stopped';
instance.stats.pid = undefined; instance.stats.pid = undefined;
@@ -119,7 +132,7 @@ export async function stopInstance(instanceId: string): Promise<void> {
instance.stats.status = 'offline'; instance.stats.status = 'offline';
await writeInstance(instance); await writeInstance(instance);
logger.info('实例已停止', { instanceId }); logger.info('实例已停止', { instanceId, mode: config.usePM2 ? 'PM2' : 'Dev' });
} catch (error) { } catch (error) {
throw error; throw error;
} }
@@ -137,9 +150,12 @@ export async function removeInstance(instanceId: string): Promise<void> {
await stopInstance(instanceId); await stopInstance(instanceId);
} }
// 删除 PM2 进程
try { try {
if (config.usePM2) {
await deleteProcess(instanceId); await deleteProcess(instanceId);
} else {
await deleteDevProcess(instanceId);
}
} catch (error) { } catch (error) {
// 忽略删除进程的错误 // 忽略删除进程的错误
} }
@@ -162,6 +178,8 @@ export async function getInstanceStatus(instanceId: string): Promise<InstanceSta
throw new Error('实例不存在'); throw new Error('实例不存在');
} }
if (config.usePM2) {
// PM2 模式:从 PM2 获取详细状态
const process = await describeProcess(instanceId); const process = await describeProcess(instanceId);
if (process) { if (process) {
@@ -177,14 +195,29 @@ export async function getInstanceStatus(instanceId: string): Promise<InstanceSta
status: isRunning ? 'online' : 'offline', status: isRunning ? 'online' : 'offline',
}; };
// 更新状态
instance.status = isRunning ? 'running' : 'stopped'; instance.status = isRunning ? 'running' : 'stopped';
await writeInstance(instance);
} else { } else {
instance.stats.status = 'offline'; instance.stats.status = 'offline';
instance.status = 'stopped'; instance.status = 'stopped';
} }
} else {
// 开发模式:简化状态
const isRunning = await isDevProcessRunning(instanceId);
instance.stats = {
pid: undefined, // 开发模式下不返回 PID
port: instance.config.port,
uptime: instance.status === 'running' ? 1 : 0, // 简化
memory: 0, // 开发模式下不监控内存
cpu: 0, // 开发模式下不监控 CPU
restarts: 0,
status: isRunning ? 'online' : 'offline',
};
instance.status = isRunning ? 'running' : 'stopped';
}
await writeInstance(instance);
return instance.stats; return instance.stats;
} }
-1
View File
@@ -1,6 +1,5 @@
import winston from 'winston'; import winston from 'winston';
import DailyRotateFile from 'winston-daily-rotate-file'; import DailyRotateFile from 'winston-daily-rotate-file';
import path from 'path';
import { config } from '../config'; import { config } from '../config';
const logDir = config.logDir; const logDir = config.logDir;