2020-01-21 06:35:58 +00:00
|
|
|
import json
|
|
|
|
import logging
|
|
|
|
import struct
|
|
|
|
|
2020-07-19 21:27:14 +00:00
|
|
|
from judge.bridge.base_handler import Disconnect, ZlibPacketHandler
|
2020-01-21 06:35:58 +00:00
|
|
|
|
|
|
|
logger = logging.getLogger('judge.bridge')
|
|
|
|
size_pack = struct.Struct('!I')
|
|
|
|
|
|
|
|
|
|
|
|
class DjangoHandler(ZlibPacketHandler):
|
2020-07-19 21:27:14 +00:00
|
|
|
def __init__(self, request, client_address, server, judges):
|
|
|
|
super().__init__(request, client_address, server)
|
2020-01-21 06:35:58 +00:00
|
|
|
|
|
|
|
self.handlers = {
|
|
|
|
'submission-request': self.on_submission,
|
|
|
|
'terminate-submission': self.on_termination,
|
2020-07-19 21:27:14 +00:00
|
|
|
'disconnect-judge': self.on_disconnect_request,
|
2020-01-21 06:35:58 +00:00
|
|
|
}
|
2020-07-19 21:27:14 +00:00
|
|
|
self.judges = judges
|
2020-01-21 06:35:58 +00:00
|
|
|
|
2020-07-19 21:27:14 +00:00
|
|
|
def send(self, data):
|
|
|
|
super().send(json.dumps(data, separators=(',', ':')))
|
2020-01-21 06:35:58 +00:00
|
|
|
|
2020-07-19 21:27:14 +00:00
|
|
|
def on_packet(self, packet):
|
2020-01-21 06:35:58 +00:00
|
|
|
packet = json.loads(packet)
|
|
|
|
try:
|
|
|
|
result = self.handlers.get(packet.get('name', None), self.on_malformed)(packet)
|
|
|
|
except Exception:
|
|
|
|
logger.exception('Error in packet handling (Django-facing)')
|
|
|
|
result = {'name': 'bad-request'}
|
2020-07-19 21:27:14 +00:00
|
|
|
self.send(result)
|
|
|
|
raise Disconnect()
|
2020-01-21 06:35:58 +00:00
|
|
|
|
|
|
|
def on_submission(self, data):
|
|
|
|
id = data['submission-id']
|
|
|
|
problem = data['problem-id']
|
|
|
|
language = data['language']
|
|
|
|
source = data['source']
|
2020-07-19 21:27:14 +00:00
|
|
|
judge_id = data['judge-id']
|
2020-01-21 06:35:58 +00:00
|
|
|
priority = data['priority']
|
2020-07-19 21:27:14 +00:00
|
|
|
if not self.judges.check_priority(priority):
|
2020-01-21 06:35:58 +00:00
|
|
|
return {'name': 'bad-request'}
|
2020-07-19 21:27:14 +00:00
|
|
|
self.judges.judge(id, problem, language, source, judge_id, priority)
|
2020-01-21 06:35:58 +00:00
|
|
|
return {'name': 'submission-received', 'submission-id': id}
|
|
|
|
|
|
|
|
def on_termination(self, data):
|
2020-07-19 21:27:14 +00:00
|
|
|
return {'name': 'submission-received', 'judge-aborted': self.judges.abort(data['submission-id'])}
|
2020-01-21 06:35:58 +00:00
|
|
|
|
2020-07-19 21:27:14 +00:00
|
|
|
def on_disconnect_request(self, data):
|
2020-01-21 06:35:58 +00:00
|
|
|
judge_id = data['judge-id']
|
|
|
|
force = data['force']
|
2020-07-19 21:27:14 +00:00
|
|
|
self.judges.disconnect(judge_id, force=force)
|
2020-01-21 06:35:58 +00:00
|
|
|
|
|
|
|
def on_malformed(self, packet):
|
|
|
|
logger.error('Malformed packet: %s', packet)
|
|
|
|
|
|
|
|
def on_close(self):
|
|
|
|
self._to_kill = False
|