def __exit__(self, exc_type, exc_val, exc_tb): if not DEBUG: try: shutil.rmtree(self.work_dir) #删除工作目录下的所有文件 except Exception as e: logger.exception(e) raise JudgeClientError("failed to clean runtime dir")
def server(path): if path in ("judge", "ping", "compile_spj"): _token = request.headers.get("X-Judge-Server-Token") try: if _token != token: raise TokenVerificationFailed("invalid token") try: data = request.json except Exception: data = {} #print(data) ret = {"err": None, "data": getattr(JudgeServer, path)(**data)} except (CompileError, TokenVerificationFailed, SPJCompileError, JudgeClientError) as e: logger.exception(e) ret = {"err": e.__class__.__name__, "data": e.message} except Exception as e: logger.exception(e) ret = { "err": "JudgeClientError", "data": e.__class__.__name__ + " :" + str(e) } else: ret = {"err": "InvalidRequest", "data": "404"} return Response(json.dumps(ret), mimetype='application/json')
def __enter__(self): try: os.mkdir(self.work_dir) #创建工作目录 if self.init_test_case_dir: os.mkdir(self.test_case_dir) #创建测试样例目录 os.chown(self.work_dir, COMPILER_USER_UID, RUN_GROUP_GID) #修改文件的属主和属组 os.chmod(self.work_dir, 0o711) #dir权限711 except Exception as e: logger.exception(e) raise JudgeClientError("failed to create runtime dir") return self.work_dir, self.test_case_dir
def run(self): def signal_handler(*args): logger.info('Received SIGTERM, shutting down.') logger.info("Stopping threads, please wait...") # teardown() self.raw_report_processor.stop() site = twisted.web.server.Site(self.__root_resource) if self.__ssl_enabled: ssl_context = self.__load_ssl_certs() self.__listen_func = functools.partial(reactor.listenSSL, contextFactory=ssl_context) else: self.__listen_func = reactor.listenTCP try: self.install_signal() # start threads and processes self.raw_report_processor = RawReportProcessor() self.raw_report_processor.start() # web and static content self.__listen_func(self.__listen_port, site, interface=self.__bind_address) # websockets try: listenWS(self.__build_websockets_resource(), interface=self.__bind_address) except: logger.warn( 'Could not start websockets, address already open. This is ok is you wan to run multiple instances.' ) logger.info('Faraday Server is ready') reactor.addSystemEventTrigger('before', 'shutdown', signal_handler) reactor.run() except error.CannotListenError as e: logger.error(str(e)) sys.exit(1) except Exception as e: logger.error( 'Something went wrong when trying to setup the Web UI') logger.exception(e) sys.exit(1)
def _request(self, data): try: resp = requests.post(self.backend_url, json=data, headers={ "X-JUDGE-SERVER-TOKEN": token, "Content-Type": "application/json" }, timeout=5).text except Exception as e: logger.exception(e) raise JudgeServiceError("Heartbeat request failed") try: r = json.loads(resp) if r["error"]: raise JudgeServiceError(r["data"]) except Exception as e: logger.exception("Heartbeat failed, response is {}".format(resp)) raise JudgeServiceError("Invalid heartbeat response")
def onMessage(self, payload, is_binary): from server.web import app """ We only support JOIN and LEAVE workspace messages. When authentication is implemented we need to verify that the user can join the selected workspace. When authentication is implemented we need to reply the client if the join failed. """ if not is_binary: message = json.loads(payload) if message['action'] == 'JOIN_WORKSPACE': if 'workspace' not in message or 'token' not in message: logger.warning('Invalid join workspace message: ' '{}'.format(message)) self.sendClose() return signer = itsdangerous.TimestampSigner(app.config['SECRET_KEY'], salt="websocket") try: workspace_id = signer.unsign(message['token'], max_age=60) except itsdangerous.BadData as e: self.sendClose() logger.warning('Invalid websocket token for workspace ' '{}'.format(message['workspace'])) logger.exception(e) else: with app.app_context(): workspace = Workspace.query.get(int(workspace_id)) if workspace.name != message['workspace']: logger.warning( 'Trying to join workspace {} with token of ' 'workspace {}. Rejecting.'.format( message['workspace'], workspace.name )) self.sendClose() else: self.factory.join_workspace( self, message['workspace']) if message['action'] == 'LEAVE_WORKSPACE': self.factory.leave_workspace(self, message['workspace'])
def run(self): def signal_handler(*args): logger.info("Stopping threads, please wait...") # teardown() self.raw_report_processor.stop() reactor.stop() site = twisted.web.server.Site(self.__root_resource) if self.__ssl_enabled: ssl_context = self.__load_ssl_certs() self.__listen_func = functools.partial( reactor.listenSSL, contextFactory=ssl_context) else: self.__listen_func = reactor.listenTCP try: self.install_signal() # start threads and processes self.raw_report_processor = RawReportProcessor() self.raw_report_processor.start() # web and static content self.__listen_func( self.__listen_port, site, interface=self.__bind_address) # websockets try: listenWS(self.__build_websockets_resource(), interface=self.__bind_address) except : logger.warn('Could not start websockets, address already open. This is ok is you wan to run multiple instances.') logger.info('Faraday Server is ready') reactor.addSystemEventTrigger('before', 'shutdown', signal_handler) reactor.run() except error.CannotListenError as e: logger.error(str(e)) sys.exit(1) except Exception as e: logger.error('Something went wrong when trying to setup the Web UI') logger.exception(e) sys.exit(1)
def onMessage(self, payload, is_binary): from server.web import app """ We only support JOIN and LEAVE workspace messages. When authentication is implemented we need to verify that the user can join the selected workspace. When authentication is implemented we need to reply the client if the join failed. """ if not is_binary: message = json.loads(payload) if message['action'] == 'JOIN_WORKSPACE': if 'workspace' not in message or 'token' not in message: logger.warning('Invalid join workspace message: ' '{}'.format(message)) self.sendClose() return signer = itsdangerous.TimestampSigner(app.config['SECRET_KEY'], salt="websocket") try: workspace_id = signer.unsign(message['token'], max_age=60) except itsdangerous.BadData as e: self.sendClose() logger.warning('Invalid websocket token for workspace ' '{}'.format(message['workspace'])) logger.exception(e) else: with app.app_context(): workspace = Workspace.query.get(int(workspace_id)) if workspace.name != message['workspace']: logger.warning( 'Trying to join workspace {} with token of ' 'workspace {}. Rejecting.'.format( message['workspace'], workspace.name)) self.sendClose() else: self.factory.join_workspace(self, message['workspace']) if message['action'] == 'LEAVE_WORKSPACE': self.factory.leave_workspace(self, message['workspace'])
"Content-Type": "application/json" }, timeout=5).text except Exception as e: logger.exception(e) raise JudgeServiceError("Heartbeat request failed") try: r = json.loads(resp) if r["error"]: raise JudgeServiceError(r["data"]) except Exception as e: logger.exception("Heartbeat failed, response is {}".format(resp)) raise JudgeServiceError("Invalid heartbeat response") def heartbeat(self): data = server_info() data["action"] = "heartbeat" data["service_url"] = self.service_url self._request(data) if __name__ == "__main__": try: if not os.environ.get("DISABLE_HEARTBEAT"): service = JudgeService() service.heartbeat() exit(0) except Exception as e: logger.exception(e) exit(1)