-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathworker.py
More file actions
1837 lines (1601 loc) · 101 KB
/
Copy pathworker.py
File metadata and controls
1837 lines (1601 loc) · 101 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
import asyncio
import logging
import os
import shutil
import httpx
import aiofiles
import json
import zipfile
import io
import subprocess
import socket
import docker
from typing import List, Dict, Any, Optional
from models import Job
from queue_manager import job_queue
from isolate_runner import IsolateRunner
from llm_judge import llm_judge_case, get_llm_judge
logger = logging.getLogger(__name__)
class ProxyManager:
"""管理 TinyProxy 實例"""
def __init__(self, worker_id: int):
self.worker_id = worker_id
self.port = 8888 + worker_id
self.config_path = f"/tmp/tinyproxy_{worker_id}.conf"
self.pid_path = f"/tmp/tinyproxy_{worker_id}.pid"
self.log_path = f"/tmp/tinyproxy_{worker_id}.log"
self.process = None
async def start(self, whitelist: List[str]):
"""啟動 Proxy 並設定白名單"""
# 1. 產生 Config
config_content = f"""
Port {self.port}
Listen 127.0.0.1
Timeout 600
PidFile "{self.pid_path}"
LogFile "{self.log_path}"
LogLevel Info
MaxClients 100
MinSpareServers 1
MaxSpareServers 5
StartServers 1
Allow 127.0.0.1
"""
# 加入白名單過濾
if whitelist:
filter_path = f"/tmp/tinyproxy_{self.worker_id}.filter"
async with aiofiles.open(filter_path, "w") as f:
for domain in whitelist:
await f.write(f"{domain}\n")
config_content += f"""
Filter "{filter_path}"
FilterURLs On
FilterExtended On
FilterDefaultDeny Yes
"""
async with aiofiles.open(self.config_path, "w") as f:
await f.write(config_content)
# 2. 啟動 TinyProxy
try:
self.process = await asyncio.create_subprocess_exec(
"tinyproxy", "-d", "-c", self.config_path,
stdout=asyncio.subprocess.DEVNULL,
stderr=asyncio.subprocess.DEVNULL
)
# 等待啟動
await asyncio.sleep(0.5)
logger.info(f"Worker-{self.worker_id}: Proxy started on port {self.port}")
except Exception as e:
logger.error(f"Worker-{self.worker_id}: Failed to start proxy: {e}")
async def get_logs(self) -> str:
"""讀取 Proxy Log"""
if os.path.exists(self.log_path):
try:
async with aiofiles.open(self.log_path, "r", errors="ignore") as f:
return await f.read()
except Exception:
return ""
return ""
async def stop(self):
"""停止 Proxy"""
if self.process:
try:
self.process.terminate()
await self.process.wait()
except Exception:
pass
self.process = None
# Cleanup files
for p in [self.config_path, self.pid_path, f"/tmp/tinyproxy_{self.worker_id}.filter", self.log_path]:
if os.path.exists(p):
try:
os.remove(p)
except: pass
class SidecarManager:
"""管理 Sidecar 容器"""
# 白名單:只允許這些 Image
ALLOWED_IMAGES = {
# 快取 / Key-Value
"redis:alpine",
"redis:7-alpine",
"memcached:alpine",
# 關聯式資料庫
"mysql:8.0",
"mysql:5.7",
"mariadb:10",
"postgres:14-alpine",
"postgres:15-alpine",
# NoSQL 資料庫
"mongo:6.0",
"mongo:7.0",
# 訊息佇列
"rabbitmq:3-alpine",
"nats:alpine",
# 物件儲存
"minio/minio",
# 時序/分析資料庫
"influxdb:2",
"clickhouse/clickhouse-server",
}
# 常用映像檔(建議預先拉取)
PRELOAD_IMAGES = {
"redis:alpine",
"mysql:8.0",
"postgres:14-alpine",
"mongo:6.0",
}
def __init__(self, worker_id: int):
self.worker_id = worker_id
self.client = None
self.container = None
self.container_name = f"sandbox_sidecar_{worker_id}"
try:
self.client = docker.from_env()
except Exception:
logger.warning("Docker client not available, Sidecar features will fail.")
@classmethod
async def preload_common_images(cls):
"""預先拉取常用映像檔(系統啟動時呼叫)"""
try:
client = docker.from_env()
loop = asyncio.get_running_loop()
for image in cls.PRELOAD_IMAGES:
try:
client.images.get(image)
logger.info(f"[Preload] Image {image} already exists")
except docker.errors.ImageNotFound:
logger.info(f"[Preload] Pulling {image}...")
await loop.run_in_executor(None, lambda img=image: client.images.pull(img))
logger.info(f"[Preload] {image} pulled successfully")
except Exception as e:
logger.warning(f"[Preload] Failed to preload images: {e}")
async def start(self, image: str):
"""啟動 Sidecar 容器"""
if not self.client:
raise RuntimeError("Docker client not initialized")
# 1. 白名單檢查
if image not in self.ALLOWED_IMAGES:
raise ValueError(f"Image '{image}' is not allowed. Allowed: {self.ALLOWED_IMAGES}")
try:
# Get current container ID (hostname in Docker)
hostname = socket.gethostname()
loop = asyncio.get_running_loop()
# 檢查映像檔是否已存在,只有不存在時才拉取
try:
self.client.images.get(image)
logger.info(f"Sidecar image {image} already exists locally")
except docker.errors.ImageNotFound:
logger.info(f"Pulling sidecar image: {image} (first time, may take a while)")
await loop.run_in_executor(None, lambda: self.client.images.pull(image))
logger.info(f"Sidecar image {image} pulled successfully")
# Remove existing if any
try:
old = self.client.containers.get(self.container_name)
old.remove(force=True)
except docker.errors.NotFound:
pass
# Run container attached to current network namespace
logger.info(f"Starting sidecar {image} attached to {hostname}")
# 設定環境變數 (從環境變數讀取資料庫密碼)
sidecar_db_password = os.getenv("SIDECAR_DB_PASSWORD", "sandbox_db_pass")
env_vars = {}
if "mysql" in image or "mariadb" in image:
env_vars["MYSQL_ROOT_PASSWORD"] = sidecar_db_password
env_vars["MYSQL_ALLOW_EMPTY_PASSWORD"] = "yes"
elif "postgres" in image:
env_vars["POSTGRES_PASSWORD"] = sidecar_db_password
env_vars["POSTGRES_HOST_AUTH_METHOD"] = "trust"
elif "mongo" in image:
pass # MongoDB 預設不需密碼
elif "minio" in image:
env_vars["MINIO_ROOT_USER"] = "minioadmin"
env_vars["MINIO_ROOT_PASSWORD"] = sidecar_db_password
elif "rabbitmq" in image:
env_vars["RABBITMQ_DEFAULT_USER"] = "guest"
env_vars["RABBITMQ_DEFAULT_PASS"] = "guest"
elif "clickhouse" in image:
env_vars["CLICKHOUSE_USER"] = "default"
env_vars["CLICKHOUSE_PASSWORD"] = ""
self.container = await loop.run_in_executor(None, lambda: self.client.containers.run(
image,
detach=True,
name=self.container_name,
network_mode=f"container:{hostname}", # Share network stack
auto_remove=True,
environment=env_vars,
# 資源限制
mem_limit="512m",
nano_cpus=500000000 # 0.5 CPU
))
# 根據服務類型調整等待時間
startup_time = self._get_startup_time(image)
logger.info(f"Waiting {startup_time}s for {image} to start...")
await asyncio.sleep(startup_time)
# Check if container is still running
self.container.reload()
if self.container.status != 'running':
logs = self.container.logs().decode('utf-8', errors='ignore')
raise RuntimeError(f"Sidecar container exited prematurely. Logs:\n{logs}")
except Exception as e:
logger.error(f"Failed to start sidecar: {e}")
raise
def _get_startup_time(self, image: str) -> int:
"""根據服務類型返回適當的啟動等待時間(秒)"""
# 輕量服務:快速啟動
if any(x in image for x in ["redis", "memcached", "nats"]):
return 2
# 中型服務
if any(x in image for x in ["mongo", "postgres", "mariadb", "rabbitmq", "influxdb"]):
return 5
# 重型服務:需要較長初始化
if any(x in image for x in ["mysql", "clickhouse", "minio"]):
return 8
# 預設
return 5
async def stop(self):
"""停止 Sidecar"""
if self.container:
try:
loop = asyncio.get_running_loop()
await loop.run_in_executor(None, self.container.stop)
except Exception as e:
logger.error(f"Error stopping sidecar: {e}")
self.container = None
class Worker:
def __init__(self, worker_id: int, queue, manager):
self.worker_id = worker_id
self.queue = queue
self.manager = manager
self.box_id = worker_id # Bind Worker ID to Box ID (0 to N-1)
self.running = False
self.current_job: Job = None
self.runner = IsolateRunner()
self.is_busy = False # 狀態追蹤
self.proxy = ProxyManager(worker_id)
self.sidecar = SidecarManager(worker_id)
async def run(self):
"""Worker 主迴圈"""
self.running = True
logger.info(f"Worker-{self.worker_id} started (Box ID: {self.box_id})")
# 初始化 Box
try:
box_path = await self.runner._init_box(self.box_id, use_cg=False)
logger.info(f"Worker-{self.worker_id} box initialized at {box_path}")
except Exception as e:
logger.error(f"Worker-{self.worker_id} failed to init box: {e}")
return
while self.running:
try:
# 1. 從隊列獲取任務
try:
job = await asyncio.wait_for(self.queue.pop(), timeout=1.0)
except asyncio.TimeoutError:
continue
self.is_busy = True
self.current_job = job
logger.info(f"Worker-{self.worker_id} processing job {job.submission_id}")
result_data = {"status": "XX", "message": "Unknown Error"}
# Network Setup
share_net = False
env_vars = {}
# Sidecar Setup
if job.sidecar_image:
try:
await self.sidecar.start(job.sidecar_image)
share_net = True # Must share net to access sidecar on localhost
logger.info(f"Job {job.submission_id}: Sidecar {job.sidecar_image} started")
except Exception as e:
logger.error(f"Job {job.submission_id}: Sidecar failed: {e}")
result_data = {"status": "XX", "message": f"Sidecar failed: {e}"}
# Skip execution if sidecar fails? Yes.
# But we are inside the loop, so we need to handle flow.
# Let's set a flag or raise exception to jump to finally
raise RuntimeError(f"Sidecar failed: {e}")
if job.allow_network:
share_net = True
if job.network_whitelist:
await self.proxy.start(job.network_whitelist)
proxy_url = f"http://127.0.0.1:{self.proxy.port}"
env_vars = {
"http_proxy": proxy_url,
"https_proxy": proxy_url,
"HTTP_PROXY": proxy_url,
"HTTPS_PROXY": proxy_url
}
logger.info(f"Job {job.submission_id}: Network enabled with whitelist proxy")
else:
logger.warning(f"Job {job.submission_id}: Full network access enabled (No whitelist)")
try:
# 2. 準備檔案 & 編譯
compile_success = True
executable_cmd = []
run_files_base = []
compile_info = {"status": "OK", "message": "No compilation needed for this language"}
source_code = ""
lang = job.language.lower()
# 判斷是否有題包
has_problem_package_for_compile = job.problem_id is not None
if has_problem_package_for_compile:
problem_dir = os.path.join("test_data", "problems", job.problem_id)
else:
problem_dir = None
# [Step 2.1] Load Teacher Provided Files (Scenario 3)
provided_files_data = [] # List of (filename, content_bytes)
has_provided_makefile = False
has_provided_main = False
if problem_dir:
meta_path = os.path.join(problem_dir, "meta.json")
else:
meta_path = None
if meta_path and os.path.exists(meta_path):
try:
async with aiofiles.open(meta_path, "r") as f:
meta_json = json.loads(await f.read())
p_files = meta_json.get("provided_files", [])
for pf in p_files:
pf_path = os.path.join(problem_dir, pf)
if os.path.exists(pf_path):
if pf == "Makefile" or pf == "makefile": has_provided_makefile = True
if pf == "main.c" or pf == "main.cpp": has_provided_main = True
async with aiofiles.open(pf_path, "rb") as f_p:
provided_files_data.append((pf, await f_p.read()))
except Exception as e:
logger.warning(f"Failed to load provided files for {job.problem_id}: {e}")
# 處理不同模式
if job.mode == "package":
# Package 模式:題包中包含 submission 代碼、testcase、checker
# file_path 指向 submission 文件
# problem_id 格式為 "package_{submission_id}"
# 讀取 submission 代碼
if os.path.exists(job.file_path):
async with aiofiles.open(job.file_path, "r", encoding="utf-8", errors="ignore") as f:
source_code = await f.read()
else:
raise FileNotFoundError(f"Submission file not found: {job.file_path}")
# 根據語言處理編譯
if lang in ["c", "cpp"]:
student_filename = "main.cpp" if lang == "cpp" else "main.c"
files = [(student_filename, source_code)]
compiler = "/usr/bin/g++" if lang == "cpp" else "/usr/bin/gcc"
compile_result = await self.runner.execute(
box_id=self.box_id,
box_path=box_path,
command=[compiler, student_filename, "-o", "main"],
files=files,
limits={"time_limit_sec": 10, "wall_time_limit_sec": 20, "process_limit": 20},
capture_output_to_files=False,
share_net=share_net,
env=env_vars
)
compile_info = {
"status": "OK" if compile_result['status'] == 'OK' else 'CE',
"stdout": compile_result.get('stdout', ''),
"stderr": compile_result.get('stderr', ''),
"time_used": compile_result.get('time_used_sec', 0),
"memory_used": compile_result.get('memory_used_kb', 0)
}
if compile_result['status'] != 'OK':
result_data = compile_result
result_data['status'] = 'CE'
result_data['compile_info'] = compile_info
compile_success = False
else:
executable_cmd = ["./main"]
run_files_base = []
elif lang == "python":
run_files_base = [("main.py", source_code)]
executable_cmd = ["/usr/bin/python3", "main.py"]
compile_info = {"status": "OK", "message": "Python interpreted"}
else:
result_data = {"status": "XX", "message": f"Language {lang} not supported in package mode"}
compile_success = False
# 執行測試用例
if compile_success:
# Package 模式下,testcase 在上傳的 ZIP 的 extracted 目錄中
# 通過 job.file_path 我們可以找到 work_dir
work_dir = os.path.dirname(os.path.dirname(job.file_path)) # /tmp/sandbox/packages/{submission_id}
testcase_dir = os.path.join(work_dir, "extracted", "testcase")
if not os.path.exists(testcase_dir):
result_data = {"status": "XX", "message": "Testcase directory not found"}
compile_success = False
else:
# 獲取所有測試用例
import glob
in_files = sorted(glob.glob(os.path.join(testcase_dir, "*.in")))
if not in_files:
result_data = {"status": "XX", "message": "No test cases found"}
compile_success = False
else:
# 執行每個測試用例
total_score = 0
cases_results = []
final_status = "AC"
for in_file in in_files:
case_name = os.path.basename(in_file).replace(".in", "")
out_file = in_file.replace(".in", ".out")
# 讀取輸入
async with aiofiles.open(in_file, "r") as f:
stdin_content = await f.read()
# 讀取期望輸出
expected_output = ""
if os.path.exists(out_file):
async with aiofiles.open(out_file, "r") as f:
expected_output = (await f.read()).strip()
# 執行
limits = {
"time_limit_sec": job.request_data.limits.time_limit_sec,
"wall_time_limit_sec": job.request_data.limits.wall_time_limit_sec,
"memory_limit_kb": job.request_data.limits.memory_limit_kb,
"process_limit": 60
}
run_result = await self.runner.execute(
box_id=self.box_id,
box_path=box_path,
command=executable_cmd,
files=run_files_base,
stdin=stdin_content,
limits=limits,
capture_output_to_files=True,
share_net=share_net,
env=env_vars
)
case_status = run_result.get('status', 'XX')
message = run_result.get('message', '')
# Checker 驗證
if case_status == 'OK':
actual_output = run_result.get('stdout', '').strip()
if job.use_checker and job.checker_file_path:
# 使用 Checker(在 Isolate 沙盒中執行)
try:
# 準備 checker 文件
async with aiofiles.open(job.checker_file_path, 'rb') as f:
checker_binary = await f.read()
# 準備輸入文件
# 使用原始測試用例文件名(如 0001.in, 0001.out)
in_filename = f"{case_name}.in"
out_filename = f"{case_name}.out"
checker_files = [
('checker', checker_binary),
(in_filename, stdin_content.encode('utf-8')),
(out_filename, actual_output.encode('utf-8')),
('answer', expected_output.encode('utf-8'))
]
# 在 Isolate 中執行 checker
checker_result = await self.runner.execute(
box_id=self.box_id,
box_path=box_path,
command=['./checker', in_filename, out_filename, 'answer'],
files=checker_files,
stdin='',
limits={
'time_limit_sec': 5.0,
'wall_time_limit_sec': 10.0,
'memory_limit_kb': 262144,
'process_limit': 10
},
capture_output_to_files=True,
share_net=False,
env={}
)
# 判斷結果
if checker_result['status'] == 'OK' and checker_result.get('exitcode', 1) == 0:
case_status = 'AC'
elif checker_result['status'] == 'OK':
case_status = 'WA'
checker_msg = checker_result.get('stderr', '').strip() or checker_result.get('stdout', '').strip()
message = f"Checker: {checker_msg[:100]}"
else:
case_status = 'XX'
message = f"Checker {checker_result['status']}: {checker_result.get('message', '')}"
except Exception as e:
case_status = 'XX'
message = f"Checker error: {str(e)}"
else:
# 默認 diff 比對
if actual_output == expected_output:
case_status = 'AC'
else:
case_status = 'WA'
message = f"Output mismatch"
cases_results.append({
"case_name": case_name,
"status": case_status,
"time": run_result.get('time_used_sec'),
"memory": run_result.get('memory_used_kb'),
"message": message
})
if case_status == 'AC':
total_score += 1
else:
if final_status == 'AC':
final_status = case_status
# 計算總分(百分比)
score_percentage = int((total_score / len(in_files)) * 100)
result_data = {
"status": final_status,
"score": score_percentage,
"tasks": [{
"task_id": 0,
"score": score_percentage,
"cases": cases_results
}],
"compile_info": compile_info,
"time_used_sec": max([c['time'] for c in cases_results] or [0]),
"memory_used_kb": max([c['memory'] for c in cases_results] or [0]),
"message": f"Passed {total_score}/{len(in_files)} test cases"
}
elif job.mode == "zip":
# 讀取 ZIP 內容
if os.path.exists(job.file_path):
async with aiofiles.open(job.file_path, "rb") as f:
zip_content = await f.read()
else:
raise FileNotFoundError(f"Source file not found: {job.file_path}")
# 檢查 ZIP 內容以決定編譯策略
has_makefile = False
has_main_cpp = False
has_main_c = False
try:
with zipfile.ZipFile(io.BytesIO(zip_content)) as z:
namelist = z.namelist()
if "Makefile" in namelist or "makefile" in namelist:
has_makefile = True
if "main.cpp" in namelist:
has_main_cpp = True
if "main.c" in namelist:
has_main_c = True
except zipfile.BadZipFile:
raise ValueError("Invalid ZIP file")
# 設定檔案列表 (IsolateRunner 會自動解壓 .zip)
# 合併題目提供的檔案 (Teacher's files) 與學生的 ZIP
files = provided_files_data + [("source.zip", zip_content)]
# 優先使用 ZIP 內的 Makefile,其次是題目提供的 Makefile
use_make = has_makefile or has_provided_makefile
if use_make:
logger.info(f"Job {job.submission_id}: Makefile detected (Student: {has_makefile}, Teacher: {has_provided_makefile})")
# 使用 make 編譯
compile_result = await self.runner.execute(
box_id=self.box_id,
box_path=box_path,
command=["/usr/bin/make"],
files=files,
limits={"time_limit_sec": 30, "wall_time_limit_sec": 60, "process_limit": 50},
capture_output_to_files=False,
share_net=share_net,
env=env_vars
)
compile_info = {
"status": "OK" if compile_result['status'] == 'OK' else 'CE',
"stdout": compile_result.get('stdout', ''),
"stderr": compile_result.get('stderr', ''),
"time_used": compile_result.get('time_used_sec', 0),
"memory_used": compile_result.get('memory_used_kb', 0)
}
if compile_result['status'] != 'OK':
result_data = compile_result
result_data['status'] = 'CE'
result_data['compile_info'] = compile_info
compile_success = False
else:
# 假設 Makefile 產生的執行檔名為 main
executable_cmd = ["./main"]
run_files_base = []
elif has_main_cpp or has_main_c or has_provided_main:
# ZIP 但沒有 Makefile,嘗試直接編譯 main.cpp/c (包含題目提供的)
# 這裡簡單假設如果是 C++ 就用 g++,否則 gcc
# 如果題目提供了 main.cpp,我們就用 g++
is_cpp = has_main_cpp or (has_provided_main and "cpp" in [f[0] for f in provided_files_data])
compiler = "/usr/bin/g++" if is_cpp else "/usr/bin/gcc"
# 編譯所有 .c / .cpp 檔案
src_pattern = "*.cpp" if is_cpp else "*.c"
# 注意:Isolate 的 execute command 是 execv 風格,不支援 shell wildcard expansion (*.c)
# 所以我們需要用 shell 來執行編譯指令
compile_cmd = ["/bin/sh", "-c", f"{compiler} {src_pattern} -o main"]
compile_result = await self.runner.execute(
box_id=self.box_id,
box_path=box_path,
command=compile_cmd,
files=files, # 傳入 ZIP + Provided Files
limits={"time_limit_sec": 10, "wall_time_limit_sec": 20, "process_limit": 20},
capture_output_to_files=False,
share_net=share_net,
env=env_vars
)
compile_info = {
"status": "OK" if compile_result['status'] == 'OK' else 'CE',
"stdout": compile_result.get('stdout', ''),
"stderr": compile_result.get('stderr', ''),
}
if compile_result['status'] != 'OK':
result_data = compile_result
result_data['status'] = 'CE'
result_data['compile_info'] = compile_info
compile_success = False
else:
executable_cmd = ["./main"]
run_files_base = []
else:
result_data = {"status": "CE", "message": "No Makefile or main.cpp/c found in ZIP or Provided Files"}
compile_success = False
elif lang in ["c", "cpp", "python"]:
# Normal Mode (Single File)
if os.path.exists(job.file_path):
async with aiofiles.open(job.file_path, "r", encoding="utf-8", errors="ignore") as f:
source_code = await f.read()
else:
raise FileNotFoundError(f"Source file not found: {job.file_path}")
if lang in ["c", "cpp"]:
# 決定學生檔案名稱
# 如果題目提供了 main.c/cpp,則學生檔案命名為 solution.c/cpp
# 否則學生檔案命名為 main.c/cpp
student_filename = "main.cpp" if lang == "cpp" else "main.c"
if has_provided_main:
student_filename = "solution.cpp" if lang == "cpp" else "solution.c"
files = provided_files_data + [(student_filename, source_code)] if source_code else provided_files_data
# 決定編譯方式
if has_provided_makefile:
# 使用題目提供的 Makefile
compile_cmd = ["/usr/bin/make"]
else:
# 編譯所有相關檔案
compiler = "/usr/bin/g++" if lang == "cpp" else "/usr/bin/gcc"
src_pattern = "*.cpp" if lang == "cpp" else "*.c"
# 混合 C 和 C++ 的情況比較複雜,這裡暫時假設語言一致
compile_cmd = ["/bin/sh", "-c", f"{compiler} {src_pattern} -o main"]
# Compile
compile_result = await self.runner.execute(
box_id=self.box_id,
box_path=box_path,
command=compile_cmd,
files=files,
limits={"time_limit_sec": 10, "wall_time_limit_sec": 20, "process_limit": 20},
capture_output_to_files=False,
share_net=share_net,
env=env_vars
)
compile_info = {
"status": "OK" if compile_result['status'] == 'OK' else 'CE',
"stdout": compile_result.get('stdout', ''),
"stderr": compile_result.get('stderr', ''),
"time_used": compile_result.get('time_used_sec', 0),
"memory_used": compile_result.get('memory_used_kb', 0)
}
if compile_result['status'] != 'OK':
logger.info(f"Job {job.submission_id} Compilation Failed")
result_data = compile_result
result_data['status'] = 'CE'
result_data['compile_info'] = compile_info
compile_success = False
else:
executable_cmd = ["./main"]
elif lang == "python":
filename = "main.py"
# 如果是 Python,通常是單檔,但如果題目有提供 lib.py,也需要一起放進去
# Python 不需要編譯,直接執行
# 如果題目提供了 main.py (Entry point),則學生檔案可能叫 solution.py
# 但 Python 執行需要指定 Entry point
entry_point = "main.py"
student_filename = "main.py"
# 檢查是否有提供的 main.py
provided_main_py = any(f[0] == "main.py" for f in provided_files_data)
if provided_main_py:
student_filename = "solution.py"
entry_point = "main.py"
run_files_base = provided_files_data + [(student_filename, source_code)]
executable_cmd = ["/usr/bin/python3", entry_point]
compile_info = {"status": "OK", "message": "Python interpreted"}
else:
result_data = {"status": "XX", "message": f"Language {job.language} not fully supported"}
compile_info = {"status": "XX", "message": f"Language {job.language} not supported"}
compile_success = False
# Execution Phase
if compile_success:
# 判斷是否為純自定義測試模式(沒有 problem_id)
has_problem_package = job.problem_id is not None
if has_problem_package:
problem_dir = os.path.join("test_data", "problems", job.problem_id)
meta_path = os.path.join(problem_dir, "meta.json")
else:
problem_dir = None
meta_path = None
# Check if we should run in "Single Case Mode"
# Selftest (is_selftest=True) 永遠走單一執行模式,直接回傳 stdout/stderr
# 其他情況:有 stdin 或沒有題包時也走單一執行
is_selftest = getattr(job, 'is_selftest', False)
if is_selftest or job.stdin is not None or not has_problem_package:
# Single Case Execution
limits = {
"time_limit_sec": job.request_data.limits.time_limit_sec,
"wall_time_limit_sec": job.request_data.limits.wall_time_limit_sec,
"memory_limit_kb": job.request_data.limits.memory_limit_kb,
"process_limit": 60
}
run_result = await self.runner.execute(
box_id=self.box_id,
box_path=box_path,
command=executable_cmd,
files=run_files_base,
stdin=job.stdin,
limits=limits,
capture_output_to_files=True,
share_net=share_net,
env=env_vars
)
case_status = run_result.get('status', 'XX')
message = run_result.get('message', '')
actual_output = run_result.get('stdout', '').strip()
# Checker Logic for Single Case
if case_status == 'OK':
if job.expected_output:
expected = job.expected_output.strip()
if actual_output == expected:
case_status = 'AC'
else:
case_status = 'WA'
message = f"Expected: {expected[:50]}..., Got: {actual_output[:50]}..."
else:
# If no expected output, we assume OK is enough or check return code
pass
result_data = {
"status": case_status,
"score": 100 if case_status == 'AC' else 0,
"tasks": [],
"time_used_sec": run_result.get('time_used_sec'),
"memory_used_kb": run_result.get('memory_used_kb'),
"message": message,
"stdout": actual_output,
"stderr": run_result.get('stderr', ''),
"compile_info": compile_info
}
elif meta_path and os.path.exists(meta_path):
# Multi-task Evaluation
async with aiofiles.open(meta_path, "r") as f:
meta = json.loads(await f.read())
total_score = 0
tasks_results = []
final_status = "AC"
# 檢查是否使用新格式(testcases 陣列)或舊格式(tasks 陣列)
testcases = meta.get("testcases", [])
tasks = meta.get("tasks", [])
if testcases:
# 新格式:後端提供的 testcases 列表
# 格式: [{"no": 1, "stem": "0001", "in": "0001.in", "out": "0001.out"}, ...]
task_count = len(testcases)
score_per_case = 100 // task_count if task_count > 0 else 100
task_passed = True
cases_results = []
for tc in testcases:
case_name = tc.get("stem", "")
in_file = tc.get("in", f"{case_name}.in")
out_file = tc.get("out", f"{case_name}.out")
# 測資直接在題目根目錄(無 testcase 子目錄)
input_file = os.path.join(problem_dir, in_file)
output_file = os.path.join(problem_dir, out_file)
if not os.path.exists(input_file):
cases_results.append({
"case_name": case_name,
"status": "SKIPPED",
"time": 0,
"memory": 0,
"message": f"Input file not found: {in_file}"
})
task_passed = False
if final_status == "AC":
final_status = "XX"
continue
# Read Input
async with aiofiles.open(input_file, "r") as f:
stdin_content = await f.read()
# Read Expected Output
expected_output = ""
if os.path.exists(output_file):
async with aiofiles.open(output_file, "r") as f:
expected_output = (await f.read()).strip()
# 使用 job 的 limits 或預設值
isolate_limits = {
"time_limit_sec": job.request_data.limits.time_limit_sec,
"wall_time_limit_sec": job.request_data.limits.wall_time_limit_sec,
"memory_limit_kb": job.request_data.limits.memory_limit_kb,
"process_limit": 60
}
# Execute
run_result = await self.runner.execute(
box_id=self.box_id,
box_path=box_path,
command=executable_cmd,
files=run_files_base,
stdin=stdin_content,
limits=isolate_limits,
capture_output_to_files=True,
share_net=share_net,
env=env_vars
)
# Verify - 確保 case_status 總是被初始化
case_status = run_result.get('status', 'XX')
message = run_result.get('message', '')
llm_feedback = None # LLM judge 回饋
case_score = 0 # 單測資得分
if case_status == 'OK':
actual_output = run_result.get('stdout', '').strip()
# 判題邏輯:檢查 judge_type
judge_type = meta.get("judge_type", "diff") # 預設為 diff
if judge_type == "llm":
# LLM-as-Judge 判題
try:
llm_result = await llm_judge_case(
meta=meta,
student_output=actual_output,
stdin_content=stdin_content,
expected_output=expected_output
)
case_status = llm_result["verdict"]
case_score = llm_result["score"]
message = llm_result["reason"]
llm_feedback = llm_result.get("llm_feedback")
logger.info(f"LLM judge result for {case_name}: {case_status}, score={case_score}")
except Exception as e:
logger.error(f"LLM judge error for {case_name}: {e}")
case_status = 'JE'
message = f"LLM Judge Error: {str(e)[:100]}"
# Checker Logic (原有邏輯)
elif job.use_checker:
if job.checker_file_path == "diff":
if actual_output == expected_output:
case_status = 'AC'
else:
case_status = 'WA'
message = f"Expected: {expected_output[:50]}..., Got: {actual_output[:50]}..."
elif job.checker_file_path and os.path.exists(job.checker_file_path):
# Custom Checker
try:
async with aiofiles.open(job.checker_file_path, 'rb') as f:
checker_binary = await f.read()
in_filename = f"{case_name}.in"
out_filename = f"{case_name}.out"
if job.checker_file_path.endswith('.py'):
checker_files = [
('checker.py', checker_binary),
(in_filename, stdin_content.encode('utf-8')),
(out_filename, actual_output.encode('utf-8')),
('answer', expected_output.encode('utf-8'))
]
checker_cmd = ['/usr/bin/python3', 'checker.py', in_filename, out_filename, 'answer']
else:
checker_files = [
('checker', checker_binary),
(in_filename, stdin_content.encode('utf-8')),
(out_filename, actual_output.encode('utf-8')),
('answer', expected_output.encode('utf-8'))
]
checker_cmd = ['./checker', in_filename, out_filename, 'answer']