inital commit 1
This commit is contained in:
commit
5c7b9edf97
42 files changed
+2371
No files matched your search
@@ -0,0 +1 @@
|
||||
3.14.4
|
||||
Whitespace-only changes.
@@ -0,0 +1,49 @@
|
||||
import _judger
|
||||
import json
|
||||
import os
|
||||
|
||||
from config import COMPILER_LOG_PATH, COMPILER_USER_UID, COMPILER_GROUP_GID
|
||||
from exception import CompileError
|
||||
import shlex
|
||||
|
||||
|
||||
class Compiler(object):
|
||||
def compile(self, compile_config, src_path, output_dir):
|
||||
command = compile_config["compile_command"]
|
||||
exe_path = os.path.join(output_dir, compile_config["exe_name"])
|
||||
command = command.format(src_path=src_path, exe_dir=output_dir, exe_path=exe_path)
|
||||
compiler_out = os.path.join(output_dir, "compiler.out")
|
||||
_command = shlex.split(command)
|
||||
|
||||
os.chdir(output_dir)
|
||||
env = compile_config.get("env", [])
|
||||
env.append("PATH=" + os.getenv("PATH"))
|
||||
result = _judger.run(max_cpu_time=compile_config["max_cpu_time"],
|
||||
max_real_time=compile_config["max_real_time"],
|
||||
max_memory=compile_config["max_memory"],
|
||||
max_stack=128 * 1024 * 1024,
|
||||
max_output_size=20 * 1024 * 1024,
|
||||
max_process_number=_judger.UNLIMITED,
|
||||
exe_path=_command[0],
|
||||
# /dev/null is best, but in some system, this will call ioctl system call
|
||||
input_path=src_path,
|
||||
output_path=compiler_out,
|
||||
error_path=compiler_out,
|
||||
args=_command[1::],
|
||||
env=env,
|
||||
log_path=COMPILER_LOG_PATH,
|
||||
seccomp_rule_name=None,
|
||||
uid=COMPILER_USER_UID,
|
||||
gid=COMPILER_GROUP_GID)
|
||||
|
||||
if result["result"] != _judger.RESULT_SUCCESS:
|
||||
if os.path.exists(compiler_out):
|
||||
with open(compiler_out, encoding="utf-8") as f:
|
||||
error = f.read().strip()
|
||||
os.remove(compiler_out)
|
||||
if error:
|
||||
raise CompileError(error)
|
||||
raise CompileError("Compiler runtime error, info: %s" % json.dumps(result))
|
||||
else:
|
||||
os.remove(compiler_out)
|
||||
return exe_path
|
||||
@@ -0,0 +1,24 @@
|
||||
import os
|
||||
import pwd
|
||||
|
||||
import grp
|
||||
|
||||
JUDGER_WORKSPACE_BASE = "/judger/run"
|
||||
LOG_BASE = "/log"
|
||||
|
||||
COMPILER_LOG_PATH = os.path.join(LOG_BASE, "compile.log")
|
||||
JUDGER_RUN_LOG_PATH = os.path.join(LOG_BASE, "judger.log")
|
||||
SERVER_LOG_PATH = os.path.join(LOG_BASE, "judge_server.log")
|
||||
|
||||
RUN_USER_UID = pwd.getpwnam("code").pw_uid
|
||||
RUN_GROUP_GID = grp.getgrnam("code").gr_gid
|
||||
|
||||
COMPILER_USER_UID = pwd.getpwnam("compiler").pw_uid
|
||||
COMPILER_GROUP_GID = grp.getgrnam("compiler").gr_gid
|
||||
|
||||
SPJ_USER_UID = pwd.getpwnam("spj").pw_uid
|
||||
SPJ_GROUP_GID = grp.getgrnam("spj").gr_gid
|
||||
|
||||
TEST_CASE_DIR = "/test_case"
|
||||
SPJ_SRC_DIR = "/judger/spj"
|
||||
SPJ_EXE_DIR = "/judger/spj"
|
||||
@@ -0,0 +1,20 @@
|
||||
#!/bin/sh
|
||||
set -ex
|
||||
|
||||
rm -rf /judger/*
|
||||
mkdir -p /judger/run /judger/spj
|
||||
|
||||
chown compiler:code /judger/run
|
||||
chmod 711 /judger/run
|
||||
|
||||
chown compiler:spj /judger/spj
|
||||
chmod 710 /judger/spj
|
||||
|
||||
CPU_CORE_NUM="$(nproc)"
|
||||
if [ "$CPU_CORE_NUM" -lt 2 ]; then
|
||||
export WORKER_NUM=2;
|
||||
else
|
||||
export WORKER_NUM="$CPU_CORE_NUM";
|
||||
fi
|
||||
|
||||
exec .venv/bin/gunicorn server:app --workers $WORKER_NUM --threads 4 --error-logfile /log/gunicorn.log --bind 0.0.0.0:8080
|
||||
@@ -0,0 +1,24 @@
|
||||
class JudgeServerException(Exception):
|
||||
def __init__(self, message):
|
||||
super().__init__()
|
||||
self.message = message
|
||||
|
||||
|
||||
class CompileError(JudgeServerException):
|
||||
pass
|
||||
|
||||
|
||||
class SPJCompileError(JudgeServerException):
|
||||
pass
|
||||
|
||||
|
||||
class TokenVerificationFailed(JudgeServerException):
|
||||
pass
|
||||
|
||||
|
||||
class JudgeClientError(JudgeServerException):
|
||||
pass
|
||||
|
||||
|
||||
class JudgeServiceError(JudgeServerException):
|
||||
pass
|
||||
@@ -0,0 +1,194 @@
|
||||
import _judger
|
||||
import hashlib
|
||||
import json
|
||||
import os
|
||||
import shutil
|
||||
from multiprocessing import Pool
|
||||
import shlex
|
||||
|
||||
import psutil
|
||||
|
||||
from config import TEST_CASE_DIR, JUDGER_RUN_LOG_PATH, RUN_GROUP_GID, RUN_USER_UID, SPJ_EXE_DIR, SPJ_USER_UID, SPJ_GROUP_GID, RUN_GROUP_GID
|
||||
from exception import JudgeClientError
|
||||
from utils import ProblemIOMode
|
||||
|
||||
SPJ_WA = 1
|
||||
SPJ_AC = 0
|
||||
SPJ_ERROR = -1
|
||||
|
||||
|
||||
def _run(instance, test_case_file_id):
|
||||
return instance._judge_one(test_case_file_id)
|
||||
|
||||
|
||||
class JudgeClient(object):
|
||||
def __init__(self, run_config, exe_path, max_cpu_time, max_memory, test_case_dir,
|
||||
submission_dir, spj_version, spj_config, io_mode, output=False):
|
||||
self._run_config = run_config
|
||||
self._exe_path = exe_path
|
||||
self._max_cpu_time = max_cpu_time
|
||||
self._max_memory = max_memory
|
||||
self._max_real_time = self._max_cpu_time * 3
|
||||
self._test_case_dir = test_case_dir
|
||||
self._submission_dir = submission_dir
|
||||
|
||||
self._test_case_info = self._load_test_case_info()
|
||||
|
||||
self._spj_version = spj_version
|
||||
self._spj_config = spj_config
|
||||
self._output = output
|
||||
self._io_mode = io_mode
|
||||
|
||||
if self._spj_version and self._spj_config:
|
||||
self._spj_exe = os.path.join(SPJ_EXE_DIR,
|
||||
self._spj_config["exe_name"].format(spj_version=self._spj_version))
|
||||
if not os.path.exists(self._spj_exe):
|
||||
raise JudgeClientError("spj exe not found")
|
||||
|
||||
def _load_test_case_info(self):
|
||||
try:
|
||||
with open(os.path.join(self._test_case_dir, "info")) as f:
|
||||
return json.load(f)
|
||||
except IOError:
|
||||
raise JudgeClientError("Test case not found")
|
||||
except ValueError:
|
||||
raise JudgeClientError("Bad test case config")
|
||||
|
||||
def _get_test_case_file_info(self, test_case_file_id):
|
||||
return self._test_case_info["test_cases"][test_case_file_id]
|
||||
|
||||
def _compare_output(self, test_case_file_id, user_output_file):
|
||||
with open(user_output_file, "rb") as f:
|
||||
content = f.read()
|
||||
output_md5 = hashlib.md5(content.rstrip()).hexdigest()
|
||||
result = output_md5 == self._get_test_case_file_info(test_case_file_id)["stripped_output_md5"]
|
||||
return output_md5, result
|
||||
|
||||
def _spj(self, in_file_path, user_out_file_path):
|
||||
os.chown(self._submission_dir, SPJ_USER_UID, 0)
|
||||
os.chown(user_out_file_path, SPJ_USER_UID, 0)
|
||||
os.chmod(user_out_file_path, 0o740)
|
||||
command = self._spj_config["command"].format(exe_path=self._spj_exe,
|
||||
in_file_path=in_file_path,
|
||||
user_out_file_path=user_out_file_path)
|
||||
command = shlex.split(command)
|
||||
seccomp_rule_name = self._spj_config["seccomp_rule"]
|
||||
result = _judger.run(max_cpu_time=self._max_cpu_time * 3,
|
||||
max_real_time=self._max_cpu_time * 9,
|
||||
max_memory=self._max_memory * 3,
|
||||
max_stack=128 * 1024 * 1024,
|
||||
max_output_size=1024 * 1024 * 1024,
|
||||
max_process_number=_judger.UNLIMITED,
|
||||
exe_path=command[0],
|
||||
input_path=in_file_path,
|
||||
output_path="/tmp/spj.out",
|
||||
error_path="/tmp/spj.out",
|
||||
args=command[1::],
|
||||
env=["PATH=" + os.environ.get("PATH", "")],
|
||||
log_path=JUDGER_RUN_LOG_PATH,
|
||||
seccomp_rule_name=seccomp_rule_name,
|
||||
uid=SPJ_USER_UID,
|
||||
gid=SPJ_GROUP_GID)
|
||||
|
||||
if result["result"] == _judger.RESULT_SUCCESS or \
|
||||
(result["result"] == _judger.RESULT_RUNTIME_ERROR and
|
||||
result["exit_code"] in [SPJ_WA, SPJ_ERROR] and result["signal"] == 0):
|
||||
return result["exit_code"]
|
||||
else:
|
||||
return SPJ_ERROR
|
||||
|
||||
def _judge_one(self, test_case_file_id):
|
||||
test_case_info = self._get_test_case_file_info(test_case_file_id)
|
||||
in_file = os.path.join(self._test_case_dir, test_case_info["input_name"])
|
||||
|
||||
if self._io_mode["io_mode"] == ProblemIOMode.file:
|
||||
user_output_dir = os.path.join(self._submission_dir, str(test_case_file_id))
|
||||
os.mkdir(user_output_dir)
|
||||
os.chown(user_output_dir, RUN_USER_UID, RUN_GROUP_GID)
|
||||
os.chmod(user_output_dir, 0o711)
|
||||
os.chdir(user_output_dir)
|
||||
# todo check permission
|
||||
user_output_file = os.path.join(user_output_dir, self._io_mode["output"])
|
||||
real_user_output_file = os.path.join(user_output_dir, "stdio.txt")
|
||||
shutil.copyfile(in_file, os.path.join(user_output_dir, self._io_mode["input"]))
|
||||
kwargs = {"input_path": in_file, "output_path": real_user_output_file, "error_path": real_user_output_file}
|
||||
else:
|
||||
real_user_output_file = user_output_file = os.path.join(self._submission_dir, test_case_file_id + ".out")
|
||||
kwargs = {"input_path": in_file, "output_path": real_user_output_file, "error_path": real_user_output_file}
|
||||
|
||||
command = self._run_config["command"].format(exe_path=self._exe_path, exe_dir=os.path.dirname(self._exe_path),
|
||||
max_memory=int(self._max_memory / 1024))
|
||||
command = shlex.split(command)
|
||||
env = ["PATH=" + os.environ.get("PATH", "")] + self._run_config.get("env", [])
|
||||
|
||||
seccomp_rule = self._run_config["seccomp_rule"]
|
||||
if isinstance(seccomp_rule, dict):
|
||||
seccomp_rule = seccomp_rule[self._io_mode["io_mode"]]
|
||||
|
||||
run_result = _judger.run(max_cpu_time=self._max_cpu_time,
|
||||
max_real_time=self._max_real_time,
|
||||
max_memory=self._max_memory,
|
||||
max_stack=128 * 1024 * 1024,
|
||||
max_output_size=max(test_case_info.get("output_size", 0) * 2, 1024 * 1024 * 16),
|
||||
max_process_number=_judger.UNLIMITED,
|
||||
exe_path=command[0],
|
||||
args=command[1::],
|
||||
env=env,
|
||||
log_path=JUDGER_RUN_LOG_PATH,
|
||||
seccomp_rule_name=seccomp_rule,
|
||||
uid=RUN_USER_UID,
|
||||
gid=RUN_GROUP_GID,
|
||||
memory_limit_check_only=self._run_config.get("memory_limit_check_only", 0),
|
||||
**kwargs)
|
||||
run_result["test_case"] = test_case_file_id
|
||||
|
||||
# if progress exited normally, then we should check output result
|
||||
run_result["output_md5"] = None
|
||||
run_result["output"] = None
|
||||
if run_result["result"] == _judger.RESULT_SUCCESS:
|
||||
if not os.path.exists(user_output_file):
|
||||
run_result["result"] = _judger.RESULT_WRONG_ANSWER
|
||||
else:
|
||||
if self._test_case_info.get("spj"):
|
||||
if not self._spj_config or not self._spj_version:
|
||||
raise JudgeClientError("spj_config or spj_version not set")
|
||||
|
||||
spj_result = self._spj(in_file_path=in_file, user_out_file_path=user_output_file)
|
||||
|
||||
if spj_result == SPJ_WA:
|
||||
run_result["result"] = _judger.RESULT_WRONG_ANSWER
|
||||
elif spj_result == SPJ_ERROR:
|
||||
run_result["result"] = _judger.RESULT_SYSTEM_ERROR
|
||||
run_result["error"] = _judger.ERROR_SPJ_ERROR
|
||||
else:
|
||||
run_result["output_md5"], is_ac = self._compare_output(test_case_file_id, user_output_file)
|
||||
# -1 == Wrong Answer
|
||||
if not is_ac:
|
||||
run_result["result"] = _judger.RESULT_WRONG_ANSWER
|
||||
|
||||
if self._output:
|
||||
try:
|
||||
with open(user_output_file, "rb") as f:
|
||||
run_result["output"] = f.read().decode("utf-8", errors="backslashreplace")
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
return run_result
|
||||
|
||||
def run(self):
|
||||
tmp_result = []
|
||||
result = []
|
||||
pool = Pool(processes=psutil.cpu_count())
|
||||
try:
|
||||
for test_case_file_id, _ in self._test_case_info["test_cases"].items():
|
||||
tmp_result.append(pool.apply_async(_run, (self, test_case_file_id)))
|
||||
except Exception as e:
|
||||
raise e
|
||||
finally:
|
||||
pool.close()
|
||||
pool.join()
|
||||
for item in tmp_result:
|
||||
# exception will be raised, when get() is called
|
||||
# http://stackoverflow.com/questions/22094852/how-to-catch-exceptions-in-workers-in-multiprocessing
|
||||
result.append(item.get())
|
||||
return result
|
||||
@@ -0,0 +1,209 @@
|
||||
import hashlib
|
||||
import json
|
||||
import os
|
||||
import shutil
|
||||
import uuid
|
||||
|
||||
from flask import Flask, request, Response
|
||||
|
||||
from compiler import Compiler
|
||||
from config import (JUDGER_WORKSPACE_BASE, SPJ_SRC_DIR, SPJ_EXE_DIR, COMPILER_USER_UID, SPJ_USER_UID,
|
||||
RUN_USER_UID, RUN_GROUP_GID, TEST_CASE_DIR)
|
||||
from exception import TokenVerificationFailed, CompileError, SPJCompileError, JudgeClientError
|
||||
from judge_client import JudgeClient
|
||||
from utils import server_info, logger, token, ProblemIOMode
|
||||
|
||||
app = Flask(__name__)
|
||||
DEBUG = os.environ.get("judger_debug") == "1"
|
||||
app.debug = DEBUG
|
||||
|
||||
|
||||
class InitSubmissionEnv(object):
|
||||
def __init__(self, judger_workspace, submission_id, init_test_case_dir=False):
|
||||
self.work_dir = os.path.join(judger_workspace, submission_id)
|
||||
self.init_test_case_dir = init_test_case_dir
|
||||
if init_test_case_dir:
|
||||
self.test_case_dir = os.path.join(self.work_dir, "submission_" + submission_id)
|
||||
else:
|
||||
self.test_case_dir = None
|
||||
|
||||
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)
|
||||
except Exception as e:
|
||||
logger.exception(e)
|
||||
raise JudgeClientError("failed to create runtime dir")
|
||||
return self.work_dir, self.test_case_dir
|
||||
|
||||
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")
|
||||
|
||||
|
||||
class JudgeServer:
|
||||
@classmethod
|
||||
def ping(cls):
|
||||
data = server_info()
|
||||
data["action"] = "pong"
|
||||
return data
|
||||
|
||||
@classmethod
|
||||
def judge(cls, language_config, src, max_cpu_time, max_memory, test_case_id=None, test_case=None,
|
||||
spj_version=None, spj_config=None, spj_compile_config=None, spj_src=None, output=False,
|
||||
io_mode=None):
|
||||
if not io_mode:
|
||||
io_mode = {"io_mode": ProblemIOMode.standard}
|
||||
|
||||
if not (test_case or test_case_id) or (test_case and test_case_id):
|
||||
raise JudgeClientError("invalid parameter")
|
||||
# init
|
||||
compile_config = language_config.get("compile")
|
||||
run_config = language_config["run"]
|
||||
submission_id = uuid.uuid4().hex
|
||||
|
||||
is_spj = spj_version and spj_config
|
||||
|
||||
if is_spj:
|
||||
spj_exe_path = os.path.join(SPJ_EXE_DIR, spj_config["exe_name"].format(spj_version=spj_version))
|
||||
# spj src has not been compiled
|
||||
if not os.path.isfile(spj_exe_path):
|
||||
logger.warning("%s does not exists, spj src will be recompiled")
|
||||
cls.compile_spj(spj_version=spj_version, src=spj_src,
|
||||
spj_compile_config=spj_compile_config)
|
||||
|
||||
init_test_case_dir = bool(test_case)
|
||||
with InitSubmissionEnv(JUDGER_WORKSPACE_BASE, submission_id=str(submission_id), init_test_case_dir=init_test_case_dir) as dirs:
|
||||
submission_dir, test_case_dir = dirs
|
||||
test_case_dir = test_case_dir or os.path.join(TEST_CASE_DIR, test_case_id)
|
||||
|
||||
if compile_config:
|
||||
src_path = os.path.join(submission_dir, compile_config["src_name"])
|
||||
|
||||
# write source code into file
|
||||
with open(src_path, "w", encoding="utf-8") as f:
|
||||
f.write(src)
|
||||
os.chown(src_path, COMPILER_USER_UID, 0)
|
||||
os.chmod(src_path, 0o400)
|
||||
|
||||
# compile source code, return exe file path
|
||||
exe_path = Compiler().compile(compile_config=compile_config,
|
||||
src_path=src_path,
|
||||
output_dir=submission_dir)
|
||||
try:
|
||||
# Java exe_path is SOME_PATH/Main, but the real path is SOME_PATH/Main.class
|
||||
# We ignore it temporarily
|
||||
os.chown(exe_path, RUN_USER_UID, 0)
|
||||
os.chmod(exe_path, 0o500)
|
||||
except Exception:
|
||||
pass
|
||||
else:
|
||||
exe_path = os.path.join(submission_dir, run_config["exe_name"])
|
||||
with open(exe_path, "w", encoding="utf-8") as f:
|
||||
f.write(src)
|
||||
|
||||
if init_test_case_dir:
|
||||
info = {"test_case_number": len(test_case), "spj": is_spj, "test_cases": {}}
|
||||
# write test case
|
||||
for index, item in enumerate(test_case):
|
||||
index += 1
|
||||
item_info = {}
|
||||
|
||||
input_name = str(index) + ".in"
|
||||
item_info["input_name"] = input_name
|
||||
input_data = item["input"].encode("utf-8")
|
||||
item_info["input_size"] = len(input_data)
|
||||
|
||||
with open(os.path.join(test_case_dir, input_name), "wb") as f:
|
||||
f.write(input_data)
|
||||
if not is_spj:
|
||||
output_name = str(index) + ".out"
|
||||
item_info["output_name"] = output_name
|
||||
output_data = item["output"].encode("utf-8")
|
||||
item_info["output_md5"] = hashlib.md5(output_data).hexdigest()
|
||||
item_info["output_size"] = len(output_data)
|
||||
item_info["stripped_output_md5"] = hashlib.md5(output_data.rstrip()).hexdigest()
|
||||
|
||||
with open(os.path.join(test_case_dir, output_name), "wb") as f:
|
||||
f.write(output_data)
|
||||
info["test_cases"][index] = item_info
|
||||
with open(os.path.join(test_case_dir, "info"), "w") as f:
|
||||
json.dump(info, f)
|
||||
|
||||
judge_client = JudgeClient(run_config=language_config["run"],
|
||||
exe_path=exe_path,
|
||||
max_cpu_time=max_cpu_time,
|
||||
max_memory=max_memory,
|
||||
test_case_dir=test_case_dir,
|
||||
submission_dir=submission_dir,
|
||||
spj_version=spj_version,
|
||||
spj_config=spj_config,
|
||||
output=output,
|
||||
io_mode=io_mode)
|
||||
run_result = judge_client.run()
|
||||
|
||||
return run_result
|
||||
|
||||
@classmethod
|
||||
def compile_spj(cls, spj_version, src, spj_compile_config):
|
||||
spj_compile_config["src_name"] = spj_compile_config["src_name"].format(spj_version=spj_version)
|
||||
spj_compile_config["exe_name"] = spj_compile_config["exe_name"].format(spj_version=spj_version)
|
||||
|
||||
spj_src_path = os.path.join(SPJ_SRC_DIR, spj_compile_config["src_name"])
|
||||
|
||||
# if spj source code not found, then write it into file
|
||||
if not os.path.exists(spj_src_path):
|
||||
with open(spj_src_path, "w", encoding="utf-8") as f:
|
||||
f.write(src)
|
||||
os.chown(spj_src_path, COMPILER_USER_UID, 0)
|
||||
os.chmod(spj_src_path, 0o400)
|
||||
|
||||
try:
|
||||
exe_path = Compiler().compile(compile_config=spj_compile_config,
|
||||
src_path=spj_src_path,
|
||||
output_dir=SPJ_EXE_DIR)
|
||||
os.chown(exe_path, SPJ_USER_UID, 0)
|
||||
os.chmod(exe_path, 0o500)
|
||||
# turn common CompileError into SPJCompileError
|
||||
except CompileError as e:
|
||||
raise SPJCompileError(e.message)
|
||||
return "success"
|
||||
|
||||
|
||||
@app.route('/', defaults={'path': ''})
|
||||
@app.route('/<path:path>', methods=["POST"])
|
||||
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 = {}
|
||||
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')
|
||||
|
||||
|
||||
if DEBUG:
|
||||
logger.info("DEBUG=ON")
|
||||
|
||||
# gunicorn -w 4 -b 0.0.0.0:8080 server:app
|
||||
if __name__ == "__main__":
|
||||
app.run(debug=DEBUG)
|
||||
@@ -0,0 +1,46 @@
|
||||
import json
|
||||
import os
|
||||
|
||||
import requests
|
||||
|
||||
from exception import JudgeServiceError
|
||||
from utils import server_info, logger, token
|
||||
|
||||
|
||||
class JudgeService(object):
|
||||
def __init__(self):
|
||||
self.service_url = os.environ["SERVICE_URL"]
|
||||
self.backend_url = os.environ["BACKEND_URL"]
|
||||
|
||||
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 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)
|
||||
@@ -0,0 +1,8 @@
|
||||
#include <stdio.h>
|
||||
|
||||
void unbuffer() __attribute__((constructor));
|
||||
|
||||
void unbuffer()
|
||||
{
|
||||
setvbuf(stdout, NULL, _IONBF, 0);
|
||||
}
|
||||
@@ -0,0 +1,42 @@
|
||||
import _judger
|
||||
import hashlib
|
||||
import logging
|
||||
import os
|
||||
import socket
|
||||
|
||||
import psutil
|
||||
|
||||
from config import SERVER_LOG_PATH
|
||||
from exception import JudgeClientError
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
handler = logging.FileHandler(SERVER_LOG_PATH)
|
||||
formatter = logging.Formatter('%(asctime)s %(levelname)s %(message)s')
|
||||
handler.setFormatter(formatter)
|
||||
logger.addHandler(handler)
|
||||
logger.setLevel(logging.WARNING)
|
||||
|
||||
|
||||
def server_info():
|
||||
ver = _judger.VERSION
|
||||
return {"hostname": socket.gethostname(),
|
||||
"cpu": psutil.cpu_percent(),
|
||||
"cpu_core": psutil.cpu_count(),
|
||||
"memory": psutil.virtual_memory().percent,
|
||||
"judger_version": ".".join([str((ver >> 16) & 0xff), str((ver >> 8) & 0xff), str(ver & 0xff)])}
|
||||
|
||||
|
||||
def get_token():
|
||||
token = os.environ.get("TOKEN")
|
||||
if token:
|
||||
return token
|
||||
else:
|
||||
raise JudgeClientError("env 'TOKEN' not found")
|
||||
|
||||
|
||||
class ProblemIOMode:
|
||||
standard = "Standard IO"
|
||||
file = "File IO"
|
||||
|
||||
|
||||
token = hashlib.sha256(get_token().encode("utf-8")).hexdigest()
|
||||
Reference in new issue
Block a user