Skip to content

Commit 83189c9

Browse files
committed
fix running tester
1 parent 5e8a050 commit 83189c9

File tree

3 files changed

+50
-29
lines changed

3 files changed

+50
-29
lines changed

judge/testing.py

+40-4
Original file line numberDiff line numberDiff line change
@@ -23,9 +23,34 @@ def create_new_problem_from_template(new_problem_id: str, old_problem_id: str):
2323
new_path = PathManager.problem_dir(new_problem_id)
2424
os.makedirs(new_path, exist_ok=True)
2525
for filename in os.listdir(old_path):
26-
shutil.copyfile(join(old_path, filename), join(new_path, filename))
26+
shutil.copy2(join(old_path, filename), new_path)
2727
print(f'create problem instance {new_path}')
2828

29+
def make_file_executable(file_path):
30+
try:
31+
# Define the executable permission in octal format (e.g., 0o755).
32+
# This gives read, write, and execute permissions to the owner,
33+
# and read and execute permissions to the group and others.
34+
executable_permission = 0o755
35+
36+
# Change the file's permission to make it executable.
37+
os.chmod(file_path, executable_permission)
38+
return True
39+
except Exception as e:
40+
print(f"Error: {e}")
41+
return False
42+
43+
44+
def run_command_with_sudo(command):
45+
try:
46+
# Use the 'sudo' command to execute the given command with elevated privileges.
47+
result = subprocess.run(['sudo'] + command, capture_output=True, text=True, check=True)
48+
return result
49+
except subprocess.CalledProcessError as e:
50+
print(f"Error: {e}")
51+
return None
52+
53+
2954
class PathManager:
3055
@staticmethod
3156
def problem_dir(problem_id: str) -> str:
@@ -111,6 +136,8 @@ def upload(self) -> bool:
111136
shutil.rmtree(dirname(self.zip_file_path))
112137
print(f"remove {dirname(self.zip_file_path)}")
113138

139+
make_file_executable(join(self.problem_dir_path, TESTER_NAME))
140+
114141
return valid
115142

116143

@@ -121,22 +148,31 @@ def __init__(self, submission: Submission):
121148
if not exists(self.sub_dirpath):
122149
os.makedirs(self.sub_dirpath, exist_ok=True)
123150
prob_dir = PathManager.problem_dir(submission.problem._id) # use display id
151+
print('problem id:', submission.problem._id)
152+
print('problem dir:', prob_dir)
124153
if not exists(prob_dir):
125154
raise Exception("problem dir {} not exists".format(prob_dir))
126155
for filename in os.listdir(prob_dir):
127-
shutil.copyfile(join(prob_dir, filename), self.sub_dirpath)
156+
print(f'copy {join(prob_dir, filename)} to {self.sub_dirpath}')
157+
shutil.copy2(join(prob_dir, filename), self.sub_dirpath)
128158

129159
def judge(self):
130160
tester_path = join(self.sub_dirpath, TESTER_NAME)
131161
if not exists(tester_path):
132162
raise Exception("running submission: tester {} not exists".format(tester_path))
133163
print(f"running {tester_path}")
134-
subprocess.run([tester_path, '--log', '--json'])
164+
result = run_command_with_sudo([tester_path, "--log", "--json"])
165+
if result:
166+
print("Command output:")
167+
print(result.stdout)
168+
else:
169+
print("Command execution failed.")
170+
135171
log_path = join(self.sub_dirpath, 'logs')
136172
if not exists(log_path):
137173
raise Exception(f"logs path {log_path} not exists")
138174
failed_info = []
139-
with open(join(log_path, "results.txt")) as fp:
175+
with open(join(log_path, "results.json")) as fp:
140176
res = json.load(fp)
141177
self.sub.grade = res['grade']
142178
for idx in res['failed']:

submission/serializers.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -41,7 +41,7 @@ def __init__(self, *args, **kwargs):
4141

4242
class Meta:
4343
model = Submission
44-
exclude = ("info", "contest", "code_list", "ip")
44+
exclude = ("contest", "code_list", "ip")
4545

4646
def get_show_link(self, obj):
4747
# 没传user或为匿名user

submission/views/user.py

+9-24
Original file line numberDiff line numberDiff line change
@@ -2,21 +2,18 @@
22
import hashlib
33
import requests
44
import logging
5-
import json
6-
from os import path
7-
from datetime import datetime
85
from django.db import transaction
96

107
from account.decorators import login_required, check_contest_permission
118
from account.models import User, UserProfile
129
from conf.models import JudgeServer
1310
from contest.models import Contest, ContestStatus
11+
from judge.testing import SubmissionTester
1412
from options.options import SysOptions
1513
from problem.models import Problem
1614
from judge.tasks import local_judge_task
1715
from judge.dispatcher import process_pending_task
1816
from judge.dispatcher import JudgeStatus
19-
from judge.testing import PathManager
2017
from utils.api import APIView, validate_serializer, CSRFExemptAPIView
2118
from utils.cache import cache
2219
from utils.throttling import TokenBucket
@@ -31,23 +28,6 @@
3128

3229
logger = logging.getLogger(__name__)
3330

34-
def update_submission_status(submission: Submission):
35-
log_path = path.join(PathManager.submission_dir(submission.id), 'logs')
36-
if path.exists(log_path):
37-
submission.result = JudgeStatus.FINISHED
38-
failed_info = []
39-
with open(path.join(log_path, "results.txt")) as fp:
40-
res = json.load(fp)
41-
submission.grade = res['grade']
42-
for idx in res['failed']:
43-
with open(path.join(log_path, f"testcase{idx}.log")) as log_fp:
44-
failed_info.append({
45-
'testcase_index': idx,
46-
'log': log_fp.read()
47-
})
48-
submission.failed_info = failed_info
49-
submission.save()
50-
5131
class SubmissionAPI(APIView):
5232
def __init__(self, **kwargs):
5333
super().__init__(**kwargs)
@@ -143,6 +123,8 @@ def post(self, request):
143123

144124
# execute judge task in dramatiq
145125
# local_judge_task.send(submission.id, problem._id)
126+
tester = SubmissionTester(submission)
127+
tester.judge()
146128

147129
if hide_id:
148130
return self.success()
@@ -166,7 +148,8 @@ def get(self, request):
166148
return self.error("No permission for this submission")
167149

168150
if submission.result in [JudgeStatus.PENDING, JudgeStatus.JUDGING]:
169-
update_submission_status(submission)
151+
# update_submission_status(submission)
152+
pass
170153

171154
submission_data = SubmissionSafeModelSerializer(submission).data
172155
submission_data["can_unshare"] = submission.check_user_permission(
@@ -216,7 +199,8 @@ def get(self, request):
216199

217200
for submission in submissions:
218201
if submission.result in [JudgeStatus.PENDING, JudgeStatus.JUDGING]:
219-
update_submission_status(submission)
202+
# update_submission_status(submission)
203+
pass
220204

221205
problem_id = request.GET.get("problem_id")
222206
result = request.GET.get("result")
@@ -266,7 +250,8 @@ def get(self, request):
266250
)
267251
for submission in submissions:
268252
if submission.result in [JudgeStatus.PENDING, JudgeStatus.JUDGING]:
269-
update_submission_status(submission)
253+
# update_submission_status(submission)
254+
pass
270255

271256
problem_id = request.GET.get("problem_id")
272257
result = request.GET.get("result")

0 commit comments

Comments
 (0)