-
Notifications
You must be signed in to change notification settings - Fork 11
/
fairyfishnet.py
executable file
·2501 lines (2064 loc) · 78.3 KB
/
fairyfishnet.py
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
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# This file is part of the pychess-variants fairyfishnet client.
# Copyright (C) 2016-2019 Niklas Fiekas <niklas.fiekas@backscattering.de>
# Copyright (C) 2019 Bajusz Tamás <gbtami@gmail.com>
# 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/>.
"""Distributed Fairy-Stockfish analysis for pychess-variants"""
from __future__ import print_function
from __future__ import division
import argparse
import logging
import json
import time
import random
import collections
import contextlib
import multiprocessing
import threading
import site
import struct
import sys
import os
import stat
import platform
import re
import textwrap
import getpass
import signal
import ctypes
import string
from bs4 import BeautifulSoup
import gdown
try:
import requests
except ImportError:
print("fishnet requires the 'requests' module.", file=sys.stderr)
print("Try 'pip install requests' or install python-requests from your distro packages.", file=sys.stderr)
print(file=sys.stderr)
raise
if os.name == "posix" and sys.version_info[0] < 3:
try:
import subprocess32 as subprocess
except ImportError:
import subprocess
else:
import subprocess
try:
import urlparse
except ImportError:
import urllib.parse as urlparse
try:
import configparser
except ImportError:
import ConfigParser as configparser
try:
import queue
except ImportError:
import Queue as queue
try:
from shlex import quote as shell_quote
except ImportError:
from pipes import quote as shell_quote
try:
# Python 2
input = raw_input
except NameError:
pass
try:
import pyffish as sf
sf_ok = True
try:
sf.set_option("VariantPath", "variants.ini")
except Exception:
print("No variants.ini found.", file=sys.stderr)
raise
try:
print(sf.version())
except Exception:
print("fairyfishnet requires pyffish", file=sys.stderr)
raise
except ImportError:
print("No pyffish module installed!", file=sys.stderr)
sf_ok = False
raise
try:
# Python 3
DEAD_ENGINE_ERRORS = (EOFError, IOError, BrokenPipeError)
except NameError:
# Python 2
DEAD_ENGINE_ERRORS = (EOFError, IOError)
__version__ = "1.16.42"
__author__ = "Bajusz Tamás"
__email__ = "gbtami@gmail.com"
__license__ = "GPLv3+"
DEFAULT_ENDPOINT = "https://pychess-variants.herokuapp.com/fishnet/"
STOCKFISH_RELEASES = "https://api.github.com/repos/gbtami/Fairy-Stockfish/releases/latest"
DEFAULT_THREADS = 3
HASH_MIN = 16
HASH_DEFAULT = 256
HASH_MAX = 512
MAX_BACKOFF = 30.0
MAX_FIXED_BACKOFF = 3.0
HTTP_TIMEOUT = 15.0
STAT_INTERVAL = 60.0
DEFAULT_CONFIG = "fishnet.ini"
PROGRESS_REPORT_INTERVAL = 5.0
CHECK_PYPI_CHANCE = 0.01
LVL_SKILL = [-4, 0, 3, 6, 10, 14, 16, 18, 20]
LVL_MOVETIMES = [50, 50, 100, 150, 200, 300, 400, 500, 1000]
LVL_DEPTHS = [1, 1, 1, 2, 3, 5, 8, 13, 22]
NNUE_NET = {}
NNUE_ALIAS = {
"cambodian": "makruk",
"chess": "nn",
"placement": "nn",
}
required_variants = set([
"ataxx",
"chess",
"crazyhouse",
"placement",
"atomic",
"makruk",
"makpong",
"cambodian",
"sittuyin",
"asean",
"shogi",
"minishogi",
"kyotoshogi",
"dobutsu",
"gorogoroplus",
"torishogi",
"cannonshogi",
"xiangqi",
"manchu",
"janggi",
"minixiangqi",
"capablanca",
"capahouse",
"seirawan",
"shouse",
"grand",
"grandhouse",
"shogun",
"shako",
"hoppelpoppel",
"orda",
"synochess",
"shinobi",
"shinobiplus",
"empire",
"ordamirror",
"chak",
"chennis",
"duck",
"spartan",
"kingofthehill",
"3check",
"mansindam",
"haganeshogi",
"dragon",
"khans",
"antichess",
"racingkings",
"horde",
"shatranj",
])
def intro():
return r"""
. _________ . .
. (.. \_ , |\ /|
. \ O \ /| \ \/ /
. \______ \/ | \ / _____ _ _ _ _ _
. vvvv\ \ | / | | ___(_)___| |__ | \ | | ___| |_
. \^^^^ == \_/ | | |_ | / __| '_ \| \| |/ _ \ __|
. `\_ === \. | | _| | \__ \ | | | |\ | __/ |_
. / /\_ \ / | |_| |_|___/_| |_|_| \_|\___|\__| %s
. |/ \_ \| /
. \________/ Distributed Fairy-Stockfish analysis for pychess-variants
""".lstrip() % __version__
PROGRESS = 15
ENGINE = 5
logging.addLevelName(PROGRESS, "PROGRESS")
logging.addLevelName(ENGINE, "ENGINE")
class LogFormatter(logging.Formatter):
def format(self, record):
# Format message
msg = super(LogFormatter, self).format(record)
# Add level name
if record.levelno in [logging.INFO, PROGRESS]:
with_level = msg
else:
with_level = "%s: %s" % (record.levelname, msg)
# Add thread name
if record.threadName == "MainThread":
return with_level
else:
return "%s: %s" % (record.threadName, with_level)
class CollapsingLogHandler(logging.StreamHandler):
def __init__(self, stream=sys.stdout):
super(CollapsingLogHandler, self).__init__(stream)
self.last_level = logging.INFO
self.last_len = 0
def emit(self, record):
try:
if self.last_level == PROGRESS:
if record.levelno == PROGRESS:
self.stream.write("\r")
else:
self.stream.write("\n")
msg = self.format(record)
if record.levelno == PROGRESS:
self.stream.write(msg.ljust(self.last_len))
self.last_len = max(len(msg), self.last_len)
else:
self.last_len = 0
self.stream.write(msg)
self.stream.write("\n")
self.last_level = record.levelno
self.flush()
except Exception:
self.handleError(record)
class TailLogHandler(logging.Handler):
def __init__(self, capacity, max_level, flush_level, target_handler):
super(TailLogHandler, self).__init__()
self.buffer = collections.deque(maxlen=capacity)
self.max_level = max_level
self.flush_level = flush_level
self.target_handler = target_handler
def emit(self, record):
if record.levelno < self.max_level:
self.buffer.append(record)
if record.levelno >= self.flush_level:
while self.buffer:
record = self.buffer.popleft()
self.target_handler.handle(record)
class CensorLogFilter(logging.Filter):
def __init__(self, keyword):
self.keyword = keyword
def censor(self, msg):
try:
# Python 2
if not isinstance(msg, basestring):
return msg
except NameError:
# Python 3
if not isinstance(msg, str):
return msg
if self.keyword:
return msg.replace(self.keyword, "*" * len(self.keyword))
else:
return msg
def filter(self, record):
record.msg = self.censor(record.msg)
record.args = tuple(self.censor(arg) for arg in record.args)
return True
def setup_logging(verbosity, stream=sys.stdout):
logger = logging.getLogger()
logger.setLevel(ENGINE)
handler = logging.StreamHandler(stream)
if verbosity >= 3:
handler.setLevel(ENGINE)
elif verbosity >= 2:
handler.setLevel(logging.DEBUG)
elif verbosity >= 1:
handler.setLevel(PROGRESS)
else:
if stream.isatty():
handler = CollapsingLogHandler(stream)
handler.setLevel(PROGRESS)
else:
handler.setLevel(logging.INFO)
if verbosity < 2:
logging.getLogger("urllib3").setLevel(logging.WARNING)
logging.getLogger("requests.packages.urllib3").setLevel(logging.WARNING)
tail_target = logging.StreamHandler(stream)
tail_target.setFormatter(LogFormatter())
logger.addHandler(TailLogHandler(35, handler.level, logging.ERROR, tail_target))
handler.setFormatter(LogFormatter())
logger.addHandler(handler)
def base_url(url):
url_info = urlparse.urlparse(url)
return "%s://%s/" % (url_info.scheme, url_info.hostname)
class ConfigError(Exception):
pass
class UpdateRequired(Exception):
pass
class Shutdown(Exception):
pass
class ShutdownSoon(Exception):
pass
class SignalHandler(object):
def __init__(self):
self.ignore = False
signal.signal(signal.SIGTERM, self.handle_term)
signal.signal(signal.SIGINT, self.handle_int)
try:
signal.signal(signal.SIGUSR1, self.handle_usr1)
except AttributeError:
# No SIGUSR1 on Windows
pass
def handle_int(self, signum, frame):
if not self.ignore:
self.ignore = True
raise ShutdownSoon()
def handle_term(self, signum, frame):
if not self.ignore:
self.ignore = True
raise Shutdown()
def handle_usr1(self, signum, frame):
if not self.ignore:
self.ignore = True
raise UpdateRequired()
def open_process(command, cwd=None, shell=True, _popen_lock=threading.Lock()):
kwargs = {
"shell": shell,
"stdout": subprocess.PIPE,
"stderr": subprocess.STDOUT,
"stdin": subprocess.PIPE,
"bufsize": 1, # Line buffered
"universal_newlines": True,
}
if cwd is not None:
kwargs["cwd"] = cwd
# Prevent signal propagation from parent process
try:
# Windows
kwargs["creationflags"] = subprocess.CREATE_NEW_PROCESS_GROUP
except AttributeError:
# Unix
kwargs["preexec_fn"] = os.setpgrp
with _popen_lock: # Work around Python 2 Popen race condition
return subprocess.Popen(command, **kwargs)
def kill_process(p):
try:
# Windows
p.send_signal(signal.CTRL_BREAK_EVENT)
except AttributeError:
# Unix
os.killpg(p.pid, signal.SIGKILL)
p.communicate()
def send(p, line):
logging.log(ENGINE, "%s << %s", p.pid, line)
p.stdin.write(line + "\n")
p.stdin.flush()
def recv(p):
while True:
line = p.stdout.readline()
if line == "":
raise EOFError()
line = line.rstrip()
logging.log(ENGINE, "%s >> %s", p.pid, line)
if line:
return line
def recv_uci(p):
command_and_args = recv(p).split(None, 1)
if len(command_and_args) == 1:
return command_and_args[0], ""
elif len(command_and_args) == 2:
return command_and_args
def uci(p):
send(p, "uci")
engine_info = {}
variants = set()
while True:
command, arg = recv_uci(p)
if command == "uciok":
return engine_info, variants
elif command == "id":
name_and_value = arg.split(None, 1)
if len(name_and_value) == 2:
engine_info[name_and_value[0]] = name_and_value[1]
elif command == "option":
if arg.startswith("name UCI_Variant type combo default chess"):
for variant in arg.split(" ")[6:]:
if variant != "var":
variants.add(variant)
elif command == "Fairy-Stockfish" and " by " in arg:
# Ignore identification line
pass
else:
logging.warning("Unexpected engine response to uci: %s %s", command, arg)
def isready(p):
send(p, "isready")
while True:
command, arg = recv_uci(p)
if command == "readyok":
break
elif command == "info" and arg.startswith("string "):
pass
else:
logging.warning("Unexpected engine response to isready: %s %s", command, arg)
def setoption(p, name, value):
if value is True:
value = "true"
elif value is False:
value = "false"
elif value is None:
value = "none"
send(p, "setoption name %s value %s" % (name, value))
def go(p, position, moves, movetime=None, clock=None, depth=None, nodes=None, variant=None, chess960=False):
send(p, "position fen %s moves %s" % (position, " ".join(moves)))
builder = []
builder.append("go")
if movetime is not None:
builder.append("movetime")
builder.append(str(movetime))
if depth is not None:
builder.append("depth")
builder.append(str(depth))
if nodes is not None:
builder.append("nodes")
builder.append(str(nodes))
if clock is not None:
builder.append("wtime")
builder.append(str(clock["wtime"] * 10))
builder.append("btime")
builder.append(str(clock["btime"] * 10))
builder.append("winc")
builder.append(str(clock["inc"] * 1000))
builder.append("binc")
builder.append(str(clock["inc"] * 1000))
send(p, " ".join(builder))
info = {}
info["bestmove"] = None
while True:
command, arg = recv_uci(p)
if command == "bestmove":
bestmove = arg.split()[0]
if bestmove and bestmove != "(none)":
info["bestmove"] = bestmove
return info
elif command == "info":
arg = arg or ""
# Parse all other parameters
score_kind, score_value, lowerbound, upperbound = None, None, False, False
current_parameter = None
for token in arg.split(" "):
if current_parameter == "string":
# Everything until the end of line is a string
if "string" in info:
info["string"] += " " + token
else:
info["string"] = token
elif token == "score":
current_parameter = "score"
elif token == "pv":
current_parameter = "pv"
if info.get("multipv", 1) == 1:
info.pop("pv", None)
elif token in ["depth", "seldepth", "time", "nodes", "multipv",
"currmove", "currmovenumber",
"hashfull", "nps", "tbhits", "cpuload",
"refutation", "currline", "string"]:
current_parameter = token
info.pop(current_parameter, None)
elif current_parameter in ["depth", "seldepth", "time",
"nodes", "currmovenumber",
"hashfull", "nps", "tbhits",
"cpuload", "multipv"]:
# Integer parameters
info[current_parameter] = int(token)
elif current_parameter == "score":
# Score
if token in ["cp", "mate"]:
score_kind = token
score_value = None
elif token == "lowerbound":
lowerbound = True
elif token == "upperbound":
upperbound = True
else:
score_value = int(token)
elif current_parameter != "pv" or info.get("multipv", 1) == 1:
# Strings
if current_parameter in info:
info[current_parameter] += " " + token
else:
info[current_parameter] = token
# Set score. Prefer scores that are not just a bound
if score_kind and score_value is not None and (not (lowerbound or upperbound) or "score" not in info or info["score"].get("lowerbound") or info["score"].get("upperbound")):
info["score"] = {score_kind: score_value}
if lowerbound:
info["score"]["lowerbound"] = lowerbound
if upperbound:
info["score"]["upperbound"] = upperbound
else:
logging.warning("Unexpected engine response to go: %s %s", command, arg)
def set_variant_options(p, variant, chess960, nnue):
variant = variant.lower()
setoption(p, "UCI_Chess960", chess960)
if (variant in NNUE_NET or variant in NNUE_ALIAS) and nnue:
vari = NNUE_ALIAS[variant] if variant in NNUE_ALIAS else variant
eval_file = "%s-%s.nnue" % (vari, NNUE_NET.get(vari, ""))
if os.path.isfile(eval_file):
setoption(p, "EvalFile", eval_file)
if variant in ["standard", "fromposition", "chess960"]:
setoption(p, "UCI_Variant", "chess")
else:
setoption(p, "UCI_Variant", variant)
class ProgressReporter(threading.Thread):
def __init__(self, queue_size, conf):
super(ProgressReporter, self).__init__()
self.http = requests.Session()
self.conf = conf
self.queue = queue.Queue(maxsize=queue_size)
self._poison_pill = object()
def send(self, job, result):
path = "analysis/%s" % job["work"]["id"]
data = json.dumps(result).encode("utf-8")
try:
self.queue.put_nowait((path, data))
except queue.Full:
logging.debug("Could not keep up with progress reports. Dropping one.")
def stop(self):
while not self.queue.empty():
self.queue.get_nowait()
self.queue.put(self._poison_pill)
def run(self):
while True:
item = self.queue.get()
if item == self._poison_pill:
return
path, data = item
try:
response = self.http.post(get_endpoint(self.conf, path),
data=data,
timeout=HTTP_TIMEOUT)
if response.status_code == 429:
logging.error("Too many requests. Suspending progress reports for 60s ...")
time.sleep(60.0)
elif response.status_code != 204:
logging.error("Expected status 204 for progress report, got %d", response.status_code)
except requests.RequestException as err:
logging.warning("Could not send progress report (%s). Continuing.", err)
class Worker(threading.Thread):
def __init__(self, conf, threads, memory, progress_reporter):
super(Worker, self).__init__()
self.conf = conf
self.threads = threads
self.memory = memory
self.progress_reporter = progress_reporter
self.alive = True
self.fatal_error = None
self.finished = threading.Event()
self.sleep = threading.Event()
self.status_lock = threading.RLock()
self.nodes = 0
self.positions = 0
self.stockfish_lock = threading.RLock()
self.stockfish = None
self.stockfish_info = None
self.job = None
self.backoff = start_backoff(self.conf)
self.http = requests.Session()
self.http.mount("http://", requests.adapters.HTTPAdapter(max_retries=1))
self.http.mount("https://", requests.adapters.HTTPAdapter(max_retries=1))
def set_name(self, name):
self.name = name
self.progress_reporter.name = "%s (P)" % (name, )
def stop(self):
with self.status_lock:
self.alive = False
self.kill_stockfish()
self.sleep.set()
def stop_soon(self):
with self.status_lock:
self.alive = False
self.sleep.set()
def is_alive(self):
with self.status_lock:
return self.alive
def run(self):
try:
while self.is_alive():
self.run_inner()
except UpdateRequired as error:
self.fatal_error = error
except Exception as error:
self.fatal_error = error
logging.exception("Fatal error in worker")
finally:
self.finished.set()
def run_inner(self):
try:
# Check if the engine is still alive and start, if necessary
self.start_stockfish()
# Do the next work unit
path, request = self.work()
except DEAD_ENGINE_ERRORS:
alive = self.is_alive()
if alive:
t = next(self.backoff)
logging.exception("Engine process has died. Backing off %0.1fs", t)
# Abort current job
self.abort_job()
if alive:
self.sleep.wait(t)
self.kill_stockfish()
return
try:
# Report result and fetch next job
response = self.http.post(get_endpoint(self.conf, path),
json=request,
timeout=HTTP_TIMEOUT)
except requests.RequestException as err:
self.job = None
t = next(self.backoff)
logging.error("Backing off %0.1fs after failed request (%s)", t, err)
self.sleep.wait(t)
else:
if response.status_code == 204:
self.job = None
t = next(self.backoff)
logging.debug("No job found. Backing off %0.1fs", t)
self.sleep.wait(t)
elif response.status_code == 202:
logging.debug("Got job: %s", response.text)
self.job = response.json()
self.backoff = start_backoff(self.conf)
elif 500 <= response.status_code <= 599:
self.job = None
t = next(self.backoff)
logging.error("Server error: HTTP %d %s. Backing off %0.1fs", response.status_code, response.reason, t)
self.sleep.wait(t)
elif 400 <= response.status_code <= 499:
self.job = None
t = next(self.backoff) + (60 if response.status_code == 429 else 0)
try:
logging.debug("Client error: HTTP %d %s: %s", response.status_code, response.reason, response.text)
error = response.json()["error"]
logging.error(error)
if "Please restart fishnet to upgrade." in error:
logging.error("Stopping worker for update.")
raise UpdateRequired()
except (KeyError, ValueError):
logging.error("Client error: HTTP %d %s. Backing off %0.1fs. Request was: %s",
response.status_code, response.reason, t, json.dumps(request))
self.sleep.wait(t)
else:
self.job = None
t = next(self.backoff)
logging.error("Unexpected HTTP status for acquire: %d", response.status_code)
self.sleep.wait(t)
def abort_job(self):
if self.job is None:
return
logging.debug("Aborting job %s", self.job["work"]["id"])
try:
response = requests.post(get_endpoint(self.conf, "abort/%s" % self.job["work"]["id"]),
data=json.dumps(self.make_request()),
timeout=HTTP_TIMEOUT)
if response.status_code == 204:
logging.info("Aborted job %s", self.job["work"]["id"])
else:
logging.error("Unexpected HTTP status for abort: %d", response.status_code)
except requests.RequestException:
logging.exception("Could not abort job. Continuing.")
self.job = None
def kill_stockfish(self):
with self.stockfish_lock:
if self.stockfish:
try:
kill_process(self.stockfish)
except OSError:
logging.exception("Failed to kill engine process.")
self.stockfish = None
def start_stockfish(self):
with self.stockfish_lock:
# Check if already running.
if self.stockfish and self.stockfish.poll() is None:
return
# Start process
self.stockfish = open_process(get_stockfish_command(self.conf, False),
get_engine_dir(self.conf))
self.stockfish_info, _ = uci(self.stockfish)
self.stockfish_info.pop("author", None)
logging.info("Started %s, threads: %s (%d), pid: %d",
self.stockfish_info.get("name", "Stockfish <?>"),
"+" * self.threads, self.threads, self.stockfish.pid)
# Prepare UCI options
self.stockfish_info["options"] = {}
self.stockfish_info["options"]["threads"] = str(self.threads)
self.stockfish_info["options"]["hash"] = str(self.memory)
# Custom options
if self.conf.has_section("Stockfish"):
for name, value in self.conf.items("Stockfish"):
self.stockfish_info["options"][name] = value
# Add .nnue file list
self.stockfish_info["nnue"] = ["%s-%s.nnue" % (v, NNUE_NET[v]) for v in NNUE_NET]
# Set UCI options
for name, value in self.stockfish_info["options"].items():
setoption(self.stockfish, name, value)
isready(self.stockfish)
def make_request(self):
return {
"fishnet": {
"version": __version__,
"python": platform.python_version(),
"apikey": get_key(self.conf),
},
"stockfish": self.stockfish_info,
}
def work(self):
result = self.make_request()
if self.job and self.job["work"]["type"] == "analysis":
result = self.analysis(self.job)
return "analysis" + "/" + self.job["work"]["id"], result
elif self.job and self.job["work"]["type"] == "move":
result = self.bestmove(self.job)
return "move" + "/" + self.job["work"]["id"], result
else:
if self.job:
logging.error("Invalid job type: %s", self.job["work"]["type"])
return "acquire", result
def job_name(self, job, ply=None):
builder = []
if job.get("game_id"):
builder.append(base_url(get_endpoint(self.conf)))
builder.append(job["game_id"])
else:
builder.append(job["work"]["id"])
if ply is not None:
builder.append("#")
builder.append(str(ply))
return "".join(builder)
def bestmove(self, job):
lvl = job["work"]["level"]
variant = job.get("variant", "standard")
chess960 = job.get("chess960", False)
moves = job["moves"].split(" ")
nnue = job.get("nnue", True)
logging.debug("Playing %s (%s) with lvl %d",
self.job_name(job), variant, lvl)
set_variant_options(self.stockfish, variant, chess960, nnue)
setoption(self.stockfish, "Skill Level", LVL_SKILL[lvl])
setoption(self.stockfish, "UCI_AnalyseMode", False)
send(self.stockfish, "ucinewgame")
isready(self.stockfish)
movetime = int(round(LVL_MOVETIMES[lvl] / (self.threads * 0.9 ** (self.threads - 1))))
start = time.time()
part = go(self.stockfish, job["position"], moves,
movetime=movetime, clock=job["work"].get("clock"),
depth=LVL_DEPTHS[lvl], variant=variant, chess960=chess960)
end = time.time()
logging.log(PROGRESS, "Played move in %s (%s) with lvl %d: %0.3fs elapsed, depth %d",
self.job_name(job), variant,
lvl, end - start, part.get("depth", 0))
self.nodes += part.get("nodes", 0)
self.positions += 1
result = self.make_request()
result["move"] = {
"bestmove": part["bestmove"],
}
return result
def analysis(self, job):
variant = job.get("variant", "standard")
chess960 = job.get("chess960", False)
moves = job["moves"].split(" ")
nnue = job.get("nnue", True)
result = self.make_request()
result["analysis"] = [None for _ in range(len(moves) + 1)]
start = last_progress_report = time.time()
set_variant_options(self.stockfish, variant, chess960, nnue)
setoption(self.stockfish, "Skill Level", 20)
setoption(self.stockfish, "UCI_AnalyseMode", True)
send(self.stockfish, "ucinewgame")
isready(self.stockfish)
nodes = job.get("nodes") or 3500000
skip = job.get("skipPositions", [])
num_positions = 0
for ply in range(len(moves), -1, -1):
if ply in skip:
result["analysis"][ply] = {"skipped": True}
continue
if last_progress_report + PROGRESS_REPORT_INTERVAL < time.time():
if self.progress_reporter:
self.progress_reporter.send(job, result)
last_progress_report = time.time()
logging.log(PROGRESS, "Analysing %s: %s",
variant, self.job_name(job, ply))
part = go(self.stockfish, job["position"], moves[0:ply],
nodes=nodes, movetime=4000, variant=variant, chess960=chess960)
if "mate" not in part["score"] and "time" in part and part["time"] < 100:
logging.warning("Very low time reported: %d ms.", part["time"])
if "nps" in part and part["nps"] >= 100000000:
logging.warning("Dropping exorbitant nps: %d", part["nps"])
del part["nps"]
self.nodes += part.get("nodes", 0)
self.positions += 1
num_positions += 1
result["analysis"][ply] = part
end = time.time()
if num_positions:
logging.info("%s took %0.1fs (%0.2fs per position)",
self.job_name(job),
end - start, (end - start) / num_positions)
else:
logging.info("%s done (nothing to do)", self.job_name(job))
return result
def detect_cpu_capabilities():
# Detects support for popcnt and pext instructions
vendor, modern, bmi2 = "", False, False
# Run cpuid in subprocess for robustness in case of segfaults