forked from pzread/judge
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathServer.py
215 lines (160 loc) · 5.65 KB
/
Server.py
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
'''Server module.
Handle and response challenge requests from the frontend server.
'''
import sys
import json
import traceback
from collections import deque
from tornado import gen, concurrent
from tornado.ioloop import IOLoop, PollIOLoop
from tornado.web import Application, RequestHandler
from tornado.websocket import WebSocketHandler
import PyExt
import Privilege
import Config
from StdChal import StdChal
class EvIOLoop(PollIOLoop):
'''Tornado compatible ioloop interface.'''
def initialize(self, **kwargs):
'''Initialize.'''
super().initialize(impl=PyExt.EvPoll(), **kwargs)
class JudgeDispatcher:
'''Judge request dispatcher.
Static attributes:
chal_running_count (int): Number of current running challenges.
chal_queue (deque): Pending challenges.
'''
chal_running_count = 0
chal_queue = deque()
@staticmethod
@gen.coroutine
def start_chal(obj, callback):
'''Start a challenge.
Check the challenge config, issue judge tasks, then report the result.
Args:
obj (dict): Challenge config.
callback: Challenge callback.
Returns:
None
'''
# The worst exception, there is no chal_id in the obj.
chal_id = None
try:
chal_id = obj['chal_id']
code_path = obj['code_path']
res_path = obj['res_path']
test_list = obj['test']
metadata = obj['metadata']
comp_type = obj['comp_type']
check_type = obj['check_type']
test_paramlist = list()
assert comp_type in ['g++', 'clang++', 'makefile', 'python3']
assert check_type in ['diff', 'ioredir']
for test in test_list:
test_idx = test['test_idx']
memlimit = test['memlimit']
timelimit = test['timelimit']
data_ids = test['metadata']['data']
for data_id in data_ids:
test_paramlist.append({
'in': res_path + '/testdata/%d.in'%data_id,
'ans': res_path + '/testdata/%d.out'%data_id,
'timelimit': timelimit,
'memlimit': memlimit,
})
chal = StdChal(chal_id, code_path, comp_type, check_type, \
res_path, test_paramlist, metadata)
result_list = yield chal.start()
result = []
idx = 0
for test in test_list:
test_idx = test['test_idx']
data_ids = test['metadata']['data']
total_runtime = 0
total_mem = 0
total_status = 0
subverdicts = list()
for data_id in data_ids:
runtime, peakmem, status, subverdict = result_list[idx]
total_runtime += runtime
total_mem += peakmem
total_status = max(total_status, status)
subverdicts.append(subverdict)
idx += 1
result.append({
'test_idx': test_idx,
'state': total_status,
'runtime': total_runtime,
'peakmem': total_mem,
'verdict': subverdicts,
})
callback({
'chal_id': chal_id,
'result': result,
})
except Exception:
traceback.print_exception(*sys.exc_info())
callback({
'chal_id': chal_id,
'verdict': None,
'result': None,
})
finally:
JudgeDispatcher.chal_running_count -= 1
JudgeDispatcher.emit_chal()
@staticmethod
def emit_chal(obj=None, callback=None):
'''Emit a challenge to the queue and trigger the start_chal.
Args:
obj (dict, optional): Challenge config.
callback: Challange callback.
Returns:
None
'''
if obj is not None:
JudgeDispatcher.chal_queue.append((obj, callback))
while (len(JudgeDispatcher.chal_queue) > 0
and JudgeDispatcher.chal_running_count < Config.TASK_MAXCONCURRENT):
chal = JudgeDispatcher.chal_queue.popleft()
JudgeDispatcher.chal_running_count += 1
IOLoop.instance().add_callback(JudgeDispatcher.start_chal, *chal)
class WebSocketClient(WebSocketHandler):
'''Websocket request handler.'''
def open(self):
'''Handle open event'''
print('Frontend connected')
def on_message(self, msg):
'''Handle message event'''
obj = json.loads(msg)
JudgeDispatcher.emit_chal(obj,
lambda res: self.write_message(json.dumps(res)))
def on_close(self):
'''Handle close event'''
print('Frontend disconnected')
class RequestClient(RequestHandler):
'''HTTP request handler.'''
@concurrent.return_future
def post(self, callback):
'''Handle POST request'''
def _chal_cb(res):
self.write(res)
callback()
obj = json.loads(self.request.body.decode('utf-8'))
JudgeDispatcher.emit_chal(obj, _chal_cb)
def init_socket_server():
'''Initialize socket server.'''
app = Application([
(r'/judge', WebSocketClient),
(r'/reqjudge', RequestClient),
])
app.listen(2501)
def main():
'''Main function.'''
Privilege.init()
PyExt.init()
StdChal.init()
IOLoop.configure(EvIOLoop)
init_socket_server()
IOLoop.instance().start()
if __name__ == '__main__':
main()