-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.py
More file actions
534 lines (451 loc) · 20.2 KB
/
main.py
File metadata and controls
534 lines (451 loc) · 20.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
import os
import sys
import argparse
import subprocess
import asyncio
from pathlib import Path
from typing import Optional
import uvicorn
from judge_micro.config.settings import setting
class JudgeMicroRunner:
"""Judge Micro API and MCP Server Runner"""
def __init__(self):
self.base_dir = Path(__file__).parent
def check_environment(self) -> bool:
"""Check runtime environment"""
print("🔍 Checking runtime environment...")
# Check Docker
try:
subprocess.run(["docker", "--version"],
capture_output=True, check=True)
subprocess.run(["docker", "info"],
capture_output=True, check=True)
except (subprocess.CalledProcessError, FileNotFoundError):
print("❌ Docker is not installed or service is not running")
return False
print("✅ Environment check passed")
return True
def check_mcp_dependencies(self) -> bool:
"""Check MCP dependencies"""
try:
import fastmcp
import httpx
print("✅ MCP dependencies available")
return True
except ImportError as e:
print(f"❌ MCP dependencies missing: {e}")
print("💡 Install with: pip install fastmcp httpx")
return False
def start_development(self, host: str = None, port: int = None) -> None:
"""Start development server (Uvicorn with reload)"""
print("🚀 Starting development server (Uvicorn with reload)...")
# Use setting defaults if not provided
if host is None:
host = setting.JUDGE_HOST
if port is None:
port = setting.JUDGE_PORT
# Set environment variable for debug mode
os.environ['JUDGE_IS_DEBUG'] = 'true'
uvicorn.run(
"judge_micro.api.main:get_app",
host=host,
port=port,
reload=True,
reload_dirs=[str(self.base_dir / "src")],
factory=True,
log_level="debug",
access_log=True
)
def start_production(self, host: str = None, port: int = None, workers: int = None) -> None:
"""Start production server (Gunicorn with multiple workers)"""
print("🚀 Starting production server (Gunicorn)...")
# Use setting defaults if not provided
if host is None:
host = setting.JUDGE_HOST
if port is None:
port = setting.JUDGE_PORT
if workers is None:
workers = min(4, (os.cpu_count() or 1) + 1)
# Set environment variable for production mode
os.environ['JUDGE_IS_DEBUG'] = 'false'
print(f"📊 Using {workers} workers")
# Build Gunicorn command with all configuration parameters
cmd = [
"gunicorn",
"judge_micro.api.main:get_app()",
# Worker configuration
"--worker-class", "uvicorn.workers.UvicornWorker",
"--workers", str(workers),
"--worker-connections", "1000",
# Server socket
"--bind", f"{host}:{port}",
"--backlog", "2048",
# Timeout settings
"--timeout", "120",
"--keep-alive", "30",
"--graceful-timeout", "30",
# Request limits
"--max-requests", "1000",
"--max-requests-jitter", "50",
"--limit-request-line", "8192",
"--limit-request-fields", "200",
"--limit-request-field-size", "8190",
# Process management
"--preload-app",
"--enable-stdio-inheritance",
# Logging
"--access-logfile", "-",
"--error-logfile", "-",
"--log-level", "info",
"--access-logformat", '%(h)s %(l)s %(u)s %(t)s "%(r)s" %(s)s %(b)s "%(f)s" "%(a)s" %(D)s',
# Performance
"--worker-tmp-dir", "/dev/shm" if os.path.exists("/dev/shm") else "/tmp",
]
try:
subprocess.run(cmd, check=True)
except subprocess.CalledProcessError as e:
print(f"❌ Failed to start production server: {e}")
sys.exit(1)
except KeyboardInterrupt:
print("\n👋 Shutting down production server...")
async def start_mcp_server(
self,
transport: str = "http",
host: str = "127.0.0.1",
port: int = 8001,
api_base_url: str = None,
with_api_server: bool = True
) -> None:
"""Start MCP server with Judge Micro API integration"""
print("🔗 Starting Judge Micro MCP Server...")
if not self.check_mcp_dependencies():
print("❌ Cannot start MCP server without dependencies")
return
try:
from judge_micro.mcp.server import run_mcp_server
print(f"🎯 MCP Server Configuration:")
print(f" Transport: {transport}")
if transport != "stdio":
print(f" Address: {transport}://{host}:{port}")
if api_base_url:
print(f" API URL: {api_base_url}")
with_api_server = False
else:
if with_api_server:
print(f" API Server: Starting local instance on {setting.JUDGE_HOST}:{setting.JUDGE_PORT}")
else:
print(" API Server: External (specify --api-url)")
print("🚀 Creating judge microservice instance...")
print("🚀 Judge microservice is ready")
await run_mcp_server(
transport=transport,
host=host,
port=port,
api_base_url=api_base_url,
with_api_server=with_api_server
)
except ImportError as e:
print(f"❌ MCP server import failed: {e}")
print("💡 Make sure MCP modules are properly installed")
except Exception as e:
print(f"❌ MCP server failed: {e}")
raise
def start_combined_server(
self,
api_host: str = None,
api_port: int = None,
mcp_host: str = "127.0.0.1",
mcp_port: int = 8001,
mcp_transport: str = "http"
) -> None:
"""Start both API and MCP servers in development mode"""
print("🚀 Starting Combined Server (API + MCP)...")
if not self.check_mcp_dependencies():
print("❌ Cannot start combined server without MCP dependencies")
return
# Use defaults
if api_host is None:
api_host = setting.JUDGE_HOST
if api_port is None:
api_port = setting.JUDGE_PORT
print(f"📊 Configuration:")
print(f" API Server: http://{api_host}:{api_port}")
print(f" MCP Server: {mcp_transport}://{mcp_host}:{mcp_port}")
try:
asyncio.run(self.start_mcp_server(
transport=mcp_transport,
host=mcp_host,
port=mcp_port,
with_api_server=True
))
except KeyboardInterrupt:
print("\n👋 Shutting down combined server...")
def start_production_with_mcp(
self,
api_host: str = None,
api_port: int = None,
workers: int = None,
mcp_host: str = "127.0.0.1",
mcp_port: int = 8001,
mcp_transport: str = "http"
) -> None:
"""Start production API server with MCP server"""
print("🚀 Starting Production Server with MCP...")
if not self.check_mcp_dependencies():
print("❌ Cannot start production+MCP server without MCP dependencies")
return
# Use setting defaults if not provided
if api_host is None:
api_host = setting.JUDGE_HOST
if api_port is None:
api_port = setting.JUDGE_PORT
if workers is None:
workers = min(4, (os.cpu_count() or 1) + 1)
# Check if ports are available
import socket
def is_port_in_use(host, port):
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
try:
s.bind((host, port))
return False
except OSError:
return True
# Check API port
if is_port_in_use(api_host, api_port):
print(f"❌ Port {api_port} is already in use. Please stop existing services or use a different port.")
print(f"💡 Try: pkill -f 'gunicorn.*judge_micro' or use --api-port <different_port>")
return
# Check MCP port
if is_port_in_use(mcp_host, mcp_port):
print(f"❌ Port {mcp_port} is already in use. Please stop existing services or use a different port.")
print(f"💡 Try: lsof -ti:{mcp_port} | xargs kill or use --port <different_port>")
return
print(f"📊 Production+MCP Configuration:")
print(f" API Server: http://{api_host}:{api_port} (Gunicorn, {workers} workers)")
print(f" MCP Server: {mcp_transport}://{mcp_host}:{mcp_port}")
import threading
import time
# Set environment variable for production mode
os.environ['JUDGE_IS_DEBUG'] = 'false'
# API Server configuration
api_cmd = [
"gunicorn",
"judge_micro.api.main:get_app()",
# Worker configuration
"--worker-class", "uvicorn.workers.UvicornWorker",
"--workers", str(workers),
"--worker-connections", "1000",
# Server socket
"--bind", f"{api_host}:{api_port}",
"--backlog", "2048",
# Timeout settings
"--timeout", "120",
"--keep-alive", "30",
"--graceful-timeout", "30",
# Request limits
"--max-requests", "1000",
"--max-requests-jitter", "50",
"--limit-request-line", "8192",
"--limit-request-fields", "200",
# Process management
"--preload",
"--enable-stdio-inheritance",
# Logging
"--access-logfile", "-",
"--error-logfile", "-",
"--log-level", "info",
# Performance
"--worker-tmp-dir", "/dev/shm" if os.path.exists("/dev/shm") else "/tmp",
]
api_process = None
def start_api_server():
nonlocal api_process
try:
print("🚀 Starting Gunicorn API server...")
api_process = subprocess.Popen(
api_cmd,
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT,
universal_newlines=True
)
# Log first few lines to see startup status
startup_logged = 0
while api_process.poll() is None and startup_logged < 10:
output = api_process.stdout.readline()
if output:
print(f"API: {output.strip()}")
startup_logged += 1
# Continue reading output without printing everything
while api_process.poll() is None:
api_process.stdout.readline()
if api_process.returncode != 0:
print(f"❌ API server exited with code {api_process.returncode}")
except Exception as e:
print(f"❌ API server error: {e}")
def start_mcp_server_async():
try:
# Wait for API server to start and be ready
import httpx
import time
api_url = f"http://{api_host}:{api_port}"
print(f"� Waiting for API server to be ready at {api_url}...")
# Wait up to 30 seconds for API server to be ready
for attempt in range(30):
try:
with httpx.Client(timeout=2) as client:
response = client.get(api_url) # 使用根路径進行健康檢查
if response.status_code == 200:
print("✅ API server is ready!")
break
except:
pass
time.sleep(1)
else:
print("⚠️ API server health check failed, but continuing with MCP startup...")
print("🚀 Starting MCP server...")
asyncio.run(self.start_mcp_server(
transport=mcp_transport,
host=mcp_host,
port=mcp_port,
api_base_url=api_url,
with_api_server=False # API server is already running
))
except Exception as e:
print(f"❌ MCP server error: {e}")
try:
# Start API server in a separate thread
api_thread = threading.Thread(target=start_api_server, daemon=True)
api_thread.start()
# Start MCP server in main thread
start_mcp_server_async()
except KeyboardInterrupt:
print("\n👋 Shutting down production+MCP server...")
if api_process:
api_process.terminate()
try:
api_process.wait(timeout=10)
except subprocess.TimeoutExpired:
api_process.kill()
except Exception as e:
print(f"❌ Failed to start production+MCP server: {e}")
if api_process:
api_process.terminate()
sys.exit(1)
def main():
"""Main entry point"""
parser = argparse.ArgumentParser(
description="Judge Micro - Code Evaluation Microservice with MCP Support",
formatter_class=argparse.RawDescriptionHelpFormatter,
epilog="""
Examples:
# Development mode (API only)
uv run python main.py dev
# Production mode (API only)
uv run python main.py prod
# Production mode with MCP server
uv run python main.py prod-mcp --transport http --port 8001
# MCP server only
uv run python main.py mcp --transport http --port 8001
# Combined API + MCP server (development)
uv run python main.py combined --mcp-port 8001
# MCP with external API
uv run python main.py mcp --api-url http://localhost:8000 --no-api-server
"""
)
subparsers = parser.add_subparsers(dest='command', help='Available commands')
# Development command
dev_parser = subparsers.add_parser('dev', help='Start development server')
dev_parser.add_argument('--host', default=None, help='Host to bind to')
dev_parser.add_argument('--port', type=int, default=None, help='Port to bind to')
dev_parser.add_argument('--no-check', action='store_true', help='Skip environment check')
# Production command
prod_parser = subparsers.add_parser('prod', help='Start production server')
prod_parser.add_argument('--host', default=None, help='Host to bind to')
prod_parser.add_argument('--port', type=int, default=None, help='Port to bind to')
prod_parser.add_argument('--workers', type=int, default=None, help='Number of workers')
prod_parser.add_argument('--no-check', action='store_true', help='Skip environment check')
# Production with MCP command
prod_mcp_parser = subparsers.add_parser('prod-mcp', help='Start production server with MCP')
prod_mcp_parser.add_argument('--api-host', default=None, help='API server host')
prod_mcp_parser.add_argument('--api-port', type=int, default=None, help='API server port')
prod_mcp_parser.add_argument('--workers', type=int, default=None, help='Number of API workers')
prod_mcp_parser.add_argument('--mcp-host', default='127.0.0.1', help='MCP server host')
prod_mcp_parser.add_argument('--port', type=int, default=8001, help='MCP server port')
prod_mcp_parser.add_argument('--transport', choices=['http', 'sse', 'stdio'],
default='http', help='MCP transport protocol')
prod_mcp_parser.add_argument('--no-check', action='store_true', help='Skip environment check')
# MCP command
mcp_parser = subparsers.add_parser('mcp', help='Start MCP server')
mcp_parser.add_argument('--transport', choices=['http', 'sse', 'stdio'],
default='http', help='Transport protocol')
mcp_parser.add_argument('--host', default='127.0.0.1', help='Host to bind to')
mcp_parser.add_argument('--port', type=int, default=8001, help='Port to bind to')
mcp_parser.add_argument('--api-url', help='External Judge Micro API URL')
mcp_parser.add_argument('--no-api-server', action='store_true',
help="Don't start local API server")
mcp_parser.add_argument('--no-check', action='store_true', help='Skip environment check')
mcp_parser.add_argument('--quiet', action='store_true', help='Reduce log output')
# Combined command
combined_parser = subparsers.add_parser('combined', help='Start both API and MCP servers')
combined_parser.add_argument('--api-host', default=None, help='API server host')
combined_parser.add_argument('--api-port', type=int, default=None, help='API server port')
combined_parser.add_argument('--mcp-host', default='127.0.0.1', help='MCP server host')
combined_parser.add_argument('--mcp-port', type=int, default=8001, help='MCP server port')
combined_parser.add_argument('--mcp-transport', choices=['http', 'sse', 'stdio'],
default='http', help='MCP transport protocol')
combined_parser.add_argument('--no-check', action='store_true', help='Skip environment check')
args = parser.parse_args()
if not args.command:
parser.print_help()
return
runner = JudgeMicroRunner()
try:
# Environment check (unless skipped)
if not getattr(args, 'no_check', False):
if not runner.check_environment():
print("💡 Use --no-check to skip environment validation")
sys.exit(1)
# Execute command
if args.command == 'dev':
runner.start_development(args.host, args.port)
elif args.command == 'prod':
runner.start_production(args.host, args.port, args.workers)
elif args.command == 'prod-mcp':
runner.start_production_with_mcp(
api_host=args.api_host,
api_port=args.api_port,
workers=args.workers,
mcp_host=args.mcp_host,
mcp_port=args.port, # 使用 --port 參數
mcp_transport=args.transport
)
elif args.command == 'mcp':
with_api_server = not args.no_api_server if hasattr(args, 'no_api_server') else True
# Set quiet mode if requested
if hasattr(args, 'quiet') and args.quiet:
import os
os.environ['FASTMCP_QUIET'] = '1'
import warnings
warnings.filterwarnings("ignore")
asyncio.run(runner.start_mcp_server(
transport=args.transport,
host=args.host,
port=args.port,
api_base_url=args.api_url,
with_api_server=with_api_server
))
elif args.command == 'combined':
runner.start_combined_server(
api_host=args.api_host,
api_port=args.api_port,
mcp_host=args.mcp_host,
mcp_port=args.mcp_port,
mcp_transport=args.mcp_transport
)
except KeyboardInterrupt:
print("\n👋 Shutting down...")
except Exception as e:
print(f"❌ Error: {e}")
sys.exit(1)
if __name__ == "__main__":
main()