-
Notifications
You must be signed in to change notification settings - Fork 127
/
worker.py
1423 lines (1240 loc) · 45.1 KB
/
worker.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 python3
import atexit
import base64
import datetime
import getpass
import glob
import hashlib
import math
import multiprocessing
import os
import platform
import random
import re
import signal
import stat
import subprocess
import sys
import threading
import time
import traceback
import uuid
import shutil
import zlib
from argparse import ArgumentDefaultsHelpFormatter, ArgumentParser
from configparser import ConfigParser
from contextlib import ExitStack
from functools import partial
from zipfile import ZipFile
# Try to import the system wide package (eg requests).
# Fall back to the local one if the global one does not exist.
packages_dir = os.path.join(os.path.dirname(os.path.realpath(__file__)), "packages")
sys.path.append(packages_dir)
# Several packages are called "expression".
# So we make sure to use the locally installed one.
import packages.expression as expression
import requests
from games import (
EXE_SUFFIX,
FatalException,
RunException,
WorkerException,
backup_log,
download_from_github,
format_return_code,
log,
run_games,
send_api_post_request,
str_signal,
)
from updater import update
WORKER_VERSION = 173
HTTP_TIMEOUT = 30.0
INITIAL_RETRY_TIME = 15.0
THREAD_JOIN_TIMEOUT = 15.0
MAX_RETRY_TIME = 900.0 # 15 minutes
IS_WINDOWS = "windows" in platform.system().lower()
IS_MACOS = "darwin" in platform.system().lower()
IS_COLAB = False
try:
import google.colab
IS_COLAB = True
del google.colab
except:
pass
CONFIGFILE = "fishtest.cfg"
LOGO = r"""
______ _ _ _ _ _
| ___(_) | | | | | | | |
| |_ _ ___| |__ | |_ ___ ___| |_ __ _____ _ __| | _____ _ __
| _| | / __| '_ \| __/ _ \/ __| __| \ \ /\ / / _ \| '__| |/ / _ \ '__|
| | | \__ \ | | | || __/\__ \ |_ \ V V / (_) | | | < __/ |
\_| |_|___/_| |_|\__\___||___/\__| \_/\_/ \___/|_| |_|\_\___|_|
"""
"""
Bird's eye view of the worker
=============================
The main control flow of the worker
is as follows:
worker.py : worker()
worker.py : fetch_and_handle_task() [in loop]
games.py : run_games()
games.py : launch_cutechess() [in loop for spsa]
games.py : parse_cutechess_output()
Apis used by the worker
=======================
<fishtest> = https://tests.stockfishchess.org
<github> = https://api.github.com
<github-books> = <github>/repos/official-stockfish/books
Heartbeat <fishtest>/api/beat POST
Setup task <github>/rate_limit GET
<fishtest>/api/request_version POST
<fishtest>/api/request_task POST
<fishtest>/api/nn/<nnue> GET
<github-books>/git/trees/master GET
<github-books>/git/trees/master/blobs/<sha-cutechess-cli> GET
<github-books>/git/trees/master/blobs/<sha-book> GET
<github>/repos/<user-repo>/zipball/<sha> GET
Main loop <fishtest>/api/update_task POST
<fishtest>/api/request_spsa POST
Finish task <fishtest>/api/failed_task POST
<fishtest>/api/stop_run POST
<fishtest>/api/upload_pgn POST
The POST requests are json encoded. For the shape of a valid request, consult
"api.py" in the Fishtest source.
The POST requests return a json encoded dictionary. It may contain a key "error".
In that case the corresponding value is an error message.
"""
def _bool(x):
x = x.strip().lower()
if x in {"true", "1"}:
return True
if x in {"false", "0"}:
return False
raise ValueError(x)
_bool.__name__ = "bool"
def _alpha_numeric(x):
x = x.strip()
if x == "_hw":
return x
if len(x) <= 1:
print("The prefix {} is too short".format(x))
raise ValueError(x)
if not all(ord(c) < 128 for c in x) or not x.isalnum():
raise ValueError(x)
return x[:8]
_alpha_numeric.__name__ = "alphanumeric"
class _memory:
def __init__(self, MAX):
self.MAX = MAX
self.__name__ = "memory"
def __call__(self, x):
e = expression.Expression_Parser(
variables={"MAX": self.MAX}, functions={"min": min, "max": max}
)
try:
ret = round(max(min(e.parse(x), self.MAX), 0))
except:
print("Unable to parse expression for max_memory")
raise ValueError(x)
return x, ret
class _concurrency:
def __init__(self, MAX):
self.MAX = MAX
self.__name__ = "concurrency"
def __call__(self, x):
e = expression.Expression_Parser(
variables={"MAX": self.MAX}, functions={"min": min, "max": max}
)
try:
ret = round(e.parse(x))
except:
print("Unable to parse expression for concurrency")
raise ValueError(x)
if ret <= 0:
print("concurrency must be at least 1")
raise ValueError(x)
if ("MAX" not in x and ret >= self.MAX) or ret > self.MAX:
print(
(
"\nYou cannot have concurrency {} but at most:\n"
" a) {} with '--concurrency MAX';\n"
" b) {} otherwise.\n"
"Please use option a) only if your computer is very lightly loaded.\n"
).format(
ret,
self.MAX,
self.MAX - 1,
)
)
raise ValueError(x)
return x, ret
def safe_sleep(f):
try:
time.sleep(f)
except:
print("\nSleep interrupted...")
def verify_credentials(remote, username, password, cached):
# Returns:
# True : username/password are ok
# False : username/password are not ok
# None : network error: unable to determine the status of
# username/password
req = {}
if username != "" and password != "":
print(
"Confirming {} credentials with {}".format(
"cached" if cached else "supplied", remote
)
)
payload = {"worker_info": {"username": username}, "password": password}
try:
req = send_api_post_request(
remote + "/api/request_version", payload, quiet=True
)
except:
return None # network problem (unrecoverable)
if "error" in req:
return False # invalid username/password
print("Credentials ok!")
return True
return False # empty username or password
def get_credentials(config, options, args):
remote = "{}://{}:{}".format(options.protocol, options.host, options.port)
print("Worker version {} connecting to {}".format(WORKER_VERSION, remote))
username = config.get("login", "username")
password = config.get("login", "password", raw=True)
cached = True
if len(args) == 2:
username = args[0]
password = args[1]
cached = False
if options.no_validation:
return username, password
ret = verify_credentials(remote, username, password, cached)
if ret is None:
return "", ""
elif not ret:
try:
print("")
username = input("Username: ")
if username != "":
password = getpass.getpass()
print("")
except:
print("\n")
return "", ""
else:
if not verify_credentials(remote, username, password, False):
return "", ""
return username, password
def verify_required_cutechess(testing_dir, cutechess):
cutechess = os.path.join(testing_dir, cutechess)
print("Obtaining version info for {} ...".format(cutechess))
if not os.path.exists(cutechess):
print("{} does not exist ...".format(cutechess))
return False
try:
with subprocess.Popen(
[cutechess, "--version"],
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
universal_newlines=True,
bufsize=1,
close_fds=not IS_WINDOWS,
) as p:
errors = p.stderr.read()
pattern = re.compile("cutechess-cli ([0-9]*).([0-9]*).([0-9]*)")
major, minor, patch = 0, 0, 0
for line in iter(p.stdout.readline, ""):
m = pattern.search(line)
if m:
print("Found: ", line.strip())
major = int(m.group(1))
minor = int(m.group(2))
patch = int(m.group(3))
except (OSError, subprocess.SubprocessError) as e:
print("Unable to run cutechess-cli. Error: {}".format(str(e)))
return False
if p.returncode != 0:
print(
"Unable to run cutechess-cli. Return code: {}. Error: {}".format(
format_return_code(p.returncode), errors
)
)
return False
if major + minor + patch == 0:
print("Unable to find the version of cutechess-cli.")
return False
if (major, minor) < (1, 2):
print("Requires cutechess 1.2 or higher, found version doesn't match")
return False
return True
def setup_cutechess():
# Create the testing directory if missing.
worker_dir = os.path.dirname(os.path.realpath(__file__))
testing_dir = os.path.join(worker_dir, "testing")
if not os.path.exists(testing_dir):
os.makedirs(testing_dir)
try:
os.chdir(testing_dir)
except Exception as e:
print("Unable to enter {}. Error: {}".format(testing_dir, str(e)))
return False
cutechess = "cutechess-cli" + EXE_SUFFIX
if not verify_required_cutechess(testing_dir, cutechess):
if len(EXE_SUFFIX) > 0:
zipball = "cutechess-cli-win.zip"
elif IS_MACOS:
zipball = "cutechess-cli-macos-64bit.zip"
else:
zipball = "cutechess-cli-linux-{}.zip".format(platform.architecture()[0])
try:
download_from_github(zipball, testing_dir)
with ZipFile(zipball) as zip_file:
zip_file.extractall()
os.remove(zipball)
os.chmod(cutechess, os.stat(cutechess).st_mode | stat.S_IEXEC)
except Exception as e:
print(
"Exception downloading or extracting {}:\n".format(zipball),
e,
sep="",
file=sys.stderr,
)
# Verify that cutechess is working and has the required minimum version.
if not verify_required_cutechess(testing_dir, cutechess):
print(
"The downloaded cutechess-cli is not working. Trying to restore a backup copy ..."
)
bkp_cutechess_clis = sorted(
glob.glob(os.path.join(worker_dir, "_testing_*", cutechess)),
key=os.path.getctime,
)
if bkp_cutechess_clis:
bkp_cutechess_cli = bkp_cutechess_clis[-1]
try:
shutil.copy(bkp_cutechess_cli, testing_dir)
except Exception as e:
print(
"Unable to copy {} to {}. Error: {}".format(
bkp_cutechess_cli, testing_dir, str(e)
)
)
if not verify_required_cutechess(testing_dir, cutechess):
print(
"The backup copy {} doesn't work either ...".format(
bkp_cutechess_cli
)
)
print("No suitable cutechess-cli found")
return False
else:
print("No backup copy found")
print("No suitable cutechess-cli found")
return False
return True
def validate(config, schema):
for v in schema:
if not config.has_section(v[0]):
config.add_section(v[0])
if not config.has_option(v[0], v[1]):
config.set(*v[:3])
else:
o = config.get(v[0], v[1])
if callable(v[4]): # prepocessor
o1 = v[4](o)
if o1 != o:
print(
"Replacing the value '{}' of config option '{}' by '{}'".format(
o, v[1], o1
)
)
config.set(v[0], v[1], o1)
o = o1
t = v[3] # type
if callable(t):
try:
_ = t(o)
except:
# v[2] is the default
print(
"The value '{}' of config option '{}' is not of type '{}'.\n"
"Replacing it by the default value '{}'".format(
o, v[1], v[3].__name__, v[2]
)
)
config.set(*v[:3])
elif o not in t: # choices
print(
"The value '{}' of config option '{}' is not in {}.\n"
"Replacing it by the default value '{}'".format(o, v[1], v[3], v[2])
)
config.set(*v[:3])
# cleanup
schema_sections = [v[0] for v in schema]
schema_options = [v[:2] for v in schema]
for section in config.sections():
if section not in schema_sections:
print("Removing unknown config section '{}'".format(section))
config.remove_section(section)
continue
for option in config.options(section):
if (section, option) not in schema_options:
print("Removing unknown config option '{}'".format(option))
config.remove_option(section, option)
def setup_parameters(worker_dir):
# Step 1: read the config file if it exists.
config = ConfigParser(inline_comment_prefixes=";", interpolation=None)
config_file = os.path.join(worker_dir, CONFIGFILE)
try:
config.read(config_file)
except Exception as e:
print(
"Exception reading configfile {}:\n".format(config_file),
e,
sep="",
file=sys.stderr,
)
print("Initializing configfile")
config = ConfigParser(inline_comment_prefixes=";", interpolation=None)
# Step 2: probe the host system.
# Step 2a: determine the amount of available memory.
mem = 0
system_type = platform.system().lower()
try:
if "linux" in system_type:
cmd = "free -b"
elif "windows" in system_type:
cmd = (
"powershell (Get-CimInstance Win32_OperatingSystem)"
".TotalVisibleMemorySize*1024"
)
elif "darwin" in system_type:
cmd = "sysctl hw.memsize"
else:
cmd = ""
print("Unknown system")
with os.popen(cmd) as proc:
mem_str = str(proc.readlines())
mem = int(re.search(r"\d+", mem_str).group())
except Exception as e:
print("Exception checking HW info:\n", e, sep="", file=sys.stderr)
return None
# Step 2b: determine the number of cores.
max_cpu_count = 0
try:
max_cpu_count = multiprocessing.cpu_count()
except Exception as e:
print("Exception checking the CPU cores count:\n", e, sep="", file=sys.stderr)
return None
# Step 2c: detect the available compilers.
compilers = detect_compilers()
if compilers == {}:
print("No usable compilers found")
return None
# Step 3: validate config options and replace missing or invalid
# ones by defaults.
compiler_names = list(compilers.keys())
if "g++" not in compiler_names:
default_compiler = compiler_names[0]
else:
default_compiler = "g++"
schema = [
# (<section>, <option>, <default>, <type>, <preprocessor>),
("login", "username", "", str, None),
("login", "password", "", str, None),
("parameters", "protocol", "https", ["http", "https"], None),
("parameters", "host", "tests.stockfishchess.org", str, None),
("parameters", "port", "443", int, None),
(
"parameters",
"concurrency",
"max(1,min(3,MAX-1))",
_concurrency(MAX=max_cpu_count),
None,
),
(
"parameters",
"max_memory",
"MAX/2",
_memory(MAX=mem / 1024 / 1024),
None,
),
("parameters", "uuid_prefix", "_hw", _alpha_numeric, None),
("parameters", "min_threads", "1", int, None),
("parameters", "fleet", "False", _bool, None),
("parameters", "compiler", default_compiler, compiler_names, None),
("private", "hw_seed", str(random.randint(0, 0xFFFFFFFF)), int, None),
]
validate(config, schema)
# Step 4: parse the command line. Use the current config options as defaults.
class ExplicitDefaultsHelpFormatter(ArgumentDefaultsHelpFormatter):
def _get_help_string(self, action):
if action.const:
return action.help
return super()._get_help_string(action)
parser = ArgumentParser(
usage="python worker.py [USERNAME PASSWORD] [OPTIONS]",
formatter_class=ExplicitDefaultsHelpFormatter,
)
parser.add_argument(
"-P",
"--protocol",
dest="protocol",
default=config.get("parameters", "protocol"),
choices=["http", "https"],
help="the protocol used by the server",
)
parser.add_argument(
"-n",
"--host",
dest="host",
default=config.get("parameters", "host"),
help="the hostname of the fishtest server",
)
parser.add_argument(
"-p",
"--port",
dest="port",
default=config.getint("parameters", "port"),
type=int,
help="the port of the fishtest server",
)
parser.add_argument(
"-c",
"--concurrency",
dest="concurrency_",
metavar="CONCURRENCY",
default=config.get("parameters", "concurrency"),
type=_concurrency(MAX=max_cpu_count),
help="an expression, potentially involving the variable 'MAX', "
"evaluating to the maximal number of cores that the worker will use",
)
parser.add_argument(
"-m",
"--max_memory",
dest="max_memory_",
metavar="MAX_MEMORY",
default=config.get("parameters", "max_memory"),
type=_memory(MAX=mem / 1024 / 1024),
help="an expression, potentially involving the variable 'MAX', "
"evaluating to the maximum amount of memory in MiB that the worker will use",
)
parser.add_argument(
"-u",
"--uuid_prefix",
dest="uuid_prefix",
default=config.get("parameters", "uuid_prefix"),
type=_alpha_numeric,
help="set the initial part of the UUID (_hw to use an internal algorithm), "
"if you run more than one worker, please make sure their prefixes are distinct",
)
parser.add_argument(
"-t",
"--min_threads",
dest="min_threads",
default=config.getint("parameters", "min_threads"),
type=int,
help="do not accept tasks with fewer threads than MIN_THREADS",
)
parser.add_argument(
"-f",
"--fleet",
dest="fleet",
default=config.getboolean("parameters", "fleet"),
type=_bool,
choices=[False, True], # useful for usage message
help="if 'False', quit in case of errors or if no task is available",
)
parser.add_argument(
"-C",
"--compiler",
dest="compiler_",
default=config.get("parameters", "compiler"),
type=str,
choices=compiler_names,
help="choose the compiler used by the worker",
)
parser.add_argument(
"-w",
"--only_config",
dest="only_config",
action="store_true",
help="just write the configfile and quit",
)
parser.add_argument(
"-v",
"--no_validation",
dest="no_validation",
action="store_true",
help="do not validate username/password with server",
)
def my_error(e):
raise Exception(e)
parser.error = my_error
try:
(options, args) = parser.parse_known_args()
except Exception as e:
print(str(e))
return None
if len(args) not in [0, 2]:
print("Unparsed command line arguments: {}".format(" ".join(args)))
parser.print_usage()
return None
# Step 5: fixup the config options.
options.concurrency_, options.concurrency = options.concurrency_
options.max_memory_, options.max_memory = options.max_memory_
if options.protocol == "http" and options.port == 443:
# Rewrite old port 443 to 80
print("Changing port to 80")
options.port = 80
elif options.protocol == "https" and options.port == 80:
# Rewrite old port 80 to 443
print("Changing port to 443")
options.port = 443
options.compiler = compilers[options.compiler_]
options.hw_id = hw_id(config.getint("private", "hw_seed"))
print("Default uuid_prefix: {}".format(options.hw_id))
# Step 6: determine credentials
username, password = get_credentials(config, options, args)
if username == "":
print("Invalid or missing credentials")
return None
options.username = username
options.password = password
# Step 7: write command line parameters to the config file.
config.set("login", "username", options.username)
config.set("login", "password", options.password)
config.set("parameters", "protocol", options.protocol)
config.set("parameters", "host", options.host)
config.set("parameters", "port", str(options.port))
config.set(
"parameters",
"concurrency",
options.concurrency_ + " ; = {} cores".format(options.concurrency),
)
config.set(
"parameters",
"max_memory",
options.max_memory_ + " ; = {} MiB".format(options.max_memory),
)
config.set(
"parameters",
"uuid_prefix",
options.uuid_prefix
+ (" ; = {}".format(options.hw_id) if options.uuid_prefix == "_hw" else ""),
)
config.set("parameters", "min_threads", str(options.min_threads))
config.set("parameters", "fleet", str(options.fleet))
config.set("parameters", "compiler", options.compiler_)
with open(config_file, "w") as f:
config.write(f)
# Step 8: give some feedback to the user.
print(
"System memory determined to be: {:.3f}GiB".format(mem / (1024 * 1024 * 1024))
)
print(
"Worker constraints: {{'concurrency': {}, 'max_memory': {}, 'min_threads': {}}}".format(
options.concurrency, options.max_memory, options.min_threads
)
)
print("Config file {} written".format(config_file))
return options
def on_sigint(current_state, signal, frame):
current_state["alive"] = False
raise FatalException("Terminated by signal {}".format(str_signal(signal)))
def fingerprint(s):
# A cryptographically secure hash
return int.from_bytes(
hashlib.md5(str(s).encode("utf-8")).digest()[:4], byteorder="big"
)
def read_winreg(path, name):
import winreg
views = [winreg.KEY_WOW64_64KEY, winreg.KEY_WOW64_32KEY]
value = None
for v in views:
try:
registry_key = winreg.OpenKey(
winreg.HKEY_LOCAL_MACHINE, path, 0, winreg.KEY_READ | v
)
value, regtype = winreg.QueryValueEx(registry_key, name)
winreg.CloseKey(registry_key)
break
except WindowsError:
pass
return value
def get_machine_id():
if IS_WINDOWS:
# Get windows machine_id from the registry key:
# HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Cryptography\MachineGuid
# See https://www.medo64.com/2020/04/unique-machine-id/ .
path = r"SOFTWARE\Microsoft\Cryptography"
name = "MachineGuid"
machine_id = read_winreg(path, name)
if machine_id is not None:
print(
"machine_id {} obtained from HKEY_LOCAL_MACHINE\\{}\\{}".format(
machine_id, path, name
)
)
return machine_id
elif IS_MACOS:
# https://stackoverflow.com/questions/11999886/get-machine-id-of-mac-os-x
# Somebody with a Mac should clean this code up a bit.
cmd = "ioreg -rd1 -c IOPlatformExpertDevice"
machine_uuid_str = ""
try:
with subprocess.Popen(
cmd.split(),
stdin=subprocess.DEVNULL,
stdout=subprocess.PIPE,
universal_newlines=True,
bufsize=1,
close_fds=not IS_WINDOWS,
) as p:
for line in iter(p.stdout.readline, ""):
if "UUID" not in line:
continue
if not line:
break
machine_uuid_str += line
except Exception as e:
print(
"Exception while reading the machine_id:\n",
e,
sep="",
file=sys.stderr,
)
if machine_uuid_str != "":
match_obj = re.compile(
"[A-Z,0-9]{8,8}-"
+ "[A-Z,0-9]{4,4}-"
+ "[A-Z,0-9]{4,4}-"
+ "[A-Z,0-9]{4,4}-"
+ "[A-Z,0-9]{12,12}"
)
result = match_obj.findall(machine_uuid_str)
if len(result) > 0:
machine_id = result[0]
print("machine_id {} obtained via '{}'".format(machine_id, cmd))
return machine_id
elif os.name == "posix":
host_ids = ["/etc/machine-id", "/var/lib/dbus/machine-id"]
for file in host_ids:
try:
with open(file) as f:
machine_id = f.read().strip()
print("machine_id {} obtained from {}".format(machine_id, file))
return machine_id
except:
pass
print("Unable to obtain the machine id")
return ""
def hw_id(hw_seed):
fingerprint_machine = fingerprint(get_machine_id())
fingerprint_path = fingerprint(os.path.realpath(__file__))
return format(hw_seed ^ fingerprint_machine ^ fingerprint_path, "08x")
def get_uuid(options):
if options.uuid_prefix == "_hw":
uuid_prefix = options.hw_id
else:
uuid_prefix = options.uuid_prefix
return uuid_prefix[:8] + str(uuid.uuid4())[8:]
def get_rate():
try:
rate = requests.get(
"https://api.github.com/rate_limit", timeout=HTTP_TIMEOUT
).json()["resources"]["core"]
except Exception as e:
print("Exception fetching rate_limit:\n", e, sep="", file=sys.stderr)
rate = {"remaining": 0, "limit": 5000}
return rate, False
remaining = rate["remaining"]
print("API call rate limits:", rate)
return rate, remaining < math.sqrt(rate["limit"])
def gcc_version():
"""Parse the output of g++ -E -dM -"""
try:
with subprocess.Popen(
["g++", "-E", "-dM", "-"],
stdin=subprocess.DEVNULL,
stdout=subprocess.PIPE,
universal_newlines=True,
bufsize=1,
close_fds=not IS_WINDOWS,
) as p:
for line in iter(p.stdout.readline, ""):
if "__clang_major__" in line:
print("clang++ poses as g++")
return None
if "__GNUC__" in line:
major = line.split()[2]
if "__GNUC_MINOR__" in line:
minor = line.split()[2]
if "__GNUC_PATCHLEVEL__" in line:
patchlevel = line.split()[2]
except (OSError, subprocess.SubprocessError):
print("No g++ or g++ is not executable")
return None
if p.returncode != 0:
print("g++ version query failed with return code {}".format(p.returncode))
return None
try:
major = int(major)
minor = int(minor)
patchlevel = int(patchlevel)
compiler = "g++"
except:
print("Failed to parse g++ version.")
return None
if (major, minor) < (7, 3):
print(
"Found g++ version {}.{}.{}. First usable version is 7.3.0.".format(
major, minor, patchlevel
)
)
return None
print("Found {} version {}.{}.{}".format(compiler, major, minor, patchlevel))
return (compiler, major, minor, patchlevel)
def clang_version():
"""Parse the output of clang++ -E -dM -"""
try:
with subprocess.Popen(
["clang++", "-E", "-dM", "-"],
stdin=subprocess.DEVNULL,
stdout=subprocess.PIPE,
universal_newlines=True,
bufsize=1,
close_fds=not IS_WINDOWS,
) as p:
for line in iter(p.stdout.readline, ""):
if "__clang_major__" in line:
clang_major = line.split()[2]
if "__clang_minor__" in line:
clang_minor = line.split()[2]
if "__clang_patchlevel__" in line:
clang_patchlevel = line.split()[2]
except (OSError, subprocess.SubprocessError):
print("No clang++ or clang++ is not executable")
return None
if p.returncode != 0:
print("clang++ version query failed with return code {}".format(p.returncode))
return None
try:
major = int(clang_major)
minor = int(clang_minor)
patchlevel = int(clang_patchlevel)
compiler = "clang++"
except:
print("Failed to parse clang++ version.")
return None
print("Found {} version {}.{}.{}".format(compiler, major, minor, patchlevel))
return (compiler, major, minor, patchlevel)
def detect_compilers():
ret = {}
gcc_version_ = gcc_version()
if gcc_version_ is not None:
ret["g++"] = gcc_version_
clang_version_ = clang_version()
if clang_version_ is not None:
ret["clang++"] = clang_version_
return ret
def get_exception(files):
i = 0
exc_type, exc_obj, tb = sys.exc_info()
filename, lineno, name, line = traceback.extract_tb(tb)[i]
message = "Exception {} at {}:{}".format(
exc_type.__name__, os.path.basename(filename), lineno
)
while os.path.basename(filename) in files:
message = "Exception {} at {}:{}".format(
exc_type.__name__, os.path.basename(filename), lineno
)
i += 1
try:
filename, lineno, name, line = traceback.extract_tb(tb)[i]
except:
break
return message
def heartbeat(worker_info, password, remote, current_state):
print("Start heartbeat")
payload = {
"password": password,
"worker_info": worker_info,
}
count = 0
while current_state["alive"]:
time.sleep(1)
count += 1
if count == 60:
count = 0
print(" Send heartbeat for", worker_info["unique_key"], end=" ... ")