| 1 | """A bot in its own process, spoken to one JSON line at a time. Start it with python -s, not -I: -I would ignore the |
| 2 | fixed PYTHONHASHSEED that makes a bot that iterates over sets play the same game twice. |
| 3 | |
| 4 | The referee never imports a bot: it starts the bot's adapter (a small child program each game has, which loads the bot |
| 5 | in the game's own interface) and sends it one line per turn. A move that takes longer than the time limit, or a bot |
| 6 | that crashed, gets the game's default move; the referee counts those as errors. The child side is `serve(handle)`. |
| 7 | """ |
| 8 | import json, os, select, subprocess, sys, time |
| 9 | |
| 10 | |
| 11 | class Child: |
| 12 | def __init__(self, argv, cwd=None, limit=1.0, start=10.0): |
| 13 | self.limit, self.errors, self.dead = limit, 0, False |
| 14 | env = {k: v for k, v in os.environ.items() if not k.startswith(('SS_', 'SLURM_'))} |
| 15 | env['PYTHONHASHSEED'] = '0' |
| 16 | self.p = subprocess.Popen(argv, cwd=cwd, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.DEVNULL, env=env) |
| 17 | self.buf, self.n = b'', 0 |
| 18 | self.ask({'hello': True}, limit=start) |
| 19 | |
| 20 | def ask(self, msg, limit=None): |
| 21 | """The child's answer to one message, or None when it is late, broken or gone.""" |
| 22 | if self.dead: |
| 23 | return None |
| 24 | try: |
| 25 | self.n += 1 |
| 26 | self.p.stdin.write((json.dumps({**msg, 'n': self.n}) + '\n').encode()) |
| 27 | self.p.stdin.flush() |
| 28 | deadline = time.monotonic() + (limit or self.limit) |
| 29 | fd = self.p.stdout.fileno() |
| 30 | while True: |
| 31 | while b'\n' not in self.buf: |
| 32 | ready, _, _ = select.select([fd], [], [], max(0.0, deadline - time.monotonic())) |
| 33 | chunk = os.read(fd, 1 << 16) if ready else b'' |
| 34 | if not chunk: |
| 35 | raise TimeoutError |
| 36 | self.buf += chunk |
| 37 | line, self.buf = self.buf.split(b'\n', 1) |
| 38 | try: |
| 39 | msg_in = json.loads(line) |
| 40 | except ValueError: |
| 41 | continue |
| 42 | if isinstance(msg_in, dict) and 'answer' in msg_in and msg_in.get('n') == self.n: |
| 43 | return msg_in['answer'] |
| 44 | except Exception: |
| 45 | self.errors += 1 |
| 46 | if self.errors >= 20 or self.p.poll() is not None: |
| 47 | self.close() |
| 48 | return None |
| 49 | |
| 50 | def close(self): |
| 51 | self.dead = True |
| 52 | try: |
| 53 | self.p.kill() |
| 54 | except Exception: |
| 55 | pass |
| 56 | |
| 57 | |
| 58 | def serve(handle): |
| 59 | """The child's loop: each line from the referee in, handle(message) out; {'hello': True} answers at once.""" |
| 60 | out = sys.__stdout__ |
| 61 | sys.stdout = sys.stderr |
| 62 | for line in sys.stdin: |
| 63 | msg = json.loads(line) |
| 64 | answer = True if msg.get('hello') else handle(msg) |
| 65 | out.write(json.dumps({'answer': answer, 'n': msg.get('n')}) + '\n') |
| 66 | out.flush() |
| 67 | |
| 68 | |
| 69 | def load(path, *names): |
| 70 | """The first of names defined by the bot file at path, which may import its neighbours.""" |
| 71 | import importlib.util |
| 72 | sys.path.insert(0, os.path.dirname(os.path.abspath(path))) |
| 73 | spec = importlib.util.spec_from_file_location('bot', path) |
| 74 | mod = importlib.util.module_from_spec(spec) |
| 75 | spec.loader.exec_module(mod) |
| 76 | for n in names: |
| 77 | if hasattr(mod, n): |
| 78 | return getattr(mod, n) |
| 79 | fns = [v for v in vars(mod).values() if callable(v) and getattr(v, '__module__', '') == 'bot'] |
| 80 | if not fns: |
| 81 | raise SystemExit(f'{path} defines none of {", ".join(names)}') |
| 82 | return fns[-1] |