Skip to content

Commit

Permalink
fixed code style
Browse files Browse the repository at this point in the history
  • Loading branch information
OriSnow420 authored and futrime committed Jan 27, 2025
1 parent 975d5a3 commit 38bdd32
Show file tree
Hide file tree
Showing 2 changed files with 49 additions and 47 deletions.
37 changes: 18 additions & 19 deletions thuai_builder.py
Original file line number Diff line number Diff line change
@@ -1,42 +1,42 @@
import docker.errors
from base_docker_image_builder import BaseDockerImageBuilder
"""Contains docker image build for THUAI."""

from typing import Dict
from pathlib import Path
import string
import random
import docker
import string, random
import docker.errors
from base_docker_image_builder import BaseDockerImageBuilder

BUILDER_NAME_LENGTH = 10
IMAGE_NAME_PREFIX = "THUAI-image"

class ThuaiBuilder(BaseDockerImageBuilder):
"""Docker image builder for THUAI matches."""

def __init__(self):
self.client = docker.from_env()
self.built_images = dict()
self.built_images = {}

# Generate a random string for the builder, to avoid name conflict
chars = string.ascii_letters + string.digits
self.name = ''.join(random.choice(chars) for _ in range(BUILDER_NAME_LENGTH))

# ID for image, to avoid name conflict
self.image_id = 0

async def build(self, file_path: Path) -> str:
# if not built yet...
if file_path not in self.built_images.keys():
try:
img_tag = self.get_image_name()
image, log = self.client.images.build(path=file_path,
tag=img_tag,
rm=True
)
self.built_images[file_path] = img_tag

except Exception as e:
raise
if file_path not in self.built_images:
img_tag = self.get_image_name()
self.client.images.build(path=file_path,
tag=img_tag,
rm=True
)
self.built_images[file_path] = img_tag

return self.built_images[file_path]

async def clean(self) -> None:
for image_tag in self.built_images.values():
self.client.images.remove(image=image_tag)
Expand All @@ -45,7 +45,7 @@ async def clean(self) -> None:

async def list(self) -> Dict[Path, str]:
return self.built_images.copy()

async def get_image_name(self) -> str:
'''Get a no-duplicate name for images
Expand All @@ -57,4 +57,3 @@ async def get_image_name(self) -> str:
name = IMAGE_NAME_PREFIX + self.name + '-' + str(self.image_id)
self.image_id = self.image_id + 1
return name

59 changes: 31 additions & 28 deletions thuai_judger.py
Original file line number Diff line number Diff line change
@@ -1,15 +1,19 @@
"""Contains the judger class implemented for THUAI matches."""

from base_match_judger import BaseMatchJudger
from match_result import MatchResult
from typing import List, Dict
from pathlib import Path
import docker
import random, string
from docker.types import Mount
import random
import string
import asyncio
import json

import docker
from docker.types import Mount

from base_match_judger import BaseMatchJudger
from match_result import MatchResult



JUDGER_NAME_LENGTH = 10
AGENT_CONTAINER_NAME_PREFIX = "THUAI_agent_"
Expand All @@ -19,18 +23,18 @@
JUDGE_TIMEOUT = 600 # In seconds

class JudgeTimeoutException(Exception):
"""Exception class for Judge timeout"""

def __init__(self):
super().__init__()
pass

class ThuaiJudger(BaseMatchJudger):
"""The Judger implemented for THUAI judgement work."""

def __init__(self):
"""Initialize the judger
"""
"""Initialize the judger."""
self.client = docker.from_env()
self.judges = dict()
self.containers = []
self.judges = {}

# Generate a random string for the judger, to avoid name conflict
chars = string.ascii_letters + string.digits
Expand All @@ -42,15 +46,15 @@ def __init__(self):
self.network_id = 0

# Record resources held by each judge.
self.judge_containers : Dict[str, List[str]] = dict()
self.judge_networks : Dict[str, List[str]] = dict()
self.judge_containers : Dict[str, List[str]] = {}
self.judge_networks : Dict[str, List[str]] = {}

async def judge(
self, match_id: str, game_host_image_tag: str, agent_image_tags: List[str]
) -> MatchResult:

# If not judged before...
if match_id not in self.judges.keys():
if match_id not in self.judges:
try:
# Judge and memorize the result.

Expand Down Expand Up @@ -113,7 +117,7 @@ async def judge(
except Exception:
self.stop_judge(match_id)
raise

return self.judges[match_id]

async def wait_container(self, container_name: str):
Expand All @@ -126,7 +130,7 @@ async def wait_container(self, container_name: str):

async def list(self) -> Dict[str, MatchResult]:
return self.judges.copy()

async def force_kill(self, match_id, waiting: int=JUDGE_TIMEOUT) -> None:
"""Force stop a match and throw an exception.
Expand All @@ -140,7 +144,7 @@ async def force_kill(self, match_id, waiting: int=JUDGE_TIMEOUT) -> None:
await asyncio.sleep(waiting)
self.stop_judge(match_id)
raise JudgeTimeoutException

def stop_judge(self, match_id: str) -> None:
"""Stop a judge and release its resources
Expand All @@ -150,12 +154,12 @@ def stop_judge(self, match_id: str) -> None:
match_id (str): The match to stop.
"""

if match_id in self.judge_containers.keys():
if match_id in self.judge_containers:
for container in self.judge_containers[match_id]:
self.client.containers.get(container).kill()
self.judge_containers.pop(match_id)

if match_id in self.judge_networks.keys():
if match_id in self.judge_networks:
for network in self.judge_networks[match_id]:
self.client.networks.get(network).remove()
self.judge_networks.pop(match_id)
Expand All @@ -169,11 +173,12 @@ def get_winner(self, match_id) -> int:
Returns:
int: The player id
"""
with open(Path(self.get_name("record", match_id)) / "result.json", 'r') as f:
with open(Path(self.get_name("record", match_id)) / "result.json", 'r',
encoding='utf-8') as f:
return int(json.load(f)["winner"])


def get_name(self, type: str, match_id="") -> str:
def get_name(self, resource_type: str, match_id="") -> str:
"""Generates a no-duplicate name for containers and networks.
Name format: THUAI_{type}_{judger_name}_{id} (except for "record")
Expand All @@ -190,19 +195,17 @@ def get_name(self, type: str, match_id="") -> str:
Raises:
ValueError: If type is illegal.
"""
if type == "agent":
if resource_type == "agent":
name = AGENT_CONTAINER_NAME_PREFIX + self.name + '_' + str(self.agent_id)
self.agent_id = self.agent_id + 1
elif type == "server":
elif resource_type == "server":
name = SERVER_CONTAINER_NAME_PREFIX + self.name + '_' + str(self.server_id)
self.server_id = self.server_id + 1
elif type == "network":
elif resource_type == "network":
name = NETWORK_NAME_PREFIX + self.name + '_' + str(self.network_id)
self.network_id = self.network_id + 1
elif type == "record":
elif resource_type == "record":
name = str(Path.cwd() / "record" / self.name / match_id)
pass
else:
raise ValueError
return name

0 comments on commit 38bdd32

Please sign in to comment.