-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapi_server.py
More file actions
1930 lines (1621 loc) · 75.9 KB
/
api_server.py
File metadata and controls
1930 lines (1621 loc) · 75.9 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
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
from fastapi import FastAPI, HTTPException, File, Form, UploadFile, Depends, Header, status, Request
from fastapi.security import APIKeyHeader
from fastapi.responses import HTMLResponse, FileResponse, StreamingResponse
from pydantic import ValidationError
from typing import Optional
from contextlib import asynccontextmanager
import logging
import json
import asyncio
import os
import hashlib
import shutil
import aiofiles
import time
import glob
import docker
import zipfile
import io
import httpx
import uuid
import subprocess
from logging.handlers import TimedRotatingFileHandler
from models import SubmissionRequest, LimitObject, Job
from queue_manager import job_queue
from worker import worker_manager
from llm_judge import get_llm_judge
# 設定日誌
log_dir = "logs"
os.makedirs(log_dir, exist_ok=True)
log_file = os.path.join(log_dir, "sandbox.log")
AUTH_LOG_FILE = os.path.join(log_dir, "auth_failures.jsonl")
# 設定 Checkers 目錄
CHECKERS_DIR = "checkers"
os.makedirs(CHECKERS_DIR, exist_ok=True)
handler = TimedRotatingFileHandler(
log_file,
when="midnight",
interval=1,
backupCount=30,
encoding='utf-8'
)
handler.suffix = "%Y-%m-%d"
logging.basicConfig(
level=logging.INFO,
format="%(asctime)s - %(levelname)s - %(message)s",
handlers=[
handler,
logging.StreamHandler()
]
)
logger = logging.getLogger(__name__)
@asynccontextmanager
async def lifespan(app: FastAPI):
# Startup
# 檢查必要的環境變數
api_key = os.getenv("SANDBOX_API_KEY", "")
if not api_key or api_key == "default-insecure-key":
logger.warning("=" * 60)
logger.warning("WARNING: SANDBOX_API_KEY 未設定或使用不安全的預設值!")
logger.warning("請在 .env 檔案中設定強密碼: SANDBOX_API_KEY=your-strong-key")
logger.warning("生成強密碼: openssl rand -hex 32")
logger.warning("=" * 60)
# 預先拉取常用 Sidecar 映像檔(背景執行,不阻塞啟動)
from worker import SidecarManager
asyncio.create_task(SidecarManager.preload_common_images())
await worker_manager.start()
yield
# Shutdown
await worker_manager.stop()
app = FastAPI(
title="Sandbox Isolate API",
version="2.0.0",
description="非同步 Isolate 沙盒評測服務",
lifespan=lifespan
)
# ===== Security =====
API_KEY_NAME = "X-API-KEY"
API_KEY = os.getenv("SANDBOX_API_KEY", "")
if not API_KEY:
API_KEY = "default-insecure-key" # Fallback for development only
api_key_header = APIKeyHeader(name=API_KEY_NAME, auto_error=False)
async def verify_api_key(request: Request, api_key: str = Depends(api_key_header)):
"""驗證 API Key"""
if not API_KEY or API_KEY == "default-insecure-key":
raise HTTPException(
status_code=status.HTTP_503_SERVICE_UNAVAILABLE,
detail="Server not configured: SANDBOX_API_KEY not set"
)
if api_key != API_KEY:
# Log failure
try:
entry = {
"timestamp": time.time(),
"ip": request.client.host if request.client else "unknown",
"method": request.method,
"path": request.url.path,
"provided_key": (api_key[:3] + "***") if api_key else "None"
}
async with aiofiles.open(AUTH_LOG_FILE, "a") as f:
await f.write(json.dumps(entry) + "\n")
except Exception as e:
logger.error(f"Failed to log auth failure: {e}")
raise HTTPException(
status_code=status.HTTP_403_FORBIDDEN,
detail="Could not validate credentials"
)
return api_key
async def fetch_submission_code(submission_id: str):
"""從後端取得學生程式碼與語言"""
backend_url = os.getenv("BACKEND_API_URL", "").strip()
# 如果沒有設定後端 URL,拋出異常
if not backend_url:
raise HTTPException(status_code=503, detail="BACKEND_API_URL not configured")
url = f"{backend_url}/submission/{submission_id}/code/"
try:
async with httpx.AsyncClient() as client:
resp = await client.get(url, timeout=30.0)
if resp.status_code in (403, 404):
raise HTTPException(status_code=resp.status_code, detail=resp.text or "Upstream returned error")
if resp.status_code != 200:
raise HTTPException(status_code=502, detail=f"Failed to fetch submission code (status {resp.status_code})")
code = None
language = None
content_type = resp.headers.get("content-type", "").lower()
if "application/json" in content_type:
try:
payload = resp.json()
data_obj = payload.get("data") or {}
# 嘗試各種鍵名,優先 data 區塊
code = (
data_obj.get("source_code")
or data_obj.get("sourceCode")
or payload.get("code")
or payload.get("submission_code")
)
language = (
data_obj.get("language_type")
or data_obj.get("languageType")
or data_obj.get("language")
or payload.get("language")
or payload.get("lang")
)
except Exception as e:
logger.warning(f"Submission code JSON parse failed: {e}")
if code is None:
code = resp.text
if not code:
raise HTTPException(status_code=502, detail="Submission code is empty from backend")
if not language:
raise HTTPException(status_code=502, detail="Submission language missing from backend response")
# 語言標準化:支援數字代碼與字串代碼
lang_map_numeric = {
0: "c",
1: "cpp",
2: "python",
3: "java",
4: "javascript",
}
normalized_language = None
if isinstance(language, int):
normalized_language = lang_map_numeric.get(language)
else:
normalized_language = str(language).lower()
if normalized_language is None:
raise HTTPException(status_code=400, detail=f"Unsupported language from backend: {language}")
return code, normalized_language
except HTTPException:
raise
except Exception as e:
logger.error(f"Error fetching submission code: {e}")
raise HTTPException(status_code=502, detail=f"Failed to fetch submission code: {str(e)}")
# ===== API Endpoints =====
@app.get("/api/v1/checkers", dependencies=[Depends(verify_api_key)])
async def list_checkers():
"""
列出所有已上傳的 Checker
"""
checkers = []
try:
for f in os.listdir(CHECKERS_DIR):
path = os.path.join(CHECKERS_DIR, f)
if os.path.isfile(path):
stat = os.stat(path)
# 判斷類型
checker_type = "unknown"
if f.endswith('.py'):
checker_type = "python"
elif os.access(path, os.X_OK):
checker_type = "binary"
checkers.append({
"name": f,
"size": stat.st_size,
"modified": stat.st_mtime,
"type": checker_type,
"executable": os.access(path, os.X_OK)
})
return {"success": True, "checkers": checkers, "count": len(checkers)}
except Exception as e:
raise HTTPException(status_code=500, detail=f"Failed to list checkers: {str(e)}")
@app.get("/api/v1/checkers/{name}", dependencies=[Depends(verify_api_key)])
async def get_checker_info(name: str):
"""
查詢單個 Checker 詳情
"""
path = os.path.join(CHECKERS_DIR, name)
if not os.path.exists(path):
raise HTTPException(status_code=404, detail=f"Checker '{name}' not found")
stat = os.stat(path)
checker_type = "unknown"
if name.endswith('.py'):
checker_type = "python"
elif os.access(path, os.X_OK):
checker_type = "binary"
return {
"success": True,
"name": name,
"path": os.path.abspath(path),
"size": stat.st_size,
"modified": stat.st_mtime,
"type": checker_type,
"executable": os.access(path, os.X_OK)
}
@app.get("/api/v1/checkers/{name}/download", dependencies=[Depends(verify_api_key)])
async def download_checker(name: str):
"""
下載指定的 Checker 檔案
"""
path = os.path.join(CHECKERS_DIR, name)
if not os.path.exists(path):
raise HTTPException(status_code=404, detail=f"Checker '{name}' not found")
# 判斷 media_type
if name.endswith('.py'):
media_type = "text/x-python"
else:
media_type = "application/octet-stream"
return FileResponse(
path=path,
filename=name,
media_type=media_type
)
@app.delete("/api/v1/checkers/{name}", dependencies=[Depends(verify_api_key)])
async def delete_checker(name: str):
"""
刪除指定的 Checker
"""
path = os.path.join(CHECKERS_DIR, name)
if not os.path.exists(path):
raise HTTPException(status_code=404, detail=f"Checker '{name}' not found")
try:
os.remove(path)
logger.info(f"Checker '{name}' deleted")
return {"success": True, "message": f"Checker '{name}' deleted successfully"}
except Exception as e:
raise HTTPException(status_code=500, detail=f"Failed to delete checker: {str(e)}")
@app.post("/api/v1/checkers", dependencies=[Depends(verify_api_key)])
async def upload_checker(
name: str = Form(..., description="Checker 名稱 (e.g., my_checker)"),
file: UploadFile = File(..., description="Checker 執行檔 (Binary or Script)")
):
"""
上傳 Custom Checker
"""
file_path = os.path.join(CHECKERS_DIR, name)
try:
async with aiofiles.open(file_path, 'wb') as out_file:
content = await file.read()
await out_file.write(content)
# Make executable
os.chmod(file_path, 0o755)
return {"success": True, "message": f"Checker '{name}' uploaded successfully", "path": file_path}
except Exception as e:
raise HTTPException(status_code=500, detail=f"Failed to upload checker: {str(e)}")
@app.post("/api/v1/checkers/compile", dependencies=[Depends(verify_api_key)])
async def upload_and_compile_checker(
name: str = Form(..., description="編譯後的 Checker 名稱"),
source: UploadFile = File(..., description="Checker 源碼 (.cpp/.c)")
):
"""
上傳 Checker 源碼並編譯
支援 C/C++ 源碼上傳,自動編譯為可執行檔
"""
content = await source.read()
ext = os.path.splitext(source.filename)[1].lower()
if ext not in ['.c', '.cpp']:
raise HTTPException(status_code=400, detail="Only .c and .cpp source files are supported")
# 暫存源碼
src_path = f"/tmp/checker_{name}_{uuid.uuid4().hex[:8]}{ext}"
out_path = os.path.join(CHECKERS_DIR, name)
try:
async with aiofiles.open(src_path, 'wb') as f:
await f.write(content)
# 編譯
compiler = "g++" if ext == ".cpp" else "gcc"
cmd = [compiler, "-O2", "-o", out_path, src_path]
result = subprocess.run(cmd, capture_output=True, text=True, timeout=30)
if result.returncode != 0:
raise HTTPException(status_code=400, detail=f"Compilation failed: {result.stderr}")
os.chmod(out_path, 0o755)
logger.info(f"Checker '{name}' compiled from {source.filename}")
return {
"success": True,
"message": f"Checker '{name}' compiled successfully",
"source_file": source.filename,
"output_path": out_path
}
except subprocess.TimeoutExpired:
raise HTTPException(status_code=408, detail="Compilation timed out")
except HTTPException:
raise
except Exception as e:
raise HTTPException(status_code=500, detail=f"Compilation error: {str(e)}")
finally:
# 清理暫存檔
if os.path.exists(src_path):
os.unlink(src_path)
@app.post("/api/v1/evaluate-package", status_code=status.HTTP_202_ACCEPTED, dependencies=[Depends(verify_api_key)])
async def evaluate_package(
submission_id: str = Form(..., description="唯一的提交 ID"),
package: UploadFile = File(..., description="完整題包 ZIP (包含 submission, testcase, checker)"),
package_hash: str = Form(..., description="題包 SHA256 Hash"),
time_limit: float = Form(2.0, description="CPU 時間限制 (秒)"),
memory_limit: int = Form(256000, description="記憶體限制 (KB)"),
callback_url: Optional[str] = Form(None, description="Webhook URL"),
callback_token: Optional[str] = Form(None, description="Webhook Token"),
priority: int = Form(10, description="優先級"),
):
"""
評測完整題包
題包結構:
- meta.json: 題目元數據
- testcase/*.in, testcase/*.out: 測試用例
- checker/checker.{c,cpp}: Checker 源代碼
- (submission code 透過後端 API 取得)
"""
logger.info(f"Received package evaluation {submission_id}")
# 1. 建立暫存目錄
work_dir = f"/tmp/sandbox/packages/{submission_id}"
os.makedirs(work_dir, exist_ok=True)
try:
# 2. 儲存並驗證題包
package_path = os.path.join(work_dir, "package.zip")
async with aiofiles.open(package_path, 'wb') as out_file:
content = await package.read()
await out_file.write(content)
# 驗證 Hash
sha256_hash = hashlib.sha256(content).hexdigest()
if sha256_hash != package_hash:
shutil.rmtree(work_dir, ignore_errors=True)
raise HTTPException(status_code=400, detail=f"Package hash mismatch. Expected {package_hash}, got {sha256_hash}")
# 3. 解壓題包
extract_dir = os.path.join(work_dir, "extracted")
os.makedirs(extract_dir, exist_ok=True)
with zipfile.ZipFile(package_path) as z:
z.extractall(extract_dir)
# 4. 讀取 meta.json
meta_path = os.path.join(extract_dir, "meta.json")
if not os.path.exists(meta_path):
raise HTTPException(status_code=400, detail="Missing meta.json in package")
async with aiofiles.open(meta_path, 'r') as f:
meta = json.loads(await f.read())
# 5. 從後端取得 submission code
code_text, language_raw = await fetch_submission_code(submission_id)
lang_map = {
"python": "python",
"python3": "python",
"py": "python",
"c": "c",
"cpp": "cpp",
"c++": "cpp",
"java": None, # 不支援
"javascript": None, # 不支援
}
language_key = str(language_raw).lower()
language = lang_map.get(language_key)
if not language:
raise HTTPException(status_code=400, detail=f"Unsupported language from backend: {language_raw}")
ext_map = {"python": ".py", "c": ".c", "cpp": ".cpp"}
submission_path = os.path.join(extract_dir, f"submission{ext_map[language]}")
async with aiofiles.open(submission_path, "w", encoding="utf-8") as f:
await f.write(code_text)
# 6. 處理 Checker(支援多種格式)
checker_path = None
checker_dir = os.path.join(extract_dir, "checker")
if os.path.exists(checker_dir):
# 優先順序:已編譯 binary > C++ > C > Python
checker_candidates = [
("checker", None), # 已編譯的 binary
("checker.cpp", "cpp"), # C++ 源碼
("checker.c", "c"), # C 源碼
("checker.py", "python"), # Python 腳本
]
for checker_file, checker_type in checker_candidates:
potential_checker = os.path.join(checker_dir, checker_file)
if os.path.exists(potential_checker):
if checker_type == "cpp":
# 編譯 C++ checker(包含 testlib.h 支援)
compiled_checker = os.path.join(work_dir, "checker_compiled")
# 檢查是否有 testlib.h
testlib_path = os.path.join(checker_dir, "testlib.h")
include_flag = ["-I", checker_dir] if os.path.exists(testlib_path) else []
cmd = ["g++", "-O2", "-o", compiled_checker] + include_flag + [potential_checker, "-lm"]
logger.info(f"Compiling C++ checker: {' '.join(cmd)}")
result = subprocess.run(cmd, capture_output=True, text=True, timeout=30)
if result.returncode != 0:
logger.error(f"Checker compilation failed: {result.stderr}")
raise HTTPException(status_code=400, detail=f"Checker compilation error: {result.stderr}")
checker_path = compiled_checker
os.chmod(checker_path, 0o755)
elif checker_type == "c":
# 編譯 C checker
compiled_checker = os.path.join(work_dir, "checker_compiled")
cmd = ["gcc", "-O2", "-o", compiled_checker, potential_checker, "-lm"]
logger.info(f"Compiling C checker: {' '.join(cmd)}")
result = subprocess.run(cmd, capture_output=True, text=True, timeout=30)
if result.returncode != 0:
logger.error(f"Checker compilation failed: {result.stderr}")
raise HTTPException(status_code=400, detail=f"Checker compilation error: {result.stderr}")
checker_path = compiled_checker
os.chmod(checker_path, 0o755)
elif checker_type == "python":
# Python checker 不需要編譯,直接使用
# 複製到 work_dir 確保路徑一致
python_checker_path = os.path.join(work_dir, "checker.py")
shutil.copy(potential_checker, python_checker_path)
checker_path = python_checker_path
os.chmod(checker_path, 0o755)
logger.info(f"Using Python checker: {checker_path}")
else:
# 已編譯的 binary
checker_path = potential_checker
os.chmod(checker_path, 0o755)
logger.info(f"Using pre-compiled checker: {checker_path}")
break
# 也檢查 meta.json 中是否指定了 checker
if not checker_path and meta.get("checker"):
checker_name = meta.get("checker")
# 從預設 checkers 目錄尋找
default_checker = os.path.join(CHECKERS_DIR, checker_name)
if os.path.exists(default_checker):
checker_path = os.path.abspath(default_checker)
logger.info(f"Using default checker from meta.json: {checker_name}")
# 7. 讀取測試用例
testcase_dir = os.path.join(extract_dir, "testcase")
if not os.path.exists(testcase_dir):
raise HTTPException(status_code=400, detail="Missing testcase directory")
# 8. 建構 Request Data
limits = LimitObject(
time_limit_sec=time_limit,
memory_limit_kb=memory_limit,
wall_time_limit_sec=time_limit * 2.5
)
request_data = SubmissionRequest(
submission_id=submission_id,
code="<PACKAGE>",
language=language,
priority=priority,
limits=limits,
callback_url=callback_url,
callback_token=callback_token
)
# 9. 建立 Job (使用特殊的 problem_id 表示這是 package 模式)
job = Job(
submission_id=submission_id,
language=language,
priority=priority,
timestamp=time.time(),
request_data=request_data,
problem_id=f"package_{submission_id}", # 特殊標記
mode="package", # 新模式:package
file_path=submission_path,
file_hash=package_hash,
problem_hash=package_hash,
use_checker=bool(checker_path),
checker_file_path=checker_path,
stdin=None, # Package 模式下使用測試用例文件
allow_network=meta.get("allow_network", False),
network_whitelist=meta.get("network_whitelist", []),
sidecar_image=meta.get("sidecar_image", None)
)
# 10. 推入隊列
await job_queue.push(job)
logger.info(f"Package evaluation job {submission_id} added to queue")
return {
"success": True,
"submission_id": submission_id,
"status": "queued",
"language": language,
"has_checker": bool(checker_path),
"queue_position": job_queue.size()
}
except HTTPException:
shutil.rmtree(work_dir, ignore_errors=True)
raise
except Exception as e:
shutil.rmtree(work_dir, ignore_errors=True)
logger.error(f"Error processing package: {e}")
raise HTTPException(status_code=500, detail=f"Failed to process package: {str(e)}")
async def compile_problem_checker(problem_dir: str):
"""
編譯題包內的 checker(如果存在)
支援 C/C++ 源碼編譯和 Python checker
"""
checker_dir = os.path.join(problem_dir, "checker")
if not os.path.exists(checker_dir):
return None
compiled_checker_path = os.path.join(problem_dir, "checker_compiled")
# 優先順序:已編譯 binary > C++ > C > Python
checker_candidates = [
("checker", None), # 已編譯的 binary
("checker.cpp", "cpp"), # C++ 源碼
("checker.c", "c"), # C 源碼
("checker.py", "python"), # Python 腳本
]
for checker_file, checker_type in checker_candidates:
potential_checker = os.path.join(checker_dir, checker_file)
if os.path.exists(potential_checker):
try:
if checker_type == "cpp":
# 編譯 C++ checker(包含 testlib.h 支援)
testlib_path = os.path.join(checker_dir, "testlib.h")
include_flag = ["-I", checker_dir] if os.path.exists(testlib_path) else []
cmd = ["g++", "-O2", "-o", compiled_checker_path] + include_flag + [potential_checker, "-lm"]
logger.info(f"Compiling C++ checker for problem: {' '.join(cmd)}")
result = subprocess.run(cmd, capture_output=True, text=True, timeout=30)
if result.returncode != 0:
logger.error(f"Checker compilation failed: {result.stderr}")
return None
os.chmod(compiled_checker_path, 0o755)
return compiled_checker_path
elif checker_type == "c":
# 編譯 C checker
cmd = ["gcc", "-O2", "-o", compiled_checker_path, potential_checker, "-lm"]
logger.info(f"Compiling C checker for problem: {' '.join(cmd)}")
result = subprocess.run(cmd, capture_output=True, text=True, timeout=30)
if result.returncode != 0:
logger.error(f"Checker compilation failed: {result.stderr}")
return None
os.chmod(compiled_checker_path, 0o755)
return compiled_checker_path
elif checker_type == "python":
# Python checker 不需要編譯
# 複製到題目目錄的根目錄
python_checker_path = os.path.join(problem_dir, "checker.py")
shutil.copy(potential_checker, python_checker_path)
os.chmod(python_checker_path, 0o755)
logger.info(f"Using Python checker: {python_checker_path}")
return python_checker_path
else:
# 已編譯的 binary,複製到題目根目錄
shutil.copy(potential_checker, compiled_checker_path)
os.chmod(compiled_checker_path, 0o755)
logger.info(f"Using pre-compiled checker: {compiled_checker_path}")
return compiled_checker_path
except Exception as e:
logger.error(f"Error processing checker: {e}")
return None
return None
async def fetch_problem_checksum(problem_id: str) -> str:
"""
從後端取得題目測資的 MD5 checksum
使用 Sandbox Token 驗證
"""
backend_url = os.getenv("BACKEND_API_URL", "").strip()
# 如果沒有設定後端 URL,拋出異常讓 caller 處理 (使用本地題包)
if not backend_url:
raise HTTPException(status_code=503, detail="BACKEND_API_URL not configured, using local packages only")
sandbox_token = os.getenv("SANDBOX_TOKEN", "")
url = f"{backend_url}/problem/{problem_id}/checksum?token={sandbox_token}"
try:
async with httpx.AsyncClient() as client:
resp = await client.get(url, timeout=30.0)
if resp.status_code == 401:
raise HTTPException(status_code=401, detail="Invalid sandbox token")
if resp.status_code == 404:
raise HTTPException(status_code=404, detail=f"Problem {problem_id} or testdata not found")
if resp.status_code != 200:
raise HTTPException(status_code=502, detail=f"Failed to fetch checksum: {resp.status_code}")
data = resp.json()
return data.get("data", {}).get("checksum", "")
except HTTPException:
raise
except Exception as e:
logger.error(f"Error fetching checksum for problem {problem_id}: {e}")
raise HTTPException(status_code=502, detail=f"Failed to fetch checksum: {str(e)}")
async def fetch_problem_meta(problem_id: str) -> dict:
"""
從後端取得題目測資的元資料(tasks 結構)
使用 Sandbox Token 驗證
"""
backend_url = os.getenv("BACKEND_API_URL", "").strip()
# 如果沒有設定後端 URL,拋出異常
if not backend_url:
raise HTTPException(status_code=503, detail="BACKEND_API_URL not configured")
sandbox_token = os.getenv("SANDBOX_TOKEN", "")
url = f"{backend_url}/problem/{problem_id}/meta?token={sandbox_token}"
try:
async with httpx.AsyncClient() as client:
resp = await client.get(url, timeout=30.0)
if resp.status_code == 401:
raise HTTPException(status_code=401, detail="Invalid sandbox token")
if resp.status_code == 404:
raise HTTPException(status_code=404, detail=f"Problem {problem_id} or testdata not found")
if resp.status_code != 200:
raise HTTPException(status_code=502, detail=f"Failed to fetch meta: {resp.status_code}")
data = resp.json()
return data.get("data", {})
except HTTPException:
raise
except Exception as e:
logger.error(f"Error fetching meta for problem {problem_id}: {e}")
raise HTTPException(status_code=502, detail=f"Failed to fetch meta: {str(e)}")
async def download_problem_testdata(problem_id: str) -> bytes:
"""
從後端下載題目測資包 (ZIP)
使用 Sandbox Token 驗證
"""
backend_url = os.getenv("BACKEND_API_URL", "").strip()
# 如果沒有設定後端 URL,拋出異常
if not backend_url:
raise HTTPException(status_code=503, detail="BACKEND_API_URL not configured")
sandbox_token = os.getenv("SANDBOX_TOKEN", "")
url = f"{backend_url}/problem/{problem_id}/testdata?token={sandbox_token}"
try:
async with httpx.AsyncClient() as client:
resp = await client.get(url, timeout=120.0) # 較長的超時時間以應對大檔案
if resp.status_code == 401:
raise HTTPException(status_code=401, detail="Invalid sandbox token")
if resp.status_code == 404:
raise HTTPException(status_code=404, detail=f"Problem {problem_id} or testdata not found")
if resp.status_code != 200:
raise HTTPException(status_code=502, detail=f"Failed to download testdata: {resp.status_code}")
return resp.content
except HTTPException:
raise
except Exception as e:
logger.error(f"Error downloading testdata for problem {problem_id}: {e}")
raise HTTPException(status_code=502, detail=f"Failed to download testdata: {str(e)}")
async def ensure_problem_package(problem_id: str, problem_hash: str):
"""
確保題目測資包存在且為最新版本。
工作流程:
1. 先檢查本地是否已有題包且 checksum 匹配(優先使用本地)
2. 如果本地不存在或 checksum 不匹配,嘗試從後端下載
3. 驗證下載的檔案完整性(MD5)
4. 解壓並編譯 checker(如果存在)
5. 生成 meta.json 供 worker 使用
"""
problem_dir = os.path.join("test_data", "problems", problem_id)
hash_file = os.path.join(problem_dir, ".checksum") # 改用 checksum 檔名
meta_file = os.path.join(problem_dir, "meta.json")
# 1. 先檢查本地題包是否存在且 checksum 匹配
if os.path.exists(problem_dir) and os.path.exists(hash_file) and os.path.exists(meta_file):
try:
async with aiofiles.open(hash_file, "r") as f:
local_checksum = (await f.read()).strip()
# 如果傳入的 problem_hash 與本地 checksum 匹配,直接使用本地題包
if local_checksum == problem_hash:
logger.info(f"Problem {problem_id} using local package (checksum: {problem_hash})")
return # 使用本地題包
except Exception as e:
logger.warning(f"Error reading local checksum for {problem_id}: {e}")
# 2. 嘗試從後端獲取最新版本
try:
# 從後端取得最新 checksum
remote_checksum = await fetch_problem_checksum(problem_id)
# 檢查本地是否已有相同 checksum 的測資包
if os.path.exists(problem_dir) and os.path.exists(hash_file):
try:
async with aiofiles.open(hash_file, "r") as f:
local_checksum = (await f.read()).strip()
if local_checksum == remote_checksum:
logger.info(f"Problem {problem_id} testdata is up-to-date (checksum match)")
return # 已是最新版本
except Exception:
pass # 讀取失敗,重新下載
# 3. 下載測資包
logger.info(f"Downloading testdata for problem {problem_id}...")
zip_content = await download_problem_testdata(problem_id)
logger.info(f"Problem {problem_id} testdata downloaded (checksum: {remote_checksum})")
# 5. 解壓測資包 - 直接放到題目根目錄(無 testcase 子目錄)
if os.path.exists(problem_dir):
shutil.rmtree(problem_dir)
os.makedirs(problem_dir, exist_ok=True)
meta_from_zip = None
with zipfile.ZipFile(io.BytesIO(zip_content)) as z:
for member in z.namelist():
filename = os.path.basename(member)
if not filename:
continue
# 處理 meta.json - 放到題目根目錄並讀取內容
if filename == 'meta.json':
target_path = os.path.join(problem_dir, filename)
with z.open(member) as source:
content = source.read()
with open(target_path, 'wb') as target:
target.write(content)
# 解析 meta.json 內容
try:
meta_from_zip = json.loads(content.decode('utf-8'))
except Exception as e:
logger.warning(f"Failed to parse meta.json from ZIP: {e}")
# 處理 .in 和 .out 檔案 - 直接放到題目根目錄
elif filename.endswith('.in') or filename.endswith('.out'):
target_path = os.path.join(problem_dir, filename)
with z.open(member) as source, open(target_path, 'wb') as target:
target.write(source.read())
# 處理 checker 檔案
elif 'checker' in filename.lower() or filename.endswith('.cpp') or filename.endswith('.py'):
if 'checker' in member.lower():
target_path = os.path.join(problem_dir, filename)
with z.open(member) as source, open(target_path, 'wb') as target:
target.write(source.read())
# 6. 如果 ZIP 內有 meta.json,補充 checksum 並保存
if meta_from_zip:
meta_from_zip["checksum"] = remote_checksum
async with aiofiles.open(meta_file, "w") as f:
await f.write(json.dumps(meta_from_zip, indent=2))
logger.info(f"Problem {problem_id} using meta.json from ZIP package")
else:
# 如果 ZIP 內沒有 meta.json,嘗試從後端 API 取得
logger.warning(f"Problem {problem_id} ZIP has no meta.json, fetching from API...")
try:
meta_data = await fetch_problem_meta(problem_id)
meta_json = {
"checksum": remote_checksum,
"tasks": meta_data.get("tasks", []),
"allow_network": False,
"network_whitelist": [],
"sidecar_image": None
}
async with aiofiles.open(meta_file, "w") as f:
await f.write(json.dumps(meta_json, indent=2))
except Exception as e:
logger.error(f"Failed to fetch meta for {problem_id}: {e}")
# 建立最小 meta.json
meta_json = {"checksum": remote_checksum, "tasks": []}
async with aiofiles.open(meta_file, "w") as f:
await f.write(json.dumps(meta_json, indent=2))
# 7. 寫入 checksum 檔案
async with aiofiles.open(hash_file, "w") as f:
await f.write(remote_checksum)
# 8. 編譯題包內的 checker(如果存在)
checker_path = await compile_problem_checker(problem_dir)
if checker_path:
logger.info(f"Problem {problem_id} checker compiled: {checker_path}")
logger.info(f"Problem {problem_id} testdata package ready.")
except HTTPException as he:
# 如果本地有題包(無論版本),優先使用
if os.path.exists(problem_dir) and os.path.exists(meta_file):
logger.warning(f"Failed to fetch remote problem {problem_id} ({he.detail}), using local version.")
return
raise
except Exception as e:
logger.error(f"Error ensuring problem package {problem_id}: {e}")
# 如果本地有題包(無論版本),優先使用
if os.path.exists(problem_dir) and os.path.exists(meta_file):
logger.warning(f"Error updating problem {problem_id} ({e}), using local version.")
return
raise HTTPException(status_code=503, detail=f"Problem package missing and fetch failed: {str(e)}")
# ===== Problem Package Manual Upload API =====
@app.get("/api/v1/problems", dependencies=[Depends(verify_api_key)])
async def list_problems():
"""
列出所有已快取的題目
"""
problems_dir = os.path.join("test_data", "problems")
if not os.path.exists(problems_dir):
return {"success": True, "problems": [], "count": 0}
problems = []
for d in os.listdir(problems_dir):
problem_path = os.path.join(problems_dir, d)
if os.path.isdir(problem_path):
meta_file = os.path.join(problem_path, "meta.json")
hash_file = os.path.join(problem_path, ".checksum")
# 讀取 meta.json
meta = {}
if os.path.exists(meta_file):
try:
async with aiofiles.open(meta_file, "r") as f:
meta = json.loads(await f.read())
except:
pass
# 讀取 checksum
checksum = None
if os.path.exists(hash_file):
try:
async with aiofiles.open(hash_file, "r") as f:
checksum = (await f.read()).strip()
except:
pass
# 統計測資數量 - 直接在題目根目錄
testcase_count = len([f for f in os.listdir(problem_path) if f.endswith('.in')])
# 檢查 checker
has_checker = os.path.exists(os.path.join(problem_path, "checker_compiled")) or \
os.path.exists(os.path.join(problem_path, "checker.py"))
problems.append({
"problem_id": d,
"checksum": checksum,
"testcase_count": testcase_count,
"has_checker": has_checker,
"task_count": meta.get("task_count", 0)
})
return {"success": True, "problems": problems, "count": len(problems)}
@app.get("/api/v1/problems/{problem_id}", dependencies=[Depends(verify_api_key)])
async def get_problem_info(problem_id: str):
"""
查詢單個題目詳情
"""
problem_dir = os.path.join("test_data", "problems", problem_id)
if not os.path.exists(problem_dir):
raise HTTPException(status_code=404, detail=f"Problem '{problem_id}' not found")
meta_file = os.path.join(problem_dir, "meta.json")
hash_file = os.path.join(problem_dir, ".checksum")
# 讀取 meta.json
meta = {}
if os.path.exists(meta_file):
async with aiofiles.open(meta_file, "r") as f:
meta = json.loads(await f.read())
# 讀取 checksum
checksum = None
if os.path.exists(hash_file):
async with aiofiles.open(hash_file, "r") as f:
checksum = (await f.read()).strip()
# 列出測資檔案 - 直接在題目根目錄
testcases = []
for f in sorted(os.listdir(problem_dir)):
if f.endswith('.in'):
stem = f[:-3]
testcases.append({
"input": f,
"output": f"{stem}.out",
"input_exists": True,
"output_exists": os.path.exists(os.path.join(problem_dir, f"{stem}.out"))
})