inital commit 1
This commit is contained in:
commit
5c7b9edf97
42 files changed
+2371
No files matched your search
@@ -0,0 +1,54 @@
|
||||
name: Release build
|
||||
|
||||
on:
|
||||
push:
|
||||
tags:
|
||||
- v**
|
||||
workflow_dispatch:
|
||||
|
||||
jobs:
|
||||
build:
|
||||
runs-on: ubuntu-latest
|
||||
environment: release
|
||||
permissions:
|
||||
contents: read
|
||||
packages: write
|
||||
steps:
|
||||
- name: Docker metadata
|
||||
id: metadata
|
||||
uses: docker/metadata-action@v5
|
||||
with:
|
||||
images: |
|
||||
registry.cn-hongkong.aliyuncs.com/oj-image/judge
|
||||
tags: |
|
||||
type=semver,pattern={{version}}
|
||||
type=semver,pattern={{major}}.{{minor}}
|
||||
type=semver,pattern={{major}},enable=${{ !startsWith(github.ref, 'refs/tags/v0.') }}
|
||||
|
||||
- name: Set up QEMU
|
||||
uses: docker/setup-qemu-action@v3
|
||||
|
||||
- name: Set up Docker Buildx
|
||||
uses: docker/setup-buildx-action@v3
|
||||
|
||||
- name: Login to GitHub Container Registry
|
||||
uses: docker/login-action@v3
|
||||
with:
|
||||
registry: ghcr.io
|
||||
username: ${{ github.actor }}
|
||||
password: ${{ secrets.GITHUB_TOKEN }}
|
||||
|
||||
- name: Login to Aliyun Container Registry
|
||||
uses: docker/login-action@v3
|
||||
with:
|
||||
registry: registry.cn-hongkong.aliyuncs.com
|
||||
username: ${{ secrets.ALIYUN_ACR_USERNAME }}
|
||||
password: ${{ secrets.ALIYUN_ACR_PASSWORD }}
|
||||
|
||||
- name: Build and push
|
||||
uses: docker/build-push-action@v5
|
||||
with:
|
||||
push: true
|
||||
platforms: linux/amd64,linux/arm64
|
||||
tags: ${{ steps.metadata.outputs.tags }}
|
||||
annotations: ${{ steps.metadata.outputs.annotations }}
|
||||
+74
@@ -0,0 +1,74 @@
|
||||
# Byte-compiled / optimized / DLL files
|
||||
__pycache__/
|
||||
*.py[cod]
|
||||
# C extensions
|
||||
*.so
|
||||
# Distribution / packaging
|
||||
.Python
|
||||
env/
|
||||
bin/
|
||||
develop-eggs/
|
||||
dist/
|
||||
eggs/
|
||||
lib64/
|
||||
parts/
|
||||
sdist/
|
||||
var/
|
||||
*.egg-info/
|
||||
.installed.cfg
|
||||
*.egg
|
||||
# Installer logs
|
||||
pip-log.txt
|
||||
pip-delete-this-directory.txt
|
||||
# Unit test / coverage reports
|
||||
htmlcov/
|
||||
.tox/
|
||||
.coverage
|
||||
.cache
|
||||
nosetests.xml
|
||||
coverage.xml
|
||||
# Translations
|
||||
*.mo
|
||||
# Mr Developer
|
||||
.mr.developer.cfg
|
||||
.project
|
||||
.pydevproject
|
||||
# Rope
|
||||
.ropeproject
|
||||
.idea/
|
||||
.vscode/
|
||||
# Django stuff:
|
||||
*.log
|
||||
*.pot
|
||||
# Sphinx documentation
|
||||
docs/_build/
|
||||
# Back up file
|
||||
*~
|
||||
#db file
|
||||
db.db
|
||||
#vim cache
|
||||
*swp
|
||||
*swo
|
||||
#redis dump
|
||||
*.rdb
|
||||
#*.out
|
||||
*.sqlite3
|
||||
.DS_Store
|
||||
log/
|
||||
static/release/css
|
||||
static/release/js
|
||||
static/release/img
|
||||
static/src/upload_image/*
|
||||
build.txt
|
||||
tmp/
|
||||
release/
|
||||
upload/
|
||||
custom_settings.py
|
||||
docker-compose.yml
|
||||
*.zip
|
||||
rsyncd.passwd
|
||||
|
||||
node_modules/
|
||||
|
||||
token.txt
|
||||
run/
|
||||
@@ -0,0 +1,3 @@
|
||||
[submodule "Judger"]
|
||||
path = Judger
|
||||
url = https://git.mxdyeah.com/OnlineJudge/Judger.git
|
||||
+14
@@ -0,0 +1,14 @@
|
||||
sudo: required
|
||||
language: python
|
||||
services:
|
||||
- docker
|
||||
before_install:
|
||||
- sudo mkdir -p /data/log
|
||||
- pip install requests
|
||||
script:
|
||||
- docker pull qduoj/judge-server
|
||||
- cp docker-compose.example.yml docker-compose.yml
|
||||
- docker-compose up -d
|
||||
- docker ps -a
|
||||
- sleep 5
|
||||
- python tests/tests.py
|
||||
+126
@@ -0,0 +1,126 @@
|
||||
FROM debian:trixie-slim AS builder
|
||||
ARG TARGETARCH
|
||||
ARG TARGETVARIANT
|
||||
|
||||
ENV DEBIAN_FRONTEND=noninteractive
|
||||
WORKDIR /app
|
||||
|
||||
RUN --mount=type=cache,target=/var/cache/apt,id=apt-cahce-1-$TARGETARCH$TARGETVARIANT-builder,sharing=locked \
|
||||
--mount=type=cache,target=/var/lib/apt,id=apt-cahce-2-$TARGETARCH$TARGETVARIANT-builder,sharing=locked \
|
||||
<<EOS
|
||||
set -ex
|
||||
rm -f /etc/apt/apt.conf.d/docker-clean
|
||||
echo 'Binary::apt::APT::Keep-Downloaded-Packages "1";' > /etc/apt/apt.conf.d/keep-cache
|
||||
echo 'APT::Install-Recommends "0";' > /etc/apt/apt.conf.d/no-recommends
|
||||
echo 'APT::AutoRemove::RecommendsImportant "0";' >> /etc/apt/apt.conf.d/no-recommends
|
||||
apt-get update
|
||||
apt-get install -y libtool make cmake libseccomp-dev gcc python3 python3-venv
|
||||
EOS
|
||||
|
||||
COPY Judger/ /app/
|
||||
RUN <<EOS
|
||||
set -ex
|
||||
mkdir /app/build
|
||||
cmake -S . -B build
|
||||
cmake --build build --parallel $(nproc)
|
||||
EOS
|
||||
|
||||
RUN <<EOS
|
||||
set -ex
|
||||
cd bindings/Python
|
||||
python3 -m venv .venv
|
||||
.venv/bin/pip3 install build
|
||||
.venv/bin/python3 -m build -w
|
||||
EOS
|
||||
|
||||
FROM debian:trixie-slim
|
||||
ARG TARGETARCH
|
||||
ARG TARGETVARIANT
|
||||
|
||||
ENV DEBIAN_FRONTEND=noninteractive
|
||||
WORKDIR /app
|
||||
|
||||
RUN --mount=type=cache,target=/var/cache/apt,id=apt-cahce-1-$TARGETARCH$TARGETVARIANT-final,sharing=locked \
|
||||
--mount=type=cache,target=/var/lib/apt,id=apt-cahce-2-$TARGETARCH$TARGETVARIANT-final,sharing=locked \
|
||||
<<EOS
|
||||
set -ex
|
||||
rm -f /etc/apt/apt.conf.d/docker-clean
|
||||
echo 'Binary::apt::APT::Keep-Downloaded-Packages "1";' > /etc/apt/apt.conf.d/keep-cache
|
||||
echo 'APT::Install-Recommends "0";' > /etc/apt/apt.conf.d/no-recommends
|
||||
echo 'APT::AutoRemove::RecommendsImportant "0";' >> /etc/apt/apt.conf.d/no-recommends
|
||||
needed="python3.12-minimal \
|
||||
python3.12-venv \
|
||||
libpython3.12-stdlib \
|
||||
libpython3.12-dev \
|
||||
golang-1.22-go \
|
||||
temurin-21-jdk \
|
||||
gcc-13 \
|
||||
g++-13 \
|
||||
nodejs \
|
||||
strace"
|
||||
savedAptMark="$(apt-mark showmanual) $needed"
|
||||
apt-get update
|
||||
apt-get install -y ca-certificates curl gnupg
|
||||
curl -fsSL https://packages.adoptium.net/artifactory/api/gpg/key/public | gpg --dearmor -o /etc/apt/keyrings/adoptium.gpg
|
||||
cat > /etc/apt/sources.list.d/adoptium.sources <<EOF
|
||||
Types: deb
|
||||
URIs: https://packages.adoptium.net/artifactory/deb
|
||||
Suites: bookworm
|
||||
Components: main
|
||||
Signed-By: /etc/apt/keyrings/adoptium.gpg
|
||||
EOF
|
||||
curl -fsSL https://deb.nodesource.com/gpgkey/nodesource-repo.gpg.key | gpg --dearmor -o /etc/apt/keyrings/nodesource.gpg
|
||||
cat > /etc/apt/sources.list.d/nodesource.sources <<EOF
|
||||
Types: deb
|
||||
URIs: https://deb.nodesource.com/node_20.x
|
||||
Suites: nodistro
|
||||
Components: main
|
||||
Signed-By:/etc/apt/keyrings/nodesource.gpg
|
||||
EOF
|
||||
apt-get update
|
||||
apt-get install -y $needed
|
||||
update-alternatives --install /usr/bin/gcc gcc /usr/bin/gcc-13 13
|
||||
update-alternatives --install /usr/bin/g++ g++ /usr/bin/g++-13 13
|
||||
update-alternatives --install /usr/bin/python3 python3 /usr/bin/python3.12 12
|
||||
update-alternatives --install /usr/bin/go go /usr/lib/go-1.22/bin/go 22
|
||||
rm -rf /usr/lib/jvm/temurin-21-jdk-*/jmods
|
||||
rm -rf /usr/lib/jvm/temurin-21-jdk-*/lib/src.zip
|
||||
apt-mark auto '.*' > /dev/null
|
||||
apt-mark manual $savedAptMark
|
||||
apt-get purge -y --auto-remove
|
||||
EOS
|
||||
|
||||
COPY --from=builder --chmod=755 --link /app/output/libjudger.so /usr/lib/judger/libjudger.so
|
||||
COPY --from=builder /app/bindings/Python/dist/ /app/
|
||||
RUN --mount=type=cache,target=/root/.cache/pip,id=pip-cahce-$TARGETARCH$TARGETVARIANT-final \
|
||||
<<EOS
|
||||
set -ex
|
||||
python3 -m venv .venv
|
||||
CC=gcc .venv/bin/pip3 install --compile --no-cache-dir flask gunicorn idna psutil requests
|
||||
.venv/bin/pip3 install *.whl
|
||||
EOS
|
||||
|
||||
COPY server/ /app/
|
||||
RUN <<EOS
|
||||
set -ex
|
||||
chmod -R u=rwX,go=rX /app/
|
||||
chmod +x /app/entrypoint.sh
|
||||
gcc -shared -fPIC -o unbuffer.so unbuffer.c
|
||||
useradd -u 901 -r -s /sbin/nologin -M compiler
|
||||
useradd -u 902 -r -s /sbin/nologin -M code
|
||||
useradd -u 903 -r -s /sbin/nologin -M -G code spj
|
||||
mkdir -p /usr/lib/judger
|
||||
EOS
|
||||
|
||||
RUN <<EOS
|
||||
set -ex
|
||||
gcc --version
|
||||
g++ --version
|
||||
python3 --version
|
||||
java -version
|
||||
node --version
|
||||
EOS
|
||||
|
||||
HEALTHCHECK --interval=5s CMD [ "/app/.venv/bin/python3", "/app/service.py" ]
|
||||
EXPOSE 8080
|
||||
ENTRYPOINT [ "/app/entrypoint.sh" ]
|
||||
@@ -0,0 +1,170 @@
|
||||
<?php
|
||||
|
||||
class JudgeClient
|
||||
{
|
||||
|
||||
private $ch = null;
|
||||
private $serverBaseUrl = '';
|
||||
private $token;
|
||||
private static $languageConfigs = [];
|
||||
|
||||
public function __construct($token, $serverBaseUrl)
|
||||
{
|
||||
$this->serverBaseUrl = rtrim($serverBaseUrl, '/');
|
||||
$this->token = hash('sha256', $token);
|
||||
}
|
||||
|
||||
public function ping()
|
||||
{
|
||||
return $this->post($this->serverBaseUrl . '/ping');
|
||||
}
|
||||
|
||||
/**
|
||||
* 调用判题 api
|
||||
* @param string $src 提交的源代码
|
||||
* @param string $language 使用的编程语言
|
||||
* @param string $testCaseId test_case_id
|
||||
* @param array $config 额外配置
|
||||
* @return array
|
||||
* @throws Exception
|
||||
*/
|
||||
public function judge($src, $language, $testCaseId, $config = [])
|
||||
{
|
||||
$languageConfig = static::getLanguageConfigByLanguage($language);
|
||||
|
||||
if (is_null($languageConfig)) {
|
||||
throw new Exception("don't support \"$language\" language!");
|
||||
}
|
||||
|
||||
$default = [
|
||||
'language_config' => $languageConfig,
|
||||
'src' => $src,
|
||||
'test_case_id' => $testCaseId,
|
||||
'max_cpu_time' => $languageConfig['compile']['max_cpu_time'],
|
||||
'max_memory' => $languageConfig['compile']['max_memory'],
|
||||
'spj_version' => null,
|
||||
'spj_config' => null,
|
||||
'spj_compile_config' => null,
|
||||
'spj_src' => null,
|
||||
'output' => false
|
||||
];
|
||||
return $this->post($this->serverBaseUrl . '/judge', array_merge($default, $config));
|
||||
}
|
||||
|
||||
public function compileSpj($src, $spjVersion, $spjCompileConfig)
|
||||
{
|
||||
$data = [
|
||||
'src' => $src,
|
||||
'spj_version' => $spjVersion,
|
||||
'spj_compile_config' => $spjCompileConfig,
|
||||
];
|
||||
return $this->post($this->serverBaseUrl . '/compile_spj', $data);
|
||||
}
|
||||
|
||||
public static function loadLanguageConfigs()
|
||||
{
|
||||
if (empty(static::$languageConfigs))
|
||||
static::$languageConfigs = require('languages.php');
|
||||
}
|
||||
|
||||
public static function getLanguageConfigByLanguage($language)
|
||||
{
|
||||
return static::getLanguageConfigByKey($language . '_lang_config');
|
||||
}
|
||||
|
||||
public static function getLanguageConfigByKey($key)
|
||||
{
|
||||
return isset(static::$languageConfigs[$key]) ? static::$languageConfigs[$key] : null;
|
||||
}
|
||||
|
||||
private function needCreateCurl()
|
||||
{
|
||||
return is_null($this->ch);
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取 curl 资源
|
||||
* @return null|resource
|
||||
*/
|
||||
private function getCurl()
|
||||
{
|
||||
if ($this->needCreateCurl()) {
|
||||
$this->ch = curl_init();
|
||||
$defaults = [
|
||||
CURLOPT_RETURNTRANSFER => true,
|
||||
CURLOPT_HEADER => false,
|
||||
// set HTTP request header
|
||||
CURLOPT_HTTPHEADER => [
|
||||
'Content-type: application/json',
|
||||
'X-Judge-Server-Token: ' . $this->token
|
||||
],
|
||||
];
|
||||
curl_setopt_array($this->ch, $defaults);
|
||||
}
|
||||
|
||||
return $this->ch;
|
||||
}
|
||||
|
||||
/**
|
||||
* 发送 GET 请求
|
||||
* @param string $url 请求的url
|
||||
* @param array $data 请求参数
|
||||
* @return array
|
||||
*/
|
||||
private function get($url, $data = [])
|
||||
{
|
||||
return $this->request('GET', $url, $data);
|
||||
}
|
||||
|
||||
/**
|
||||
* 发送 POST 请求
|
||||
* @param string $url 请求的url
|
||||
* @param array $data 请求参数
|
||||
* @return array
|
||||
*/
|
||||
private function post($url, $data = [])
|
||||
{
|
||||
return $this->request('POST', $url, $data);
|
||||
}
|
||||
|
||||
/**
|
||||
* 发送 http 请求
|
||||
* @param string $method http method
|
||||
* @param string $url 请求的url
|
||||
* @param array $data 请求参数
|
||||
* @return array
|
||||
*/
|
||||
private function request($method, $url, $data = [])
|
||||
{
|
||||
$ch = $this->getCurl();
|
||||
$method = strtoupper($method);
|
||||
if (in_array($method, ['GET', 'HEAD', 'DELETE', 'POST', 'PUT', 'PATCH']))
|
||||
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $method);
|
||||
|
||||
curl_setopt($ch, CURLOPT_URL, $url);
|
||||
curl_setopt($ch, CURLOPT_POSTFIELDS, empty($data) ? '{}' : json_encode($data));
|
||||
if (!$result = curl_exec($this->ch)) {
|
||||
trigger_error(curl_error($this->ch));
|
||||
}
|
||||
return json_decode($result, true);
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* 关闭 curl 资源
|
||||
*/
|
||||
public function close()
|
||||
{
|
||||
if (is_resource($this->ch)) {
|
||||
curl_close($this->ch);
|
||||
}
|
||||
$this->ch = null;
|
||||
}
|
||||
|
||||
public function __destruct()
|
||||
{
|
||||
$this->close();
|
||||
}
|
||||
}
|
||||
|
||||
JudgeClient::loadLanguageConfigs();
|
||||
@@ -0,0 +1,94 @@
|
||||
<?php
|
||||
|
||||
require('JudgeClient.php');
|
||||
|
||||
$token = 'YOUR_TOKEN_HERE';
|
||||
|
||||
$cSrc = <<<'CODE'
|
||||
#include <stdio.h>
|
||||
int main(){
|
||||
int a, b;
|
||||
scanf("%d%d", &a, &b);
|
||||
printf("%d\n", a+b);
|
||||
return 0;
|
||||
}
|
||||
CODE;
|
||||
|
||||
$cSpjSrc = <<<'CODE'
|
||||
#include <stdio.h>
|
||||
int main(){
|
||||
return 1;
|
||||
}
|
||||
CODE;
|
||||
|
||||
$cppSrc = <<<'CODE'
|
||||
#include <iostream>
|
||||
|
||||
using namespace std;
|
||||
|
||||
int main()
|
||||
{
|
||||
int a,b;
|
||||
cin >> a >> b;
|
||||
cout << a+b << endl;
|
||||
return 0;
|
||||
}
|
||||
CODE;
|
||||
|
||||
$javaSrc = <<<'CODE'
|
||||
import java.util.Scanner;
|
||||
public class Main{
|
||||
public static void main(String[] args){
|
||||
Scanner in=new Scanner(System.in);
|
||||
int a=in.nextInt();
|
||||
int b=in.nextInt();
|
||||
System.out.println(a + b);
|
||||
}
|
||||
}
|
||||
CODE;
|
||||
|
||||
$py2src = <<<'CODE'
|
||||
s = raw_input()
|
||||
s1 = s.split(" ")
|
||||
print int(s1[0]) + int(s1[1])
|
||||
CODE;
|
||||
|
||||
$py3src = <<<'CODE'
|
||||
s = input()
|
||||
s1 = s.split(" ")
|
||||
print(int(s1[0]) + int(s1[1]))
|
||||
CODE;
|
||||
|
||||
|
||||
$judgeClient = new JudgeClient($token, 'http://127.0.0.1:12358');
|
||||
|
||||
echo "ping:\n";
|
||||
print_r($judgeClient->ping());
|
||||
|
||||
echo "\n\ncompile_spj:\n";
|
||||
print_r($judgeClient->compileSpj($cSpjSrc, '2', JudgeClient::getLanguageConfigByKey('c_lang_spj_compile')));
|
||||
|
||||
echo "\n\nc_judge:\n";
|
||||
print_r($judgeClient->judge($cSrc, 'c', 'normal', [
|
||||
'output' => true
|
||||
]));
|
||||
|
||||
echo "\n\nc_spj_judge:\n";
|
||||
print_r($judgeClient->judge($cSrc, 'c', 'spj', [
|
||||
'spj_version' => '3',
|
||||
'spj_config' => JudgeClient::getLanguageConfigByKey('c_lang_spj_config'),
|
||||
'spj_compile_config' => JudgeClient::getLanguageConfigByKey('c_lang_spj_compile'),
|
||||
'spj_src' => $cSpjSrc,
|
||||
]));
|
||||
|
||||
echo "\n\ncpp_judge:\n";
|
||||
print_r($judgeClient->judge($cppSrc, 'cpp', 'normal'));
|
||||
|
||||
echo "\n\njava_judge:\n";
|
||||
print_r($judgeClient->judge($javaSrc, 'java', 'normal'));
|
||||
|
||||
echo "\n\npy2_judge:\n";
|
||||
print_r($judgeClient->judge($py2src, 'py2', 'normal'));
|
||||
|
||||
echo "\n\npy3_judge:\n";
|
||||
print_r($judgeClient->judge($py3src, 'py3', 'normal'));
|
||||
@@ -0,0 +1,97 @@
|
||||
<?php
|
||||
|
||||
$default_env = ["LANG=en_US.UTF-8", "LANGUAGE=en_US:en", "LC_ALL=en_US.UTF-8"];
|
||||
|
||||
return [
|
||||
'c_lang_config' => [
|
||||
'compile' => [
|
||||
'src_name' => 'main.c',
|
||||
'exe_name' => 'main',
|
||||
'max_cpu_time' => 3000,
|
||||
'max_real_time' => 5000,
|
||||
'max_memory' => 128 * 1024 * 1024,
|
||||
'compile_command' => '/usr/bin/gcc -DONLINE_JUDGE -O2 -w -fmax-errors=3 -std=c99 -static {src_path} -lm -o {exe_path}',
|
||||
],
|
||||
'run' => [
|
||||
'command' => '{exe_path}',
|
||||
'seccomp_rule' => 'c_cpp',
|
||||
'env' => $default_env
|
||||
]
|
||||
],
|
||||
'c_lang_spj_compile' => [
|
||||
'src_name' => 'spj-{spj_version}.c',
|
||||
'exe_name' => 'spj-{spj_version}',
|
||||
'max_cpu_time' => 3000,
|
||||
'max_real_time' => 5000,
|
||||
'max_memory' => 1024 * 1024 * 1024,
|
||||
'compile_command' => '/usr/bin/gcc -DONLINE_JUDGE -O2 -w -fmax-errors=3 -std=c99 {src_path} -lm -o {exe_path}'
|
||||
],
|
||||
'c_lang_spj_config' => [
|
||||
'exe_name' => 'spj-{spj_version}',
|
||||
'command' => '{exe_path} {in_file_path} {user_out_file_path}',
|
||||
'seccomp_rule' => 'c_cpp',
|
||||
'env' => $default_env
|
||||
],
|
||||
'cpp_lang_config' => [
|
||||
'name' => 'cpp',
|
||||
'compile' => [
|
||||
'src_name' => 'main.cpp',
|
||||
'exe_name' => 'main',
|
||||
'max_cpu_time' => 3000,
|
||||
'max_real_time' => 5000,
|
||||
'max_memory' => 128 * 1024 * 1024,
|
||||
'compile_command' => '/usr/bin/g++ -DONLINE_JUDGE -O2 -w -fmax-errors=3 -std=c++11 {src_path} -lm -o {exe_path}',
|
||||
],
|
||||
'run' => [
|
||||
'command' => '{exe_path}',
|
||||
'seccomp_rule' => 'c_cpp',
|
||||
]
|
||||
],
|
||||
'java_lang_config' => [
|
||||
'name' => 'java',
|
||||
'compile' => [
|
||||
'src_name' => 'Main.java',
|
||||
'exe_name' => 'Main',
|
||||
'max_cpu_time' => 3000,
|
||||
'max_real_time' => 5000,
|
||||
'max_memory' => -1,
|
||||
'compile_command' => '/usr/bin/javac {src_path} -d {exe_dir} -encoding UTF8'
|
||||
],
|
||||
'run' => [
|
||||
'command' => '/usr/bin/java -cp {exe_dir} -Xss1M -XX:MaxPermSize=16M -XX:PermSize=8M -Xms16M -Xmx{max_memory}k -Djava.security.manager -Djava.security.policy==/etc/java_policy -Djava.awt.headless=true Main',
|
||||
'seccomp_rule' => null,
|
||||
'env' => $default_env,
|
||||
'memory_limit_check_only' => 1
|
||||
]
|
||||
],
|
||||
'py2_lang_config' => [
|
||||
'compile' => [
|
||||
'src_name' => 'solution.py',
|
||||
'exe_name' => 'solution.pyc',
|
||||
'max_cpu_time' => 3000,
|
||||
'max_real_time' => 5000,
|
||||
'max_memory' => 128 * 1024 * 1024,
|
||||
'compile_command' => '/usr/bin/python -m py_compile {src_path}',
|
||||
],
|
||||
'run' => [
|
||||
'command' => '/usr/bin/python {exe_path}',
|
||||
'seccomp_rule' => null,
|
||||
'env' => $default_env
|
||||
]
|
||||
],
|
||||
'py3_lang_config' => [
|
||||
'compile' => [
|
||||
'src_name' => 'solution.py',
|
||||
'exe_name' => '__pycache__/solution.cpython-35.pyc',
|
||||
'max_cpu_time' => 3000,
|
||||
'max_real_time' => 5000,
|
||||
'max_memory' => 128 * 1024 * 1024,
|
||||
'compile_command' => '/usr/bin/python3 -m py_compile {src_path}',
|
||||
],
|
||||
'run' => [
|
||||
'command' => '/usr/bin/python3 {exe_path}',
|
||||
'seccomp_rule' => 'general',
|
||||
'env' => array_merge(['MALLOC_ARENA_MAX=1'], $default_env)
|
||||
]
|
||||
]
|
||||
];
|
||||
Whitespace-only changes.
@@ -0,0 +1,191 @@
|
||||
import hashlib
|
||||
import json
|
||||
|
||||
import requests
|
||||
|
||||
from .languages import c_lang_config, cpp_lang_config, java_lang_config, c_lang_spj_config, c_lang_spj_compile, py2_lang_config, py3_lang_config, go_lang_config, php_lang_config, js_lang_config
|
||||
|
||||
|
||||
class JudgeServerClientError(Exception):
|
||||
pass
|
||||
|
||||
|
||||
class JudgeServerClient(object):
|
||||
def __init__(self, token, server_base_url):
|
||||
self.token = hashlib.sha256(token.encode("utf-8")).hexdigest()
|
||||
self.server_base_url = server_base_url.rstrip("/")
|
||||
|
||||
def _request(self, url, data=None):
|
||||
kwargs = {"headers": {"X-Judge-Server-Token": self.token,
|
||||
"Content-Type": "application/json"}}
|
||||
if data:
|
||||
kwargs["data"] = json.dumps(data)
|
||||
try:
|
||||
return requests.post(url, **kwargs).json()
|
||||
except Exception as e:
|
||||
raise JudgeServerClientError(str(e))
|
||||
|
||||
def ping(self):
|
||||
return self._request(self.server_base_url + "/ping")
|
||||
|
||||
def judge(self, src, language_config, 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):
|
||||
if not (test_case or test_case_id) or (test_case and test_case_id):
|
||||
raise ValueError("invalid parameter")
|
||||
|
||||
data = {"language_config": language_config,
|
||||
"src": src,
|
||||
"max_cpu_time": max_cpu_time,
|
||||
"max_memory": max_memory,
|
||||
"test_case_id": test_case_id,
|
||||
"test_case": test_case,
|
||||
"spj_version": spj_version,
|
||||
"spj_config": spj_config,
|
||||
"spj_compile_config": spj_compile_config,
|
||||
"spj_src": spj_src,
|
||||
"output": output}
|
||||
return self._request(self.server_base_url + "/judge", data=data)
|
||||
|
||||
def compile_spj(self, src, spj_version, spj_compile_config):
|
||||
data = {"src": src, "spj_version": spj_version,
|
||||
"spj_compile_config": spj_compile_config}
|
||||
return self._request(self.server_base_url + "/compile_spj", data=data)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
token = "YOUR_TOKEN_HERE"
|
||||
|
||||
c_src = r"""
|
||||
#include <stdio.h>
|
||||
int main(){
|
||||
int a, b;
|
||||
scanf("%d%d", &a, &b);
|
||||
printf("%d\n", a+b);
|
||||
return 0;
|
||||
}
|
||||
"""
|
||||
|
||||
c_spj_src = r"""
|
||||
#include <stdio.h>
|
||||
int main(){
|
||||
return 1;
|
||||
}
|
||||
"""
|
||||
|
||||
cpp_src = r"""
|
||||
#include <iostream>
|
||||
|
||||
using namespace std;
|
||||
|
||||
int main()
|
||||
{
|
||||
int a,b;
|
||||
cin >> a >> b;
|
||||
cout << a+b << endl;
|
||||
return 0;
|
||||
}
|
||||
"""
|
||||
|
||||
java_src = r"""
|
||||
import java.util.Scanner;
|
||||
public class Main{
|
||||
public static void main(String[] args){
|
||||
Scanner in=new Scanner(System.in);
|
||||
int a=in.nextInt();
|
||||
int b=in.nextInt();
|
||||
System.out.println(a + b);
|
||||
}
|
||||
}
|
||||
"""
|
||||
|
||||
py2_src = """s = raw_input()
|
||||
s1 = s.split(" ")
|
||||
print int(s1[0]) + int(s1[1])"""
|
||||
|
||||
py3_src = """s = input()
|
||||
s1 = s.split(" ")
|
||||
print(int(s1[0]) + int(s1[1]))"""
|
||||
|
||||
go_src = """package main
|
||||
import "fmt"
|
||||
|
||||
func main() {
|
||||
a := 0
|
||||
b := 0
|
||||
fmt.Scanf("%d %d", &a, &b)
|
||||
fmt.Printf("%d", a + b)
|
||||
}"""
|
||||
|
||||
php_src = """<?php
|
||||
fscanf(STDIN, "%d %d", $a, $b);
|
||||
print($a + $b);"""
|
||||
|
||||
js_src = """const readline = require('readline');
|
||||
const rl = readline.createInterface({ input: process.stdin });
|
||||
rl.on('line', (input) => {
|
||||
if (input === '') {
|
||||
return rl.close();
|
||||
}
|
||||
const [a, b] = input.split(' ').map(Number)
|
||||
console.log(a + b);
|
||||
});"""
|
||||
|
||||
client = JudgeServerClient(token=token, server_base_url="http://127.0.0.1:12358")
|
||||
print("ping")
|
||||
print(client.ping(), "\n\n")
|
||||
|
||||
print("compile_spj")
|
||||
print(client.compile_spj(src=c_spj_src, spj_version="2", spj_compile_config=c_lang_spj_compile
|
||||
), "\n\n")
|
||||
|
||||
print("c_judge")
|
||||
print(client.judge(src=c_src, language_config=c_lang_config,
|
||||
max_cpu_time=1000, max_memory=1024 * 1024 * 128,
|
||||
test_case_id="normal", output=True), "\n\n")
|
||||
|
||||
print("cpp_judge")
|
||||
print(client.judge(src=cpp_src, language_config=cpp_lang_config,
|
||||
max_cpu_time=1000, max_memory=1024 * 1024 * 128,
|
||||
test_case_id="normal"), "\n\n")
|
||||
|
||||
print("java_judge")
|
||||
print(client.judge(src=java_src, language_config=java_lang_config,
|
||||
max_cpu_time=1000, max_memory=256 * 1024 * 1024,
|
||||
test_case_id="normal"), "\n\n")
|
||||
|
||||
print("c_spj_judge")
|
||||
print(client.judge(src=c_src, language_config=c_lang_config,
|
||||
max_cpu_time=1000, max_memory=1024 * 1024 * 128,
|
||||
test_case_id="spj",
|
||||
spj_version="3", spj_config=c_lang_spj_config,
|
||||
spj_compile_config=c_lang_spj_compile, spj_src=c_spj_src), "\n\n")
|
||||
|
||||
print("py2_judge")
|
||||
print(client.judge(src=py2_src, language_config=py2_lang_config,
|
||||
max_cpu_time=1000, max_memory=128 * 1024 * 1024,
|
||||
test_case_id="normal", output=True), "\n\n")
|
||||
|
||||
print("py3_judge")
|
||||
print(client.judge(src=py3_src, language_config=py3_lang_config,
|
||||
max_cpu_time=1000, max_memory=128 * 1024 * 1024,
|
||||
test_case_id="normal", output=True), "\n\n")
|
||||
|
||||
print("go_judge")
|
||||
print(client.judge(src=go_src, language_config=go_lang_config,
|
||||
max_cpu_time=1000, max_memory=128 * 1024 * 1024,
|
||||
test_case_id="normal", output=True), "\n\n")
|
||||
|
||||
print("php_judge")
|
||||
print(client.judge(src=php_src, language_config=php_lang_config,
|
||||
max_cpu_time=1000, max_memory=128 * 1024 * 1024,
|
||||
test_case_id="normal", output=True), "\n\n")
|
||||
|
||||
print("js_judge")
|
||||
print(client.judge(src=js_src, language_config=js_lang_config,
|
||||
max_cpu_time=1000, max_memory=128 * 1024 * 1024,
|
||||
test_case_id="normal", output=True), "\n\n")
|
||||
|
||||
print("c_dynamic_input_judge")
|
||||
print(client.judge(src=c_src, language_config=c_lang_config,
|
||||
max_cpu_time=1000, max_memory=1024 * 1024 * 128,
|
||||
test_case=[{"input": "1 2\n", "output": "3"}, {"input": "1 4\n", "output": "3"}], output=True), "\n\n")
|
||||
@@ -0,0 +1,142 @@
|
||||
# coding=utf-8
|
||||
from __future__ import unicode_literals
|
||||
|
||||
default_env = ["LANG=en_US.UTF-8", "LANGUAGE=en_US:en", "LC_ALL=en_US.UTF-8"]
|
||||
|
||||
|
||||
c_lang_config = {
|
||||
"compile": {
|
||||
"src_name": "main.c",
|
||||
"exe_name": "main",
|
||||
"max_cpu_time": 3000,
|
||||
"max_real_time": 5000,
|
||||
"max_memory": 128 * 1024 * 1024,
|
||||
"compile_command": "/usr/bin/gcc -DONLINE_JUDGE -O2 -w -fmax-errors=3 -std=c99 {src_path} -lm -o {exe_path}",
|
||||
},
|
||||
"run": {
|
||||
"command": "{exe_path}",
|
||||
"seccomp_rule": "c_cpp",
|
||||
"env": default_env
|
||||
}
|
||||
}
|
||||
|
||||
c_lang_spj_compile = {
|
||||
"src_name": "spj-{spj_version}.c",
|
||||
"exe_name": "spj-{spj_version}",
|
||||
"max_cpu_time": 3000,
|
||||
"max_real_time": 5000,
|
||||
"max_memory": 1024 * 1024 * 1024,
|
||||
"compile_command": "/usr/bin/gcc -DONLINE_JUDGE -O2 -w -fmax-errors=3 -std=c99 {src_path} -lm -o {exe_path}"
|
||||
}
|
||||
|
||||
c_lang_spj_config = {
|
||||
"exe_name": "spj-{spj_version}",
|
||||
"command": "{exe_path} {in_file_path} {user_out_file_path}",
|
||||
"seccomp_rule": "c_cpp"
|
||||
}
|
||||
|
||||
cpp_lang_config = {
|
||||
"compile": {
|
||||
"src_name": "main.cpp",
|
||||
"exe_name": "main",
|
||||
"max_cpu_time": 3000,
|
||||
"max_real_time": 5000,
|
||||
"max_memory": 128 * 1024 * 1024,
|
||||
"compile_command": "/usr/bin/g++ -DONLINE_JUDGE -O2 -w -fmax-errors=3 -std=c++11 {src_path} -lm -o {exe_path}",
|
||||
},
|
||||
"run": {
|
||||
"command": "{exe_path}",
|
||||
"seccomp_rule": "c_cpp",
|
||||
"env": default_env
|
||||
}
|
||||
}
|
||||
|
||||
java_lang_config = {
|
||||
"name": "java",
|
||||
"compile": {
|
||||
"src_name": "Main.java",
|
||||
"exe_name": "Main",
|
||||
"max_cpu_time": 3000,
|
||||
"max_real_time": 5000,
|
||||
"max_memory": -1,
|
||||
"compile_command": "/usr/bin/javac {src_path} -d {exe_dir} -encoding UTF8"
|
||||
},
|
||||
"run": {
|
||||
"command": "/usr/bin/java -cp {exe_dir} -XX:MaxRAM={max_memory}k -Djava.security.manager -Dfile.encoding=UTF-8 -Djava.security.policy==/etc/java_policy -Djava.awt.headless=true Main",
|
||||
"seccomp_rule": None,
|
||||
"env": default_env,
|
||||
"memory_limit_check_only": 1
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
py2_lang_config = {
|
||||
"compile": {
|
||||
"src_name": "solution.py",
|
||||
"exe_name": "solution.pyc",
|
||||
"max_cpu_time": 3000,
|
||||
"max_real_time": 5000,
|
||||
"max_memory": 128 * 1024 * 1024,
|
||||
"compile_command": "/usr/bin/python -m py_compile {src_path}",
|
||||
},
|
||||
"run": {
|
||||
"command": "/usr/bin/python {exe_path}",
|
||||
"seccomp_rule": "general",
|
||||
"env": default_env
|
||||
}
|
||||
}
|
||||
|
||||
py3_lang_config = {
|
||||
"compile": {
|
||||
"src_name": "solution.py",
|
||||
"exe_name": "__pycache__/solution.cpython-36.pyc",
|
||||
"max_cpu_time": 3000,
|
||||
"max_real_time": 5000,
|
||||
"max_memory": 128 * 1024 * 1024,
|
||||
"compile_command": "/usr/bin/python3 -m py_compile {src_path}",
|
||||
},
|
||||
"run": {
|
||||
"command": "/usr/bin/python3 {exe_path}",
|
||||
"seccomp_rule": "general",
|
||||
"env": ["PYTHONIOENCODING=UTF-8"] + default_env
|
||||
}
|
||||
}
|
||||
|
||||
go_lang_config = {
|
||||
"compile": {
|
||||
"src_name": "main.go",
|
||||
"exe_name": "main",
|
||||
"max_cpu_time": 3000,
|
||||
"max_real_time": 5000,
|
||||
"max_memory": 1024 * 1024 * 1024,
|
||||
"compile_command": "/usr/bin/go build -o {exe_path} {src_path}",
|
||||
"env": ["GOCACHE=/tmp", "GOPATH=/tmp/go"]
|
||||
},
|
||||
"run": {
|
||||
"command": "{exe_path}",
|
||||
"seccomp_rule": "",
|
||||
# 降低内存占用
|
||||
"env": ["GODEBUG=madvdontneed=1", "GOCACHE=off"] + default_env,
|
||||
"memory_limit_check_only": 1
|
||||
}
|
||||
}
|
||||
|
||||
php_lang_config = {
|
||||
"run": {
|
||||
"exe_name": "solution.php",
|
||||
"command": "/usr/bin/php {exe_path}",
|
||||
"seccomp_rule": "",
|
||||
"env": default_env,
|
||||
"memory_limit_check_only": 1
|
||||
}
|
||||
}
|
||||
|
||||
js_lang_config = {
|
||||
"run": {
|
||||
"exe_name": "solution.js",
|
||||
"command": "/usr/bin/node {exe_path}",
|
||||
"seccomp_rule": "",
|
||||
"env": ["NO_COLOR=true"] + default_env,
|
||||
"memory_limit_check_only": 1
|
||||
}
|
||||
}
|
||||
Whitespace-only changes.
@@ -0,0 +1,19 @@
|
||||
# JudgeServer client for Golang
|
||||
|
||||
# Installation
|
||||
|
||||
Install:
|
||||
|
||||
```shell
|
||||
go get -d github.com/QingdaoU/JudgeServer/client/go
|
||||
```
|
||||
|
||||
Import:
|
||||
|
||||
```go
|
||||
import "github.com/QingdaoU/JudgeServer/client/go"
|
||||
```
|
||||
|
||||
# Examples
|
||||
|
||||
[examples](https://github.com/QingdaoU/JudgeServer/tree/master/client/go/examples)
|
||||
@@ -0,0 +1,184 @@
|
||||
package judge
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"io/ioutil"
|
||||
"io"
|
||||
"encoding/json"
|
||||
"time"
|
||||
"bytes"
|
||||
"fmt"
|
||||
)
|
||||
|
||||
// Data 成员的类型参考 https://github.com/QingdaoU/Judger/blob/b6414e7a6715eb013b1ffeb7cfb04626a3ff5b4e/src/runner.h#L73
|
||||
type Data struct {
|
||||
CpuTime int
|
||||
Result int
|
||||
Memory int64 // https://github.com/QingdaoU/Judger/blob/b6414e7a6715eb013b1ffeb7cfb04626a3ff5b4e/src/runner.h#L76
|
||||
RealTime int
|
||||
Signal int
|
||||
Error int
|
||||
ExitCode int
|
||||
OutputMd5 string
|
||||
Output interface{}
|
||||
TestCase string
|
||||
}
|
||||
|
||||
type Resp struct {
|
||||
RespData interface{} `json:"data"`
|
||||
RespErr string `json:"err"`
|
||||
err error `json:"-"`
|
||||
}
|
||||
|
||||
func (resp *Resp) Data() interface{} {
|
||||
if resp == nil {
|
||||
return nil
|
||||
}
|
||||
return resp.RespData
|
||||
}
|
||||
|
||||
func (resp *Resp) StringData() string {
|
||||
if resp == nil {
|
||||
return ""
|
||||
}
|
||||
str, _ := resp.RespData.(string)
|
||||
return str
|
||||
}
|
||||
|
||||
func (resp *Resp) SliceData() []*Data {
|
||||
if resp == nil {
|
||||
return nil
|
||||
}
|
||||
slice, _ := resp.RespData.([]interface{})
|
||||
data := make([]*Data, 0, len(slice))
|
||||
for _, s := range slice {
|
||||
item, ok := s.(map[string]interface{})
|
||||
if ok {
|
||||
cpuTimeF64, _ := item["cpu_time"].(float64)
|
||||
resultF64, _ := item["result"].(float64)
|
||||
memoryF64, _ := item["memory"].(float64)
|
||||
realTimeF64, _ := item["real_time"].(float64)
|
||||
signalF64, _ := item["signal"].(float64)
|
||||
errorF64, _ := item["error"].(float64)
|
||||
exitCodeF64, _ := item["exit_code"].(float64)
|
||||
outputMd5, _ := item["output_md5"].(string)
|
||||
testCase, _ := item["test_case"].(string)
|
||||
data = append(data, &Data{
|
||||
CpuTime: int(cpuTimeF64),
|
||||
Result: int(resultF64),
|
||||
Memory: int64(memoryF64),
|
||||
RealTime: int(realTimeF64),
|
||||
Signal: int(signalF64),
|
||||
Error: int(errorF64),
|
||||
ExitCode: int(exitCodeF64),
|
||||
OutputMd5: outputMd5,
|
||||
Output: item["output"],
|
||||
TestCase: testCase,
|
||||
})
|
||||
}
|
||||
|
||||
}
|
||||
return data
|
||||
}
|
||||
|
||||
func (resp *Resp) Err() error {
|
||||
if resp == nil {
|
||||
return nil
|
||||
}
|
||||
return resp.err
|
||||
}
|
||||
|
||||
func parseResp(body []byte) (*Resp, error) {
|
||||
resp := &Resp{}
|
||||
err := json.Unmarshal(body, resp)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
// 有错误的响应了
|
||||
if resp.RespErr != "" {
|
||||
resp.err = fmt.Errorf("err: %s, data: %s", resp.RespErr, resp.RespData)
|
||||
}
|
||||
|
||||
return resp, nil
|
||||
}
|
||||
|
||||
type Client struct {
|
||||
opts *options
|
||||
httpClient *http.Client
|
||||
}
|
||||
|
||||
func (c *Client) request(method, path string, body io.Reader) (resp *Resp, err error) {
|
||||
req, err := http.NewRequest("POST", c.opts.EndpointURL+"/"+path, body)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
req.Header.Set("X-Judge-Server-Token", c.opts.sha256Token)
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
|
||||
httpResp, err := c.httpClient.Do(req)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
b, err := ioutil.ReadAll(httpResp.Body)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
httpResp.Body.Close()
|
||||
return parseResp(b)
|
||||
}
|
||||
|
||||
func (c *Client) post(path string, body io.Reader) (resp *Resp, err error) {
|
||||
return c.request("POST", path, body)
|
||||
}
|
||||
|
||||
// Ping Judge server
|
||||
func (c *Client) Ping() (resp *Resp, err error) {
|
||||
resp, err = c.post("ping", nil)
|
||||
return
|
||||
}
|
||||
|
||||
func (c *Client) CompileSpj(src, spjVersion string, spjCompileConfig *CompileConfig) (resp *Resp, err error) {
|
||||
data := map[string]interface{}{
|
||||
"src": src,
|
||||
"spj_version": spjVersion,
|
||||
"spj_compile_config": spjCompileConfig,
|
||||
}
|
||||
b, err := json.Marshal(data)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
resp, err = c.post("compile_spj", bytes.NewReader(b))
|
||||
return
|
||||
}
|
||||
|
||||
func New(endpointURL, token string, timeout time.Duration) *Client {
|
||||
return NewClient(
|
||||
WithEndpointURL(endpointURL),
|
||||
WithToken(token),
|
||||
WithTimeout(timeout),
|
||||
)
|
||||
}
|
||||
|
||||
func (c *Client) SetOptions(options ...Option) {
|
||||
originTimeout := c.opts.Timeout
|
||||
for _, o := range options {
|
||||
o(c.opts)
|
||||
}
|
||||
if c.opts.Timeout != originTimeout {
|
||||
c.httpClient.Timeout = c.opts.Timeout
|
||||
}
|
||||
}
|
||||
|
||||
func NewClient(options ...Option) *Client {
|
||||
opts := DefaultOptions
|
||||
for _, o := range options {
|
||||
o(opts)
|
||||
}
|
||||
|
||||
return &Client{
|
||||
opts: opts,
|
||||
httpClient: &http.Client{
|
||||
Timeout: opts.Timeout,
|
||||
},
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,56 @@
|
||||
package judge
|
||||
|
||||
import (
|
||||
"testing"
|
||||
)
|
||||
|
||||
var client *Client
|
||||
|
||||
func TestMain(m *testing.M) {
|
||||
// 创建一个client。 这句代码等价于 New("http://127.0.0.1:12358", "YOUR_TOKEN_HERE", 0)
|
||||
client = NewClient(
|
||||
WithEndpointURL("http://127.0.0.1:12358"),
|
||||
WithToken("YOUR_TOKEN_HERE"),
|
||||
WithTimeout(0),
|
||||
)
|
||||
m.Run()
|
||||
}
|
||||
|
||||
func TestClient_Ping(t *testing.T) {
|
||||
resp, err := client.Ping()
|
||||
if err != nil {
|
||||
t.Errorf("unexpected error. error: %+v", err)
|
||||
return
|
||||
}
|
||||
if resp.Err() != nil {
|
||||
t.Errorf("unexpected error. error: %+v", resp.Err())
|
||||
return
|
||||
}
|
||||
|
||||
if resp.RespData == nil {
|
||||
t.Error("resp.RespData unexpected nil")
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
func TestClient_CompileSpj(t *testing.T) {
|
||||
cSpjSrc := `
|
||||
#include <stdio.h>
|
||||
int main(){
|
||||
return 1;
|
||||
}
|
||||
`
|
||||
resp, err := client.CompileSpj(cSpjSrc, "2", CLangSPJCompile)
|
||||
if err != nil {
|
||||
t.Errorf("unexpected error. error: %+v", err)
|
||||
return
|
||||
}
|
||||
if resp.Err() != nil {
|
||||
t.Errorf("unexpected error. error: %+v", resp.Err())
|
||||
return
|
||||
}
|
||||
if resp.RespData == nil {
|
||||
t.Error("resp.RespData unexpected nil")
|
||||
return
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,168 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"github.com/QingdaoU/JudgeServer/client/go"
|
||||
"fmt"
|
||||
)
|
||||
|
||||
var (
|
||||
cSrc = `
|
||||
#include <stdio.h>
|
||||
int main(){
|
||||
int a, b;
|
||||
scanf("%d%d", &a, &b);
|
||||
printf("%d\n", a+b);
|
||||
return 0;
|
||||
}
|
||||
`
|
||||
cSPJSrc = `
|
||||
#include <stdio.h>
|
||||
int main(){
|
||||
return 1;
|
||||
}
|
||||
`
|
||||
cppSrc = `
|
||||
#include <iostream>
|
||||
|
||||
using namespace std;
|
||||
|
||||
int main()
|
||||
{
|
||||
int a,b;
|
||||
cin >> a >> b;
|
||||
cout << a+b << endl;
|
||||
return 0;
|
||||
}
|
||||
`
|
||||
javaSrc = `
|
||||
import java.util.Scanner;
|
||||
public class Main{
|
||||
public static void main(String[] args){
|
||||
Scanner in=new Scanner(System.in);
|
||||
int a=in.nextInt();
|
||||
int b=in.nextInt();
|
||||
System.out.println(a + b);
|
||||
}
|
||||
}
|
||||
`
|
||||
py2Src = `
|
||||
s = raw_input()
|
||||
s1 = s.split(" ")
|
||||
print int(s1[0]) + int(s1[1])
|
||||
`
|
||||
py3Src = `
|
||||
s = input()
|
||||
s1 = s.split(" ")
|
||||
print(int(s1[0]) + int(s1[1]))
|
||||
`
|
||||
)
|
||||
|
||||
func main() {
|
||||
// 创建一个client。 这句代码等价于
|
||||
|
||||
// 1.
|
||||
//client := judge.NewClient(
|
||||
// judge.WithEndpointURL("http://127.0.0.1:12358"),
|
||||
// judge.WithToken("YOUR_TOKEN_HERE"),
|
||||
// judge.WithTimeout(0),
|
||||
//)
|
||||
|
||||
// 2.
|
||||
// client := judge.New("http://127.0.0.1:12358", "YOUR_TOKEN_HERE", 0)
|
||||
|
||||
// 3.
|
||||
client := judge.NewClient(judge.WithTimeout(0))
|
||||
client.SetOptions(judge.WithEndpointURL("http://127.0.0.1:12358"), judge.WithToken("YOUR_TOKEN_HERE"))
|
||||
|
||||
fmt.Println("ping:")
|
||||
resp, err := client.Ping()
|
||||
if err != nil {
|
||||
// 这个 err 是发生在 client 这边的错误。 例如json编码失败
|
||||
fmt.Printf("ping client error. error is: %v.\n", err)
|
||||
} else if resp.Err() != nil {
|
||||
// 这个 resp.Err() 是 JudgeServer 响应的错误。 例如token错误 TokenVerificationFailed
|
||||
fmt.Printf("ping server error. error is: %v.\n", resp.Err().Error())
|
||||
} else {
|
||||
fmt.Println(resp.Data())
|
||||
}
|
||||
fmt.Println()
|
||||
|
||||
fmt.Println("cpp_judge")
|
||||
resp, _ = client.JudgeWithRequest(&judge.JudgeRequest{
|
||||
Src: cppSrc,
|
||||
LanguageConfig: judge.CPPLangConfig,
|
||||
MaxCpuTime: 1000,
|
||||
MaxMemory: 128 * 1024 * 1024,
|
||||
TestCaseId: "normal",
|
||||
})
|
||||
printSliceData(resp.SliceData())
|
||||
fmt.Println()
|
||||
|
||||
fmt.Println("java_judge")
|
||||
resp, _ = client.JudgeWithRequest(&judge.JudgeRequest{
|
||||
Src: javaSrc,
|
||||
LanguageConfig: judge.JavaLangConfig,
|
||||
MaxCpuTime: 1000,
|
||||
MaxMemory: 256 * 1024 * 1024,
|
||||
TestCaseId: "normal",
|
||||
})
|
||||
printSliceData(resp.SliceData())
|
||||
fmt.Println()
|
||||
|
||||
fmt.Println("c_spj_judge")
|
||||
resp, _ = client.JudgeWithRequest(&judge.JudgeRequest{
|
||||
Src: cSrc,
|
||||
LanguageConfig: judge.CLangConfig,
|
||||
MaxCpuTime: 1000,
|
||||
MaxMemory: 128 * 1024 * 1024,
|
||||
TestCaseId: "spj",
|
||||
SPJVersion: "3",
|
||||
SPJConfig: judge.CLangSPJConfig,
|
||||
SPJCompileConfig: judge.CLangSPJCompile,
|
||||
SPJSrc: cSPJSrc,
|
||||
})
|
||||
printSliceData(resp.SliceData())
|
||||
fmt.Println()
|
||||
|
||||
fmt.Println("py2_judge")
|
||||
resp, _ = client.JudgeWithRequest(&judge.JudgeRequest{
|
||||
Src: py2Src,
|
||||
LanguageConfig: judge.PY2LangConfig,
|
||||
MaxCpuTime: 1000,
|
||||
MaxMemory: 128 * 1024 * 1024,
|
||||
TestCaseId: "normal",
|
||||
})
|
||||
printSliceData(resp.SliceData())
|
||||
fmt.Println()
|
||||
|
||||
fmt.Println("py3_judge")
|
||||
resp, _ = client.JudgeWithRequest(&judge.JudgeRequest{
|
||||
Src: py3Src,
|
||||
LanguageConfig: judge.PY3LangConfig,
|
||||
MaxCpuTime: 1000,
|
||||
MaxMemory: 128 * 1024 * 1024,
|
||||
TestCaseId: "normal",
|
||||
})
|
||||
printSliceData(resp.SliceData())
|
||||
fmt.Println()
|
||||
|
||||
// CompileError example
|
||||
fmt.Println("CompileError example")
|
||||
resp, err = client.JudgeWithRequest(&judge.JudgeRequest{
|
||||
Src: "this bad code",
|
||||
LanguageConfig: judge.JavaLangConfig,
|
||||
MaxCpuTime: 1000,
|
||||
MaxMemory: 256 * 1024 * 1024,
|
||||
TestCaseId: "normal",
|
||||
})
|
||||
// fmt.Println(resp.RespErr) // "CompileError"
|
||||
fmt.Println(resp.StringData()) // 错误信息
|
||||
}
|
||||
|
||||
func printSliceData(slice []*judge.Data) {
|
||||
fmt.Print("[\n")
|
||||
for _, item := range slice {
|
||||
fmt.Printf("\t%#v,\n", item)
|
||||
}
|
||||
fmt.Print("]\n")
|
||||
}
|
||||
@@ -0,0 +1,46 @@
|
||||
package judge
|
||||
|
||||
import (
|
||||
"time"
|
||||
"bytes"
|
||||
"encoding/json"
|
||||
)
|
||||
|
||||
type JudgeRequest struct {
|
||||
Src string `json:"src"`
|
||||
LanguageConfig *LangConfig `json:"language_config"`
|
||||
MaxCpuTime int64 `json:"max_cpu_time"`
|
||||
MaxMemory int64 `json:"max_memory"`
|
||||
TestCaseId string `json:"test_case_id"`
|
||||
SPJVersion string `json:"spj_version"`
|
||||
SPJConfig *SPJConfig `json:"spj_config"`
|
||||
SPJCompileConfig *CompileConfig `json:"spj_compile_config"`
|
||||
SPJSrc string `json:"spj_src"`
|
||||
Output bool `json:"output"`
|
||||
}
|
||||
|
||||
// 这个方法为了模仿 php 和 python client 不推荐使用
|
||||
func (c *Client) Judge(src string, languageConfig *LangConfig, maxCpuTime time.Duration, maxMemory int64, testCaseId,
|
||||
spjVersion string, spjConfig *SPJConfig, spjCompileConfig *CompileConfig, spjSrc string, output bool) (resp *Resp, err error) {
|
||||
return c.JudgeWithRequest(&JudgeRequest{
|
||||
Src: src,
|
||||
LanguageConfig: languageConfig,
|
||||
MaxCpuTime: int64(maxCpuTime),
|
||||
MaxMemory: maxMemory,
|
||||
TestCaseId: testCaseId,
|
||||
SPJVersion: spjVersion,
|
||||
SPJConfig: spjConfig,
|
||||
SPJCompileConfig: spjCompileConfig,
|
||||
SPJSrc: spjSrc,
|
||||
Output: output,
|
||||
})
|
||||
}
|
||||
|
||||
func (c *Client) JudgeWithRequest(req *JudgeRequest) (resp *Resp, err error) {
|
||||
b, err := json.Marshal(req)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
resp, err = c.post("judge", bytes.NewReader(b))
|
||||
return
|
||||
}
|
||||
@@ -0,0 +1,76 @@
|
||||
package judge
|
||||
|
||||
import "testing"
|
||||
|
||||
func TestClient_JudgeWithRequest(t *testing.T) {
|
||||
javaSrc := `
|
||||
import java.util.Scanner;
|
||||
public class Main{
|
||||
public static void main(String[] args){
|
||||
Scanner in=new Scanner(System.in);
|
||||
int a=in.nextInt();
|
||||
int b=in.nextInt();
|
||||
System.out.println(a + b);
|
||||
}
|
||||
}
|
||||
`
|
||||
cSrc := `
|
||||
#include <stdio.h>
|
||||
int main(){
|
||||
int a, b;
|
||||
scanf("%d%d", &a, &b);
|
||||
printf("%d\n", a+b);
|
||||
return 0;
|
||||
}
|
||||
`
|
||||
cSPJSrc := `
|
||||
#include <stdio.h>
|
||||
int main(){
|
||||
return 1;
|
||||
}
|
||||
`
|
||||
var tests = []struct {
|
||||
JudgeRequest *JudgeRequest
|
||||
}{
|
||||
{
|
||||
JudgeRequest: &JudgeRequest{
|
||||
Src: javaSrc,
|
||||
LanguageConfig: JavaLangConfig,
|
||||
MaxCpuTime: 1000,
|
||||
MaxMemory: 256 * 1024 * 1024,
|
||||
TestCaseId: "normal",
|
||||
},
|
||||
},
|
||||
{
|
||||
JudgeRequest: &JudgeRequest{
|
||||
Src: cSrc,
|
||||
LanguageConfig: CLangConfig,
|
||||
MaxCpuTime: 1000,
|
||||
MaxMemory: 128 * 1024 * 1024,
|
||||
TestCaseId: "spj",
|
||||
SPJVersion: "3",
|
||||
SPJConfig: CLangSPJConfig,
|
||||
SPJCompileConfig: CLangSPJCompile,
|
||||
SPJSrc: cSPJSrc,
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
for _, test := range tests {
|
||||
resp, err := client.JudgeWithRequest(test.JudgeRequest)
|
||||
if err != nil {
|
||||
t.Errorf("unexpected error. error: %+v", err)
|
||||
return
|
||||
}
|
||||
if resp.Err() != nil {
|
||||
t.Errorf("unexpected error. error: %+v", resp.Err())
|
||||
return
|
||||
}
|
||||
if resp.RespData == nil {
|
||||
t.Error("resp.RespData unexpected nil")
|
||||
return
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,126 @@
|
||||
package judge
|
||||
|
||||
type CompileConfig struct {
|
||||
SrcName string `json:"src_name"`
|
||||
ExeName string `json:"exe_name"`
|
||||
MaxCpuTime int64 `json:"max_cpu_time"`
|
||||
MaxRealTime int64 `json:"max_real_time"`
|
||||
MaxMemory int64 `json:"max_memory"`
|
||||
CompileCommand string `json:"compile_command"`
|
||||
}
|
||||
|
||||
var DefaultEnv = []string{"LANG=en_US.UTF-8", "LANGUAGE=en_US:en", "LC_ALL=en_US.UTF-8"}
|
||||
|
||||
type RunConfig struct {
|
||||
Command string `json:"command"`
|
||||
SeccompRule string `json:"seccomp_rule"`
|
||||
Env []string `json:"env"`
|
||||
MemoryLimitCheckOnly int `json:"memory_limit_check_only"`
|
||||
}
|
||||
|
||||
type LangConfig struct {
|
||||
CompileConfig CompileConfig `json:"compile"`
|
||||
RunConfig RunConfig `json:"run"`
|
||||
}
|
||||
|
||||
type SPJConfig struct {
|
||||
ExeName string `json:"exe_name"`
|
||||
Command string `json:"command"`
|
||||
SeccompRule string `json:"seccomp_rule"`
|
||||
}
|
||||
|
||||
var CLangConfig = &LangConfig{
|
||||
CompileConfig: CompileConfig{
|
||||
SrcName: "main.c",
|
||||
ExeName: "main",
|
||||
MaxCpuTime: 3000,
|
||||
MaxRealTime: 5000,
|
||||
MaxMemory: 128 * 1024 * 1024,
|
||||
CompileCommand: "/usr/bin/gcc -DONLINE_JUDGE -O2 -w -fmax-errors=3 -std=c99 {src_path} -lm -o {exe_path}",
|
||||
},
|
||||
RunConfig: RunConfig{
|
||||
Command: "{exe_path}",
|
||||
SeccompRule: "c_cpp",
|
||||
Env: DefaultEnv,
|
||||
},
|
||||
}
|
||||
|
||||
var CLangSPJCompile = &CompileConfig{
|
||||
SrcName: "spj-{spj_version}.c",
|
||||
ExeName: "spj-{spj_version}",
|
||||
MaxCpuTime: 3000,
|
||||
MaxRealTime: 5000,
|
||||
MaxMemory: 1024 * 1024 * 1024,
|
||||
CompileCommand: "/usr/bin/gcc -DONLINE_JUDGE -O2 -w -fmax-errors=3 -std=c99 {src_path} -lm -o {exe_path}",
|
||||
}
|
||||
|
||||
var CLangSPJConfig = &SPJConfig{
|
||||
ExeName: "spj-{spj_version}",
|
||||
Command: "{exe_path} {in_file_path} {user_out_file_path}",
|
||||
SeccompRule: "c_cpp",
|
||||
}
|
||||
|
||||
var CPPLangConfig = &LangConfig{
|
||||
CompileConfig: CompileConfig{
|
||||
SrcName: "main.cpp",
|
||||
ExeName: "main",
|
||||
MaxCpuTime: 3000,
|
||||
MaxRealTime: 5000,
|
||||
MaxMemory: 128 * 1024 * 1024,
|
||||
CompileCommand: "/usr/bin/g++ -DONLINE_JUDGE -O2 -w -fmax-errors=3 -std=c++11 {src_path} -lm -o {exe_path}",
|
||||
},
|
||||
RunConfig: RunConfig{
|
||||
Command: "{exe_path}",
|
||||
SeccompRule: "c_cpp",
|
||||
Env: DefaultEnv,
|
||||
},
|
||||
}
|
||||
|
||||
var JavaLangConfig = &LangConfig{
|
||||
CompileConfig: CompileConfig{
|
||||
SrcName: "Main.java",
|
||||
ExeName: "Main",
|
||||
MaxCpuTime: 3000,
|
||||
MaxRealTime: 5000,
|
||||
MaxMemory: -1,
|
||||
CompileCommand: "/usr/bin/javac {src_path} -d {exe_dir} -encoding UTF8",
|
||||
},
|
||||
RunConfig: RunConfig{
|
||||
Command: "/usr/bin/java -cp {exe_dir} -XX:MaxRAM={max_memory}k -Djava.security.manager -Dfile.encoding=UTF-8 -Djava.security.policy==/etc/java_policy -Djava.awt.headless=true Main",
|
||||
SeccompRule: "",
|
||||
Env: DefaultEnv,
|
||||
MemoryLimitCheckOnly: 1,
|
||||
},
|
||||
}
|
||||
|
||||
var PY2LangConfig = &LangConfig{
|
||||
CompileConfig: CompileConfig{
|
||||
SrcName: "solution.py",
|
||||
ExeName: "solution.pyc",
|
||||
MaxCpuTime: 3000,
|
||||
MaxRealTime: 5000,
|
||||
MaxMemory: 128 * 1024 * 1024,
|
||||
CompileCommand: "/usr/bin/python -m py_compile {src_path}",
|
||||
},
|
||||
RunConfig: RunConfig{
|
||||
Command: "/usr/bin/python {exe_path}",
|
||||
SeccompRule: "general",
|
||||
Env: DefaultEnv,
|
||||
},
|
||||
}
|
||||
|
||||
var PY3LangConfig = &LangConfig{
|
||||
CompileConfig: CompileConfig{
|
||||
SrcName: "solution.py",
|
||||
ExeName: "__pycache__/solution.cpython-35.pyc",
|
||||
MaxCpuTime: 3000,
|
||||
MaxRealTime: 5000,
|
||||
MaxMemory: 128 * 1024 * 1024,
|
||||
CompileCommand: "/usr/bin/python3 -m py_compile {src_path}",
|
||||
},
|
||||
RunConfig: RunConfig{
|
||||
Command: "/usr/bin/python3 {exe_path}",
|
||||
SeccompRule: "general",
|
||||
Env: append(DefaultEnv, "PYTHONIOENCODING=UTF-8"),
|
||||
},
|
||||
}
|
||||
@@ -0,0 +1,45 @@
|
||||
package judge
|
||||
|
||||
import (
|
||||
"time"
|
||||
"crypto/sha256"
|
||||
"encoding/hex"
|
||||
)
|
||||
|
||||
type options struct {
|
||||
// scheme://host:port .
|
||||
EndpointURL string
|
||||
Token string
|
||||
sha256Token string
|
||||
// 请求超时时间
|
||||
// 如果 Timeout 为 0,那么意味着不会超时
|
||||
Timeout time.Duration
|
||||
}
|
||||
|
||||
var DefaultOptions = &options{
|
||||
EndpointURL: "http://127.0.0.1:12358",
|
||||
Token: "YOUR_TOKEN_HERE",
|
||||
Timeout: 10 * time.Second,
|
||||
}
|
||||
|
||||
type Option func(*options)
|
||||
|
||||
func WithEndpointURL(u string) Option {
|
||||
return func(o *options) {
|
||||
o.EndpointURL = u
|
||||
}
|
||||
}
|
||||
|
||||
func WithToken(token string) Option {
|
||||
return func(o *options) {
|
||||
o.Token = token
|
||||
sha256Token := sha256.Sum256([]byte(token))
|
||||
o.sha256Token = hex.EncodeToString(sha256Token[:])
|
||||
}
|
||||
}
|
||||
|
||||
func WithTimeout(timeout time.Duration) Option {
|
||||
return func(o *options) {
|
||||
o.Timeout = timeout
|
||||
}
|
||||
}
|
||||
@@ -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()
|
||||
@@ -0,0 +1 @@
|
||||
1 2
|
||||
@@ -0,0 +1 @@
|
||||
3
|
||||
@@ -0,0 +1 @@
|
||||
{"test_case_number": 1, "spj": false, "test_cases": {"1": {"stripped_output_md5": "eccbc87e4b5ce2fe28308fd9f2a7baf3", "output_size": 2, "output_md5": "6d7fce9fee471194aa8b5b6e47267f03", "input_name": "1.in", "input_size": 4, "output_name": "1.out"}}}
|
||||
@@ -0,0 +1 @@
|
||||
1 2
|
||||
@@ -0,0 +1 @@
|
||||
{"test_case_number": 1, "spj": true, "test_cases": {"1": {"input_name": "1.in", "input_size": 4}}}
|
||||
@@ -0,0 +1 @@
|
||||
你好,世界
|
||||
@@ -0,0 +1 @@
|
||||
你好,世界
|
||||
@@ -0,0 +1,12 @@
|
||||
{
|
||||
"spj": false,
|
||||
"test_cases": {
|
||||
"1": {
|
||||
"stripped_output_md5": "dbefd3ada018615b35588a01e216ae6e",
|
||||
"input_size": 16,
|
||||
"output_size": 16,
|
||||
"input_name": "1.in",
|
||||
"output_name": "1.out"
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,47 @@
|
||||
# coding=utf-8
|
||||
from __future__ import unicode_literals
|
||||
from os import sys, path
|
||||
sys.path.append(path.dirname(path.dirname(path.abspath(__file__))))
|
||||
|
||||
import json
|
||||
import unittest
|
||||
import requests
|
||||
|
||||
|
||||
from client.Python.client import JudgeServerClient, JudgeServerClientError
|
||||
|
||||
|
||||
class JudgeServerClientForTokenHeaderTest(JudgeServerClient):
|
||||
def _request(self, url, data=None):
|
||||
kwargs = {"headers": {"Content-Type": "application/json"}}
|
||||
if data:
|
||||
kwargs["data"] = json.dumps(data)
|
||||
try:
|
||||
return requests.post(url, **kwargs).json()
|
||||
except Exception as e:
|
||||
raise JudgeServerClientError(e.message)
|
||||
|
||||
|
||||
class JudgeServerTest(unittest.TestCase):
|
||||
def setUp(self):
|
||||
self.token = "YOUR_TOKEN_HERE"
|
||||
self.server_base_url = "http://127.0.0.1:12358"
|
||||
self.client = JudgeServerClient(token=self.token, server_base_url=self.server_base_url)
|
||||
|
||||
def test_success(self):
|
||||
data = self.client.ping()
|
||||
self.assertEqual(data["err"], None)
|
||||
self.assertEqual(data["data"]["action"], "pong")
|
||||
|
||||
def test_invalid_token(self):
|
||||
client = JudgeServerClient(token="wrong token", server_base_url=self.server_base_url)
|
||||
data = client.ping()
|
||||
self.assertEqual(data["err"], "TokenVerificationFailed")
|
||||
|
||||
def test_no_token_header(self):
|
||||
client = JudgeServerClientForTokenHeaderTest(token="wrong token", server_base_url=self.server_base_url)
|
||||
data = client.ping()
|
||||
self.assertEqual(data["err"], "TokenVerificationFailed")
|
||||
|
||||
if __name__ == '__main__':
|
||||
unittest.main()
|
||||
Reference in new issue
Block a user