diff --git a/.gitignore b/.gitignore index 5569687..84daff1 100644 --- a/.gitignore +++ b/.gitignore @@ -6,9 +6,8 @@ credentials credentials.* db.sqlite3 -Scripts/Binaries/* +Scripts/Engines/* Scripts/Networks/* -Scripts/Repositories/* Media/* diff --git a/Client/__init__.py b/Client/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/Client/utils.py b/Client/utils.py new file mode 100644 index 0000000..d0cdf54 --- /dev/null +++ b/Client/utils.py @@ -0,0 +1,178 @@ +# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # +# # +# OpenBench is a chess engine testing framework by Andrew Grant. # +# # +# # +# OpenBench 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. # +# # +# OpenBench 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 . # +# # +# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # + +import argparse +import hashlib +import os +import requests +import subprocess +import tempfile +import zipfile + +class OpenBenchBuildFailedException(Exception): + def __init__(self, message): + self.message = message + super().__init__(self.message) + + +def url_join(*args): + + # Join a set of URL paths while maintaining the correct format + return '/'.join([f.lstrip('/').rstrip('/') for f in args]) + '/' + +def credentialed_cmdline_args(parser=None): + + # Adds username, password, and server to the ArgumentParser + # Defers to the env variables for them, if not provided explicitly + + # Don't require inheritence from an existing ArgumentParser + if not parser: + parser = argparse.ArgumentParser() + + # We can use ENV variables for Username, Password, and Server + req_user = 'OPENBENCH_USERNAME' not in os.environ + req_pass = 'OPENBENCH_PASSWORD' not in os.environ + req_server = 'OPENBENCH_SERVER' not in os.environ + + # For clarity, seperate out this help text + help_user = 'Username. May also be passed as OPENBENCH_USERNAME environment variable' + help_pass = 'Password. May also be passed as OPENBENCH_PASSWORD environment variable' + help_server = ' Server. May also be passed as OPENBENCH_SERVER environment variable' + + # Parse all arguments, all of which must exist in some form + parser.add_argument('-U', '--username', help=help_user , required=req_user ) + parser.add_argument('-P', '--password', help=help_pass , required=req_pass ) + parser.add_argument('-S', '--server' , help=help_server , required=req_server) + args = parser.parse_args() + + # Fallback on ENV variables for Username, Password, and Server + args.username = args.username if args.username else os.environ['OPENBENCH_USERNAME'] + args.password = args.password if args.password else os.environ['OPENBENCH_PASSWORD'] + args.server = args.server if args.server else os.environ['OPENBENCH_SERVER' ] + + return args + +def credentialed_request(server, username, password, endpoint): + + target = url_join(server, *endpoint.split('/')) + payload = { 'username' : username, 'password' : password } + + return requests.post(data=payload, url=target) + + +def makefile_command(net_path, make_path, out_path, compiler, threads): + + # Build with EXE= to contol the output location + command = ['make', 'EXE=%s' % (out_path)] + + # Build with CC/CXX= when using a custom compiler + if compiler: + comp_flag = ['CC', 'CXX']['++' in compiler] + command += ['%s=%s' % (comp_flag, compiler)] + + # Build with -jN, or just -j if threads is not explicit + command += ['-j' if not threads else '-j%d' % (threads)] + + # Build with EVALFILE= to embed NNUE files + if net_path: + rel_net_path = os.path.relpath(os.path.abspath(net_path), make_path) + command += ['EVALFILE=%s' % (rel_net_path.replace('\\', '/'))] + + return command + + +def download_network(server, username, password, engine, net_name, net_sha, net_path): + + print ('Fetching %s (%s) for %s' % (net_name, net_sha, engine)) + + # Avoid redownloading Network files + if not os.path.isfile(net_path): + + # Format the API request, including credentials + endpoint = '/api/networks/%s/%s' % (engine, net_sha) + request = credentialed_request(server, username, password, endpoint) + + # Write the content out to the net_path in kb chunks + with open(net_path, 'wb') as fout: + for chunk in request.iter_content(chunk_size=1024): + if chunk: fout.write(chunk) + fout.flush() + + # Check for the first 8 characters of the sha256 + with open(net_path, 'rb') as network: + sha256 = hashlib.sha256(network.read()).hexdigest()[:8].upper() + + # Verify the download and delete partial or corrupted ones + if net_sha != sha256: + os.remove(net_path) + raise Exception('Invalid SHA for %s' % (network_sha)) + +def download_public_engine(engine, net_path, branch, source, make_path, out_path, compiler=None, threads=None): + + # Check for already having the binary ( Linux ) + if os.path.isfile(out_path): + return out_path + + # Check for already having the binary ( Windows ) + if os.path.isfile('%s.exe' % (out_path)): + return '%s.exe' % (out_path) + + # Work with temp files and directories until finished building + with tempfile.TemporaryDirectory() as temp_dir: + + print('Building [%s-%s]' % (engine, branch)) + + # Download the zip file from Github + zip_path = os.path.join(temp_dir, '%s-%s' % (engine, branch)) + with open(zip_path, 'wb') as zip_file: + zip_file.write(requests.get(source).content) + + # Unzip the engine to a directory called + unzip_path = os.path.join(temp_dir, engine) + with zipfile.ZipFile(zip_path, 'r') as zip_file: + zip_file.extractall(unzip_path) + + # Rename the Root folder for ease of conventions + unzip_root = os.path.join(unzip_path, os.listdir(unzip_path)[0]) + src_path = os.path.join(unzip_path, '%s-%s' % (engine, branch)) + os.rename(unzip_root, src_path) + + # Prepare the MAKEFILE command + make_path = os.path.join(src_path, make_path) + rel_out_path = os.path.relpath(os.path.abspath(out_path), make_path) + make_cmd = makefile_command(net_path, make_path, rel_out_path, compiler, threads) + + # Build the engine, which will produce a binary to the original out_path + process = subprocess.Popen(make_cmd, cwd=make_path, stdout=subprocess.PIPE, stderr=subprocess.STDOUT) + comp_output = process.communicate()[0].decode('utf-8') + + # Indicate where the true binary name ( Linux ) + if os.path.isfile(out_path): + return out_path + + # Indicate where the true binary name ( Windows ) + if os.path.isfile('%s.exe' % (out_path)): + return '%s.exe' % (out_path) + + # Someone should catch this, and possibly report it to the OpenBench server + raise OpenBenchBuildFailedException(comp_output) + + + diff --git a/OpenBench/views.py b/OpenBench/views.py index a93afd6..daed0b8 100644 --- a/OpenBench/views.py +++ b/OpenBench/views.py @@ -781,6 +781,7 @@ def client_submit_pgn(request, machine): def api_response(data): return HttpResponse(json.dumps(data, indent=4), content_type='application/json') +@csrf_exempt def api_authenticate(request, require_enabled=False): try: @@ -795,7 +796,7 @@ def api_authenticate(request, require_enabled=False): # Request might be made from the command line. Check the headers user = django.contrib.auth.authenticate( - request.POST['username'], request.POST['password']) + username=request.POST['username'], password=request.POST['password']) return not require_enabled or Profile.objects.get(user=user).enabled except Exception: @@ -803,6 +804,7 @@ def api_authenticate(request, require_enabled=False): traceback.print_exc() return False +@csrf_exempt def api_configs(request, engine=None): if not api_authenticate(request): @@ -814,11 +816,11 @@ def api_configs(request, engine=None): return api_response({ 'engines' : engines, 'books' : books }) if engine in OPENBENCH_CONFIG['engines'].keys(): - with open(os.path.join(PROJECT_PATH, 'Engines', '%s.json' % (engine))) as fin: - return HttpResponse('
' + str(fin.read()) + '
') + return api_response(OPENBENCH_CONFIG['engines'][engine]) return api_response({ 'error' : 'Engine not found. Check /api/config/ for a full list' }) +@csrf_exempt def api_networks(request, engine): if not api_authenticate(request): @@ -843,6 +845,7 @@ def api_networks(request, engine): else: return api_response({ 'error' : 'Engine not found. Check /api/config/ for a full list' }) +@csrf_exempt def api_network_download(request, engine, identifier): if not api_authenticate(request): diff --git a/Scripts/bench_all.py b/Scripts/bench_all.py new file mode 100644 index 0000000..002ed51 --- /dev/null +++ b/Scripts/bench_all.py @@ -0,0 +1,86 @@ +#!/bin/python3 + +# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # +# # +# OpenBench is a chess engine testing framework by Andrew Grant. # +# # +# # +# OpenBench 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. # +# # +# OpenBench 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 . # +# # +# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # + +import argparse +import os +import requests +import sys + +# Needed to include from ../Client/*.py +PARENT = os.path.join(os.path.dirname(__file__), os.path.pardir) +sys.path.append(os.path.abspath(PARENT)) + +from Client.utils import url_join +from Client.utils import credentialed_cmdline_args +from Client.utils import credentialed_request +from Client.utils import download_network +from Client.utils import download_public_engine + +def get_default_network_if_any(args, networks): + + # Not all engines use Networks + if 'default' not in networks: + return None + + # Download the default Network + net_name = networks['default']['name'] + net_sha = networks['default']['sha'] + net_path = os.path.join('Networks', net_sha) + download_network(args.server, args.username, args.password, engine, net_name, net_sha, net_path) + + return net_path + +if __name__ == '__main__': + + # Use bench_all.py's path as the base pathway + os.chdir(os.path.dirname(os.path.abspath(__file__))) + + # Ensure the folder structure for ease of coding + for folder in ['Engines', 'Networks']: + if not os.path.isdir(folder): + os.mkdir(folder) + + # Get the list of engines on the Server + args = credentialed_cmdline_args() + request = credentialed_request(args.server, args.username, args.password, 'api/config') + + for engine in request.json()['engines']: + + if engine == 'Torch': + continue + + # Get the configuration file for the engine + endpoint = 'api/config/%s' % (engine) + request = credentialed_request(args.server, args.username, args.password, endpoint) + config = request.json() + + # Get the list of all Networks for the engine + endpoint = 'api/networks/%s' % (engine) + request = credentialed_request(args.server, args.username, args.password, endpoint) + net_path = get_default_network_if_any(args, request.json()) + + # Download, build, and move the engine to Engines/ + make_path = config['build']['path'] + branch = config['test_presets']['default']['base_branch'] + out_path = os.path.join('Engines', engine) + target = url_join(config['source'], 'archive', '%s.zip' % (branch)) + download_public_engine(engine, net_path, branch, target, make_path, out_path) diff --git a/Scripts/download_net.py b/Scripts/download_net.py deleted file mode 100755 index 58122c7..0000000 --- a/Scripts/download_net.py +++ /dev/null @@ -1,71 +0,0 @@ -#!/bin/python3 - -# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # -# # -# OpenBench is a chess engine testing framework by Andrew Grant. # -# # -# # -# OpenBench 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. # -# # -# OpenBench 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 . # -# # -# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # - -import argparse -import hashlib -import os -import requests - -def url_join(*args): - # Join a set of URL paths while maintaining the correct format - return '/'.join([f.lstrip('/').rstrip('/') for f in args]) + '/' - -def download_network(username, password, server, engine, name): - - print ('Downloading %s for %s...' % (name, engine)) - - target = url_join(server, 'clientGetNetwork', engine, name) - payload = { 'username' : username, 'password' : password } - request = requests.post(data=payload, url=target) - - with open(name, 'wb') as fout: - for chunk in request.iter_content(chunk_size=1024): - if chunk: fout.write(chunk) - fout.flush() - -if __name__ == '__main__': - - # We can use ENV variables for Username, Password, and Server - req_user = required=('OPENBENCH_USERNAME' not in os.environ) - req_pass = required=('OPENBENCH_PASSWORD' not in os.environ) - req_server = required=('OPENBENCH_SERVER' not in os.environ) - - # For clarity, seperate out this help text - help_user = 'Username. May also be passed as OPENBENCH_USERNAME environment variable' - help_pass = 'Password. May also be passed as OPENBENCH_PASSWORD environment variable' - help_server = ' Server. May also be passed as OPENBENCH_SERVER environment variable' - - # Parse all arguments, all of which must exist in some form - p = argparse.ArgumentParser() - p.add_argument('-U', '--username', help=help_user , required=req_user ) - p.add_argument('-P', '--password', help=help_pass , required=req_pass ) - p.add_argument('-S', '--server' , help=help_server , required=req_server) - p.add_argument('-E', '--engine' , help='Engine' , required=True ) - p.add_argument('-N', '--network' , help='Name or Sha', required=True ) - args = p.parse_args() - - # Fallback on ENV variables for Username, Password, and Server - args.username = args.username if args.username else os.environ['OPENBENCH_USERNAME'] - args.password = args.password if args.password else os.environ['OPENBENCH_PASSWORD'] - args.server = args.server if args.server else os.environ['OPENBENCH_SERVER' ] - - download_network(args.username, args.password, args.server, args.engine, args.network)