forked from niklasf/python-chess
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathengine.py
More file actions
331 lines (245 loc) · 9.1 KB
/
engine.py
File metadata and controls
331 lines (245 loc) · 9.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
# -*- coding: utf-8 -*-
#
# This file is part of the python-chess library.
# Copyright (C) 2012-2017 Niklas Fiekas <niklas.fiekas@backscattering.de>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
import logging
import threading
import os
import sys
import signal
import platform
try:
import backport_collections as collections
except ImportError:
import collections
try:
import queue
except ImportError:
import Queue as queue
if os.name == "posix" and sys.version_info[0] < 3:
try:
import subprocess32 as subprocess
except ImportError:
import subprocess
else:
import subprocess
FUTURE_POLL_TIMEOUT = 0.1 if platform.system() == "Windows" else 60
LOGGER = logging.getLogger(__name__)
class EngineTerminatedException(Exception):
"""The engine has been terminated."""
pass
class EngineStateException(Exception):
"""Unexpected engine state."""
pass
class Option(collections.namedtuple("Option", "name type default min max var")):
"""Information about an available option for an UCI engine."""
__slots__ = ()
class MockProcess(object):
def __init__(self, engine):
self.engine = engine
self._expectations = collections.deque()
self._is_dead = threading.Event()
self._std_streams_closed = False
self.engine.on_process_spawned(self)
self._send_queue = queue.Queue()
self._send_thread = threading.Thread(target=self._send_thread_target)
self._send_thread.daemon = True
self._send_thread.start()
def _send_thread_target(self):
while not self._is_dead.is_set():
line = self._send_queue.get()
if line is not None:
self.engine.on_line_received(line)
self._send_queue.task_done()
def expect(self, expectation, responses=()):
self._expectations.append((expectation, responses))
def assert_done(self):
assert not self._expectations, "pending expectations: {0}".format(self._expectations)
def assert_terminated(self):
self.assert_done()
assert self._is_dead.is_set()
def is_alive(self):
return not self._is_dead.is_set()
def terminate(self):
self._is_dead.set()
self._send_queue.put(None)
self.engine.on_terminated()
def kill(self):
self._is_dead.set()
self._send_queue.put(None)
self.engine.on_terminated()
def send_line(self, string):
assert self.is_alive()
assert self._expectations, "unexpected: {0}".format(string)
expectation, responses = self._expectations.popleft()
assert expectation == string, "expected: {0}, got {1}".format(expectation, string)
for response in responses:
self._send_queue.put(response)
def wait_for_return_code(self):
self._is_dead.wait()
return 0
def pid(self):
return None
def __repr__(self):
return "<MockProcess at {0}>".format(hex(id(self)))
class PopenProcess(object):
def __init__(self, engine, command, **kwargs):
self.engine = engine
self._receiving_thread = threading.Thread(target=self._receiving_thread_target)
self._receiving_thread.daemon = True
self._stdin_lock = threading.Lock()
self.engine.on_process_spawned(self)
popen_args = {
"stdout": subprocess.PIPE,
"stdin": subprocess.PIPE,
"bufsize": 1, # Line buffering
"universal_newlines": True,
}
popen_args.update(kwargs)
self.process = subprocess.Popen(command, **popen_args)
self._receiving_thread.start()
def _receiving_thread_target(self):
while True:
line = self.process.stdout.readline()
if not line:
# Stream closed.
break
self.engine.on_line_received(line.rstrip())
# Close file descriptors.
self.process.stdout.close()
with self._stdin_lock:
self.process.stdin.close()
# Ensure the process is terminated (not just the in/out streams).
if self.is_alive():
self.terminate()
self.wait_for_return_code()
self.engine.on_terminated()
def is_alive(self):
return self.process.poll() is None
def terminate(self):
self.process.terminate()
def kill(self):
self.process.kill()
def send_line(self, string):
with self._stdin_lock:
self.process.stdin.write(string + "\n")
self.process.stdin.flush()
def wait_for_return_code(self):
self.process.wait()
return self.process.returncode
def pid(self):
return self.process.pid
def __repr__(self):
return "<PopenProcess at {0} (pid={1})>".format(hex(id(self)), self.pid())
class SpurProcess(object):
def __init__(self, engine, shell, command):
self.engine = engine
self.shell = shell
self._stdout_buffer = []
self._result = None
self._waiting_thread = threading.Thread(target=self._waiting_thread_target)
self._waiting_thread.daemon = True
self.engine.on_process_spawned(self)
self.process = self.shell.spawn(command, store_pid=True, allow_error=True, stdout=self)
self._waiting_thread.start()
def write(self, byte):
# Interally called whenever a byte is received.
if byte == b"\r":
pass
elif byte == b"\n":
self.engine.on_line_received(b"".join(self._stdout_buffer).decode("utf-8"))
del self._stdout_buffer[:]
else:
self._stdout_buffer.append(byte)
def _waiting_thread_target(self):
self._result = self.process.wait_for_result()
self.engine.on_terminated()
def is_alive(self):
return self.process.is_running()
def terminate(self):
self.process.send_signal(signal.SIGTERM)
def kill(self):
self.process.send_signal(signal.SIGKILL)
def send_line(self, string):
self.process.stdin_write(string.encode("utf-8"))
self.process.stdin_write(b"\n")
def wait_for_return_code(self):
return self.process.wait_for_result().return_code
def pid(self):
return self.process.pid
def __repr__(self):
return "<SpurProcess at {0} (pid={1})>".format(hex(id(self)), self.pid())
class OptionMap(collections.MutableMapping):
def __init__(self, data=None, **kwargs):
self._store = dict()
if data is None:
data = {}
self.update(data, **kwargs)
def __setitem__(self, key, value):
self._store[key.lower()] = (key, value)
def __getitem__(self, key):
return self._store[key.lower()][1]
def __delitem__(self, key):
del self._store[key.lower()]
def __iter__(self):
return (casedkey for casedkey, mappedvalue in self._store.values())
def __len__(self):
return len(self._store)
def __eq__(self, other):
for key, value in self.items():
if key not in other or other[key] != value:
return False
for key, value in other.items():
if key not in self or self[key] != value:
return False
return True
def copy(self):
return type(self)(self._store.values())
def __copy__(self):
return self.copy()
def __repr__(self):
return "{0}({1})".format(type(self).__name__, dict(self.items()))
def _popen_engine(command, engine_cls, setpgrp=False, _popen_lock=threading.Lock(), **kwargs):
"""
Opens a local chess engine process.
:param engine_cls: Engine class
:param setpgrp: Open the engine process in a new process group. This will
stop signals (such as keyboards interrupts) from propagating from the
parent process. Defaults to ``False``.
"""
engine = engine_cls()
popen_args = {}
if setpgrp:
try:
# Windows.
popen_args["creationflags"] = subprocess.CREATE_NEW_PROCESS_GROUP
except AttributeError:
# Unix.
popen_args["preexec_fn"] = os.setpgrp
popen_args.update(kwargs)
# Work around a possible race condition in Python 2 subprocess module
# that can occur when concurrently opening processes.
with _popen_lock:
PopenProcess(engine, command, **popen_args)
return engine
def _spur_spawn_engine(shell, command, engine_cls):
"""
Spawns a remote engine using a `Spur`_ shell.
.. _Spur: https://pypi.python.org/pypi/spur
"""
engine = engine_cls()
SpurProcess(engine, shell, command)
return engine