From 6fb21cbd7de7e8826b104e3a343790f6a148cb17 Mon Sep 17 00:00:00 2001 From: Andrew Grant Date: Mon, 24 May 2021 02:30:59 -0400 Subject: [PATCH] Initial commit of working progress --- .gitignore | 3 +- Client/openV2.py | 548 ++++++++++++++++++++++++++++++++++++++++++++ OpenBench/config.py | 97 +++++--- OpenBench/models.py | 1 - OpenBench/urls.py | 2 +- OpenBench/utils.py | 56 +++-- OpenBench/views.py | 137 ++++++----- 7 files changed, 723 insertions(+), 121 deletions(-) create mode 100644 Client/openV2.py diff --git a/.gitignore b/.gitignore index 27f78f3..6657262 100644 --- a/.gitignore +++ b/.gitignore @@ -1,7 +1,6 @@ *.pyc Client/* -!Client/OpenBench.py -!Client/Client.py +!Client/openV2.py !Client/cleanup.sh OpenBench/migrations/* credentials \ No newline at end of file diff --git a/Client/openV2.py b/Client/openV2.py new file mode 100644 index 0000000..452d5f8 --- /dev/null +++ b/Client/openV2.py @@ -0,0 +1,548 @@ +# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # +# # +# 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 platform +import re +import requests +import sys +import time +import traceback +import zipfile +import shutil + +from subprocess import PIPE, Popen + +from itertools import combinations_with_replacement + +# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # +# # +# Configuration for the Client. To disable deleting old files, use the # +# value None. If Syzygy Tablebases are not present, set to None. # +# # +# Each engine allows a custom set of arguments. All engines will compile # +# without any custom options. However you have the ability to add args # +# in order to get better builds, like PGO or PEXT/BMI2. # +# # +# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # + +TIMEOUT_HTTP = 30 # Timeout in seconds for HTTP requests +TIMEOUT_ERROR = 30 # Timeout in seconds when any errors are thrown +TIMEOUT_WORKLOAD = 60 # Timeout in seconds between workload requests + +DELETE_OLD_ENGINES = 24 # Number of hours until deleting Engines +DELETE_OLD_NETWORKS = 720 # Number of hours until deleting Networks +DELETE_OLD_PGNS = None # Number of hours until deleting PGNs + +SYZYGY_WDL_PATH = 'C:\\Users\\14438\\Desktop\\Syzygy\\' # Pathway to WDL Syzygy Tables +SYZYGY_DTZ_PATH = 'C:\\Users\\14438\\Desktop\\Syzygy\\' # Pathway to DTZ Syzygy Tables +BASE_GAMES_PER_CORE = 32 # Typical games played per-thread + +CUSTOM_SETTINGS = { + 'Ethereal' : [], 'Laser' : [], + 'Weiss' : [], 'Demolito' : [], + 'Rubichess' : [], 'FabChess' : [], + 'Igel' : [], 'Winter' : [], + 'Halogen' : [], 'Stash' : [], +}; + +ERRORS = { + 'cutechess' : 'Unable to fetch Cutechess location and download it.', + 'configure' : 'Unable to fetch engine data and find acceptable workloads', + 'request' : 'Unable to reach server for workload request.', +} + +# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # +# # +# Setting up the Client. Build the OpenBench file structure, check for # +# Syzygy Tables for both WDL and DTZ, download a static Cutechess binary, # +# and determine what engines we are able to compile by asking the server. # +# # +# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # + +# Differentiate Windows and Linux systems +IS_WINDOWS = platform.system() == 'Windows' +IS_LINUX = platform.system() != 'Windows' + +COMPILERS = {} # Compiler for each Engine, + CPU Flags +OSNAME = '%s %s' % (platform.system(), platform.release()) +DEBUG = True + + +def check_for_utilities(): + + def locate_utility(util): + + try: + process = Popen([util, '--version'], stdout=PIPE) + stdout, stderr = process.communicate() + + ver = re.search('[0-9]+.[0-9]+.[0-9]+', str(stdout)) + print ('Located %s (%s)' % (util.upper(), ver.group())) + + except OSError: + print('[Error] Unable to locate %s' % (util.upper())) + sys.exit() + + print('\nScanning For Basic Utilities...') + for utility in ['gcc', 'make']: + locate_utility(utility) + +def init_client(arguments): + + # Use Client.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', 'Books', 'PGNs']: + if not os.path.isdir(folder): + os.mkdir(folder) + + # Verify all WDL/DTZ tables are present when told they are + validate_syzygy_exists() + +def cleanup_client(): + + SECONDS_PER_DAY = 60 * 60 * 24 + SECONDS_PER_MONTH = SECONDS_PER_DAY * 30 + + file_age = lambda x: time.time() - os.path.getmtime(x) + + for file in os.listdir('Engines'): + if file_age(os.path.join('Engines', file)) > SECONDS_PER_DAY: + os.remove(os.path.join('Engines', file)) + + for file in os.listdir('Networks'): + if file_age(os.path.join('Networks', file)) > SECONDS_PER_MONTH: + os.remove(os.path.join('Networks', file)) + +def validate_syzygy_exists(): + + global SYZYGY_WDL_PATH, SYZYGY_DTZ_PATH + + print ('\nScanning for Syzygy Configuration...') + + for filename in tablebase_names(): + + # Build the paths when the configuration enables Syzygy + + if SYZYGY_WDL_PATH: + wdlpath = os.path.join(SYZYGY_WDL_PATH, filename + '.rtbw') + + if SYZYGY_DTZ_PATH: + dtzpath = os.path.join(SYZYGY_DTZ_PATH, filename + '.rtbz') + + # Reset the configuration if the file is missing + + if SYZYGY_WDL_PATH and not os.path.isfile(wdlpath): + print('Missing Syzygy File (%s)' % (filename + '.rtbw')) + SYZYGY_WDL_PATH = None + + if SYZYGY_DTZ_PATH and not os.path.isfile(dtzpath): + print('Missing Syzygy File (%s)' % (filename + '.rtbz')) + SYZYGY_DTZ_PATH = None + + # Report final results, which may conflict with the original configuration + + if SYZYGY_WDL_PATH: + print('Verified Syzygy WDL (%s)' % (SYZYGY_WDL_PATH)) + + if SYZYGY_DTZ_PATH: + print('Verified Syzygy DTZ (%s)' % (SYZYGY_DTZ_PATH)) + +def tablebase_names(K=6): + + letters = ['', 'Q', 'R', 'B', 'N', 'P']; candidates = [] + + # Generate many potential K[] v K[], including all valid ones + for N in range(1, K - 1): + for lhs in combinations_with_replacement(letters, N): + for rhs in combinations_with_replacement(letters, K - N - 2): + candidates.append('K%svK%s' % (''.join(lhs), ''.join(rhs))) + + # Syzygy does LHS having more pieces first, stronger pieces second + def valid_filename(name): + for i, letter in enumerate(letters[1:]): + name = name.replace(letter, str(9 - i)) + lhs, rhs = name.replace('K', '9').split('v') + return int(lhs) >= int(rhs) and name != 'KvK' + + return list(filter(valid_filename, set(candidates))) + +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 try_until_success(mesg): + def _try_until_success(funct): + def __try_until_success(*args): + while True: + try: return funct(*args) + except Exception: + print('[Error]', mesg); time.sleep(TIMEOUT_ERROR) + if DEBUG: traceback.print_exc() + return __try_until_success + return _try_until_success + +def download_file(source, outname, post_data=None): + + arguments = { 'stream' : True, 'timeout' : TIMEOUT_ERROR } + function = [requests.get, requests.post][post_data != None] + if post_data: arguments['data'] = post_data + + request = function(source, **arguments) + with open(outname, 'wb') as fout: + for chunk in request.iter_content(chunk_size=1024): + if chunk: fout.write(chunk) + fout.flush() + +def unzip_delete_file(source, outdir): + with zipfile.ZipFile(source) as fin: + fin.extractall(outdir) + os.remove(source) + +def make_command(arguments, engine, network_path): + + command = 'make CC=%s EXE=%s -j%s' % ( + COMPILERS[engine], engine, arguments.threads) + + if engine in CUSTOM_SETTINGS: + command += ' '.join(CUSTOM_SETTINGS[engine]) + + if network_path != None: + network_path = network_path.replace('\\', '/') + command += ' EVALFILE=%s' % (network_path) + + return command + +# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # +# # +# All functions used to make requests to the OpenBench server. Workload # +# requests require Username and Password authentication. Afterwords, all # +# verification is done using a generated token assigned to each Workload. # +# # +# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # + +@try_until_success(mesg=ERRORS['cutechess']) +def server_download_cutechess(arguments): + + print('\nScanning for Cutechess Binary...') + + if IS_WINDOWS and not os.path.isfile('cutechess.exe'): + + # Fetch the source location if we are missing the binary + source = requests.get( + url_join(arguments.server, 'clientGetFiles'), + timeout=TIMEOUT_HTTP).content.decode('utf-8') + + # Windows workers simply need a static compile (64-bit) + download_file(url_join(source, 'cutechess-windows.exe'), 'cutechess.exe') + + if IS_LINUX and not os.path.isfile('cutechess'): + + # Fetch the source location if we are missing the binary + source = requests.get( + url_join(arguments.server, 'clientGetFiles'), + timeout=TIMEOUT_HTTP).content.decode('utf-8') + + # Linux workers need a static compile (64-bit) with execute permissions + download_file(url_join(source, 'cutechess-linux'), 'cutechess') + os.system('chmod 777 cutechess') + + print('Cutechess Binary found or obtained') + +@try_until_success(mesg=ERRORS['configure']) +def server_configure_worker(arguments): + + print ('\nScanning for Compilers...') + + # Fetch { Engine -> Compilers } from the server + target = url_join(arguments.server, 'clientGetBuildInfo') + data = requests.get(target, timeout=TIMEOUT_HTTP).json() + + for engine, build_info in data.items(): + for compiler in build_info['compilers']: + + # Compilers may require a specific version + if '>=' in compiler: + compiler, version = compiler.split('>=') + version = tuple(map(int, version.split('.'))) + else: version = (0, 0, 0) + + # Try to execute the compiler from the command line + try: + process = Popen([compiler, '--version'], stdout=PIPE) + stdout, stderr = process.communicate() + except OSError: continue + + # Parse the version number reported by the compiler + stdout = stdout.decode('utf-8') + match = re.search(r'[0-9]+\.[0-9]+\.[0-9]+', stdout).group() + + # Compiler version was sufficient + if tuple(map(int, match.split('.'))) >= version: + print('%10s :: %s (%s)' % (engine, compiler, match)) + COMPILERS[engine] = compiler + break + + # Report missing engines in case the User is not expecting it + for engine in filter(lambda x: x not in COMPILERS, data): + compiler = data[engine]['compilers'] + print('%10s :: Missing %s' % (engine, compiler)) + + print ('\nScanning for CPU Flags...') + + # Use GCC -march=native to find CPU info + stdout, stderr = Popen( + 'echo | gcc -march=native -E -dM -'.split(), + stdout=PIPE, shell=True + ).communicate() + + # Check for each requested flag using the gcc dump + desired = [info['cpuflags'] for engine, info in data.items()] + flags = set(sum(desired, [])) # Trick to flatten the list + actual = set(f for f in flags if '__%s__ 1' % (f) in str(stdout)) + + # Report and save to global configuration + print (' Found ::', ' '.join(list(actual))) + print (' Missing ::', ' '.join(list(flags - actual))) + COMPILERS['cpuflags'] = ' '.join(list(actual)) + +@try_until_success(mesg=ERRORS['request']) +def server_request_workload(arguments): + + print('\nRequesting Workload from Server...') + + machine_id = 'None' + if os.path.isfile('machine.txt'): + with open('machine.txt') as fin: + machine_id = fin.readlines()[0] + + if machine_id == 'None': + print('[NOTE] This machine is currently unregistered') + + supported = ' '.join(COMPILERS.keys() - ['cpuflags']) + has_syzygy = bool(SYZYGY_DTZ_PATH) and bool(SYZYGY_WDL_PATH) + + payload = { + 'username' : arguments.username, 'threads' : arguments.threads, + 'password' : arguments.password, 'osname' : OSNAME, + 'machineid' : machine_id, 'syzygy_dtz' : str(has_syzygy), + 'supported' : supported, 'cpuflags' : COMPILERS['cpuflags'], + } + + target = url_join(arguments.server, 'clientGetWorkload') + return requests.post(target, data=payload, timeout=TIMEOUT_HTTP) + +# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # +# # +# # +# # +# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # + +def check_workload_response(arguments, response): + + raw_text = response.content.decode('utf-8') + + # No workloads available to our machine + if raw_text == 'None': + print('[Note] Server Has No Work') + time.sleep(TIMEOUT_WORKLOAD) + return False + + # Bad login, kill the worker since all requests will fail + if raw_text == 'Bad Credentials': + print('[Error] Invalid Login Credentials') + sys.exit() + + # Bad machine, mostly meaningless but note it + if raw_text == 'Bad Machine': + print('[Note] Replacing Invalid Machine Id') + os.remove('machine.txt') + return False + + # Final check that we may parse the workload JSON + data = response.json() + with open('machine.txt', 'w') as fout: + fout.write(str(data['machine']['id'])) + + # Log the start of the new workload + engine = data['test']['engine'] + dev = data['test']['dev' ]['name'] + base = data['test']['base' ]['name'] + print ('Workload [%s] %s vs %s\n' % (engine, dev, base)) + + return data + +def complete_workload(arguments, workload): + + dev_network = download_network_weights(arguments, workload, 'dev' ) + base_network = download_network_weights(arguments, workload, 'base') + + dev_engine = download_engine(arguments, workload, 'dev', dev_network ) + base_engine = download_engine(arguments, workload, 'base', base_network) + + dev_nps = compute_engine_speed(arguments, workload, 'dev', dev_engine ) + base_nps = compute_engine_speed(arguments, workload, 'base', base_engine) + + download_opening_book(workload) + +def download_opening_book(workload): + + # Log our attempts to download and verify the book + book_sha256 = workload['test']['book']['sha' ] + book_source = workload['test']['book']['source'] + book_name = workload['test']['book']['name' ] + book_path = os.path.join('Books', book_name) + print ('\nFetching Opening Book [%s]' % (book_name)) + + # Download file if we do not already have it + if not os.path.isfile(book_path): + download_file(book_source, book_name + '.zip') + unzip_delete_file(book_name + '.zip', 'Books/') + + # Verify SHAs match with the server + with open(book_path) as fin: + content = fin.read().encode('utf-8') + sha256 = hashlib.sha256(content).hexdigest() + if book_sha256 != sha256: os.remove(book_path) + + # Log SHAs on every workload + print ('Correct SHA256 %s' % (book_sha256)) + print ('Download SHA256 %s' % (sha256)) + + # We have to have the correct SHA to continue + if book_sha256 != sha256: + raise Exception('Invalid SHA for %s' % (book_name)) + +def download_network_weights(arguments, workload, branch): + + # Some tests may not use Neural Networks + network_name = workload['test'][branch]['network'] + if not network_name or network_name == 'None': return None + + # Log that we are obtaining a Neural Network + pattern = 'Fetching Neural Network [ %s, %-4s ]' + print (pattern % (network_name, branch.upper())) + + # Neural Network requests require authorization + payload = { + 'username' : arguments.username, + 'password' : arguments.password, + } + + # Fetch the Netural Network if we do not already have it + network_path = os.path.join('Networks', network_name) + if not os.path.isfile(network_path): + api = url_join(arguments.server, 'clientGetNetwork') + download_file(url_join(api, network_name), network_path, payload) + + # Verify the download and delete partial or corrupted ones + with open(network_path, 'rb') as network: + sha256 = hashlib.sha256(network.read()).hexdigest() + sha256 = sha256[:8].upper() + if network_name != sha256: os.remove(network_path) + + # We have to have the correct Neural Network to continue + if network_name != sha256: + raise Exception('Invalid SHA for %s' % (network_name)) + + return network_path + +def download_engine(arguments, workload, branch, network): + + engine = workload['test']['engine'] + branch_name = workload['test'][branch]['name'] + commit_sha = workload['test'][branch]['sha'] + source = workload['test'][branch]['source'] + build_path = workload['test']['build']['path'] + + pattern = '\nEngine: %s\nBranch: %s\nCommit: %s' + print (pattern % (engine, branch_name, commit_sha.upper())) + + # Naming as SHA256[:16]-NETSHA256[:8] + final_name = commit_sha.upper()[:16] + if network: final_name += '-%s' % (network[-8:]) + + # Check to see if we already have the final binary + final_path = os.path.join('Engines', final_name) + if os.path.isfile(final_path): return final_path + + # Download and unzip the source from Github + download_file(source, '%s.zip' % (engine)) + unzip_delete_file('%s.zip' % (engine), 'tmp/') + + # Parse out paths to find the makefile location + tokens = source.split('/') + unzip_name = '%s-%s' % (tokens[-3], tokens[-1].rstrip('.zip')) + src_path = os.path.join('tmp', unzip_name, *build_path.split('/')) + + # Build the engine and drop it into src_path + print ('\nBuilding [%s]' % (final_path)) + rel_path = os.path.relpath(os.path.abspath(network), src_path) + Popen(make_command(arguments, engine, rel_path), cwd=src_path).wait() + output_name = os.path.join(src_path, engine) + + # Move the file to the final location ( Linux ) + if os.path.isfile(output_name): + os.rename(output_name, final_path) + + # Move the file to the final location ( Windows ) + if os.path.isfile(output_name + '.exe'): + os.rename(output_name + '.exe', final_path) + + # Cleanup the source code + shutil.rmtree('tmp') + + # Relative location of final binary + return final_path + +def compute_engine_speed(arguments, workload, branch, engine): + pass + +# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # +# # +# # +# # +# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # + +if __name__ == '__main__': + + p = argparse.ArgumentParser() + p.add_argument('-U', '--username', help='Username' , required=True) + p.add_argument('-P', '--password', help='Password' , required=True) + p.add_argument('-S', '--server' , help='Webserver', required=True) + p.add_argument('-T', '--threads' , help='Threads' , required=True) + arguments = p.parse_args() + + check_for_utilities() + init_client(arguments) + server_download_cutechess(arguments) + server_configure_worker(arguments) + + while True: + cleanup_client() + response = server_request_workload(arguments) + workload = check_workload_response(arguments, response) + if workload: complete_workload(arguments, workload) + break \ No newline at end of file diff --git a/OpenBench/config.py b/OpenBench/config.py index d757b7e..07c4563 100644 --- a/OpenBench/config.py +++ b/OpenBench/config.py @@ -29,7 +29,7 @@ OPENBENCH_CONFIG = { # Link to the repo on the sidebar, as well as the core files 'framework' : 'http://github.com/AndyGrant/OpenBench/', - 'corefiles' : 'http://github.com/AndyGrant/OpenBench/raw/master/CoreFiles/', + 'corefiles' : 'http://github.com/AndyGrant/OpenBench/raw/openV2/CoreFiles/', # SPRT Elo bounds and type I/II errors 'sprt' : { 'elolower' : 0.00, 'eloupper' : 5.00, 'alpha' : 0.05, 'beta' : 0.05 }, @@ -44,28 +44,28 @@ OPENBENCH_CONFIG = { '2moves_v1.epd' : { 'name' : '2moves_v1.epd', 'sha' : '7bec98239836f219dc41944a768c0506abed950aaec48da69a0782643e90f237', - 'source' : 'http://github.com/AndyGrant/OpenBench/raw/master/Books/2moves_v1.epd', + 'source' : 'http://github.com/AndyGrant/OpenBench/raw/openV2/Books/2moves_v1.epd.zip', 'default' : False, }, '8moves_v3.epd' : { 'name' : '8moves_v3.epd', - 'sha' : '38d1b6c456bc3d3f69a4927e2667ef3f3fa231e253b6dc4040093f00a1c2ccb3', - 'source' : 'http://github.com/AndyGrant/OpenBench/raw/master/Books/8moves_v3.epd', + 'sha' : '1f055af431656f09ee6a09d2448e0b876125f78bb7b404fca2031c403a1541e5', + 'source' : 'http://github.com/AndyGrant/OpenBench/raw/openV2/Books/8moves_v3.epd.zip', 'default' : False, }, '3moves_FRC.epd' : { 'name' : '3moves_FRC.epd', - 'sha' : '4be746a91e3f8af0c9344b1e72d611e9fcfe486843867a55760970a4896f284d', - 'source' : 'http://github.com/AndyGrant/OpenBench/raw/master/Books/3moves_FRC.epd', + 'sha' : '38d1b6c456bc3d3f69a4927e2667ef3f3fa231e253b6dc4040093f00a1c2ccb3', + 'source' : 'http://github.com/AndyGrant/OpenBench/raw/openV2/Books/3moves_FRC.epd.zip', 'default' : False, }, '4moves_noob.epd' : { 'name' : '4moves_noob.epd', - 'sha' : '1f055af431656f09ee6a09d2448e0b876125f78bb7b404fca2031c403a1541e5', - 'source' : 'http://github.com/AndyGrant/OpenBench/raw/master/Books/4moves_noob.epd', + 'sha' : '4be746a91e3f8af0c9344b1e72d611e9fcfe486843867a55760970a4896f284d', + 'source' : 'http://github.com/AndyGrant/OpenBench/raw/openV2/Books/4moves_noob.epd.zip', 'default' : True, }, }, @@ -79,11 +79,15 @@ OPENBENCH_CONFIG = { 'Ethereal' : { - 'proto' : 'uci', 'nps' : 1075000, - 'build' : { 'path' : '/src/', 'compilers' : ['gcc'] }, 'source' : 'https://github.com/AndyGrant/Ethereal', + 'build' : { + 'path' : 'src', + 'compilers' : ['gcc'], + 'cpuflags' : ['AVX2', 'AVX', 'FMA', 'POPCNT', 'SSE2', 'SSE'], + }, + 'testmodes' : { 'stc' : { 'threads' : 1, 'hash' : 8, 'timecontrol' : '10.0+0.1' }, 'ltc' : { 'threads' : 1, 'hash' : 64, 'timecontrol' : '60.0+0.6' }, @@ -94,11 +98,15 @@ OPENBENCH_CONFIG = { 'Laser' : { - 'proto' : 'uci', 'nps' : 720000, - 'build' : { 'path' : '/src/', 'compilers' : ['g++'] }, 'source' : 'https://github.com/jeffreyan11/uci-chess-engine', + 'build' : { + 'path' : 'src', + 'compilers' : ['g++'], + 'cpuflags' : ['POPCNT'], + }, + 'testmodes' : { 'stc' : { 'threads' : 1, 'hash' : 8, 'timecontrol' : '10.0+0.1' }, 'ltc' : { 'threads' : 1, 'hash' : 64, 'timecontrol' : '60.0+0.6' }, @@ -109,11 +117,15 @@ OPENBENCH_CONFIG = { 'Weiss' : { - 'proto' : 'uci', 'nps' : 2400000, - 'build' : { 'path' : '/src/', 'compilers' : ['gcc'] }, 'source' : 'https://github.com/TerjeKir/weiss', + 'build' : { + 'path' : 'src', + 'compilers' : ['gcc'], + 'cpuflags' : ['POPCNT'], + }, + 'testmodes' : { 'stc' : { 'threads' : 1, 'hash' : 32, 'timecontrol' : '10.0+0.1' }, 'ltc' : { 'threads' : 1, 'hash' : 128, 'timecontrol' : '60.0+0.6' }, @@ -124,11 +136,15 @@ OPENBENCH_CONFIG = { 'Demolito' : { - 'proto' : 'uci', 'nps' : 1075000, - 'build' : { 'path' : '/src/', 'compilers' : ['clang', 'gcc'] }, 'source' : 'https://github.com/lucasart/Demolito', + 'build' : { + 'path' : 'src', + 'compilers' : ['clang', 'gcc'], + 'cpuflags' : ['POPCNT'], + }, + 'testmodes' : { 'stc' : { 'threads' : 1, 'hash' : 8, 'timecontrol' : '8.0+0.08' }, 'ltc' : { 'threads' : 1, 'hash' : 32, 'timecontrol' : '32.0+0.32'}, @@ -139,11 +155,15 @@ OPENBENCH_CONFIG = { 'RubiChess' : { - 'proto' : 'uci', 'nps' : 1500000, - 'build' : { 'path' : '/src/', 'compilers' : ['g++'] }, 'source' : 'https://github.com/Matthies/RubiChess', + 'build' : { + 'path' : 'src', + 'compilers' : ['g++'], + 'cpuflags' : ['POPCNT'], + }, + 'testmodes' : { 'stc' : { 'threads' : 1, 'hash' : 8, 'timecontrol' : '10.0+0.1' }, 'ltc' : { 'threads' : 1, 'hash' : 64, 'timecontrol' : '60.0+0.6' }, @@ -154,11 +174,15 @@ OPENBENCH_CONFIG = { 'FabChess' : { - 'proto' : 'uci', 'nps' : 640000, - 'build' : { 'path' : '', 'compilers' : ['cargo>=1.41.0'] }, 'source' : 'https://github.com/fabianvdW/FabChess', + 'build' : { + 'path' : '', + 'compilers' : ['cargo>=1.41.0'], + 'cpuflags' : ['POPCNT'], + }, + 'testmodes' : { 'stc' : { 'threads' : 1, 'hash' : 8, 'timecontrol' : '10.0+0.1' }, 'ltc' : { 'threads' : 1, 'hash' : 64, 'timecontrol' : '60.0+0.6' }, @@ -169,11 +193,15 @@ OPENBENCH_CONFIG = { 'Igel' : { - 'proto' : 'uci', 'nps' : 475000, - 'build' : { 'path' : '/src/', 'compilers' : ['g++'] }, 'source' : 'https://github.com/vshcherbyna/igel', + 'build' : { + 'path' : 'src', + 'compilers' : ['g++'], + 'cpuflags' : ['POPCNT'], + }, + 'testmodes' : { 'stc' : { 'threads' : 1, 'hash' : 8, 'timecontrol' : '10.0+0.1' }, 'ltc' : { 'threads' : 1, 'hash' : 64, 'timecontrol' : '60.0+0.6' }, @@ -184,11 +212,15 @@ OPENBENCH_CONFIG = { 'Winter' : { - 'proto' : 'uci', 'nps' : 380000, - 'build' : { 'path' : '/', 'compilers' : ['clang++', 'g++'] }, 'source' : 'https://github.com/rosenthj/Winter', + 'build' : { + 'path' : '', + 'compilers' : ['clang++', 'g++'], + 'cpuflags' : ['POPCNT'], + }, + 'testmodes' : { 'stc' : { 'threads' : 1, 'hash' : 8, 'timecontrol' : '10.0+0.1' }, 'ltc' : { 'threads' : 1, 'hash' : 64, 'timecontrol' : '60.0+0.6' }, @@ -199,11 +231,15 @@ OPENBENCH_CONFIG = { 'Halogen' : { - 'proto' : 'uci', 'nps' : 1350000, - 'build' : { 'path' : '/Halogen/src/', 'compilers' : ['g++'] }, 'source' : 'https://github.com/KierenP/Halogen', + 'build' : { + 'path' : 'Halogen/src', + 'compilers' : ['g++'], + 'cpuflags' : ['POPCNT'], + }, + 'testmodes' : { 'stc' : { 'threads' : 1, 'hash' : 8, 'timecontrol' : '10.0+0.1' }, 'ltc' : { 'threads' : 1, 'hash' : 64, 'timecontrol' : '60.0+0.6' }, @@ -213,11 +249,16 @@ OPENBENCH_CONFIG = { }, 'Stash' : { - 'proto' : 'uci', + 'nps' : 1415000, - 'build' : { 'path' : '/src/', 'compilers' : ['gcc', 'clang'] }, 'source' : 'https://github.com/mhouppin/stash-bot', + 'build' : { + 'path' : 'src', + 'compilers' : ['gcc', 'clang'], + 'cpuflags' : ['POPCNT'], + }, + 'testmodes' : { 'stc' : { 'threads' : 1, 'hash' : 16, 'timecontrol' : '10.0+0.1' }, 'ltc' : { 'threads' : 1, 'hash' : 64, 'timecontrol' : '60.0+0.6' }, diff --git a/OpenBench/models.py b/OpenBench/models.py index 196dfa9..666b5a9 100644 --- a/OpenBench/models.py +++ b/OpenBench/models.py @@ -27,7 +27,6 @@ class Engine(Model): name = CharField(max_length=128) source = CharField(max_length=1024) - protocol = CharField(max_length=16) sha = CharField(max_length=64) bench = IntegerField(default=0) diff --git a/OpenBench/urls.py b/OpenBench/urls.py index d1503f7..2bb913b 100644 --- a/OpenBench/urls.py +++ b/OpenBench/urls.py @@ -52,13 +52,13 @@ urlpatterns = [ # Links for viewing and managing Networks django.urls.path(r'networks/', OpenBench.views.networks), django.urls.path(r'networks//', OpenBench.views.networks), - django.urls.path(r'networks//', OpenBench.views.networks), django.urls.path(r'networks///', OpenBench.views.networks), # Links for the Client to work with the Server django.urls.path(r'clientGetFiles/', OpenBench.views.clientGetFiles), django.urls.path(r'clientGetBuildInfo/', OpenBench.views.clientGetBuildInfo), django.urls.path(r'clientGetWorkload/', OpenBench.views.clientGetWorkload), + django.urls.path(r'clientGetNetwork//', OpenBench.views.clientGetNetwork), django.urls.path(r'clientWrongBench/', OpenBench.views.clientWrongBench), django.urls.path(r'clientSubmitNPS/', OpenBench.views.clientSubmitNPS), django.urls.path(r'clientSubmitError/', OpenBench.views.clientSubmitError), diff --git a/OpenBench/utils.py b/OpenBench/utils.py index ad21cbc..8fdfd23 100644 --- a/OpenBench/utils.py +++ b/OpenBench/utils.py @@ -18,7 +18,7 @@ # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # -import math, re, requests, random, datetime, os +import math, re, requests, random, datetime, os, json import OpenBench.models, OpenBench.stats @@ -112,18 +112,11 @@ def getPaging(content, page, url, pagelen=25): return start, end, context -def getEngine(source, name, sha, bench, protocol): +def getEngine(source, name, sha, bench): - engine = Engine.objects.filter( - name=name, source=source, - protocol=protocol, sha=sha, bench=bench) - - if engine.first() != None: - return engine.first() - - return Engine.objects.create( - name=name, source=source, - protocol=protocol, sha=sha, bench=bench) + engine = Engine.objects.filter(name=name, source=source, sha=sha, bench=bench) + if engine.first() != None: return engine.first() + return Engine.objects.create(name=name, source=source, sha=sha, bench=bench) def getBranch(request, errors, name): @@ -236,7 +229,6 @@ def createNewTest(request): devinfo = getBranch(request, errors, 'dev') baseinfo = getBranch(request, errors, 'base') - protocol = OPENBENCH_CONFIG['engines'][request.POST['enginename']]['proto'] if errors != []: return None, errors test = Test() @@ -257,8 +249,8 @@ def createNewTest(request): test.beta = float(request.POST['beta']) test.lowerllr = math.log(test.beta / (1.0 - test.alpha)) test.upperllr = math.log((1.0 - test.beta) / test.alpha) - test.dev = getEngine(*devinfo, protocol) - test.base = getEngine(*baseinfo, protocol) + test.dev = getEngine(*devinfo) + test.base = getEngine(*baseinfo) test.save() profile = Profile.objects.get(user=request.user) @@ -306,20 +298,26 @@ def getWorkload(user, request): machine = getMachine(machineid, user, osname, int(threads)) if type(machine) == str: return machine - # Compare supported Machines vs Existing - supported = request.POST['supported'].split() - existing = OPENBENCH_CONFIG['engines'].keys() - # Filter only to active tests tests = Test.objects.filter(finished=False) tests = tests.filter(deleted=False) tests = tests.filter(approved=True) - # Remove tests that this Machine cannot complete - for engine in existing: + # Filter to compilable engines + supported = request.POST['supported'].split() + cpuflags = request.POST['cpuflags'].split() + + # Remove tests that this Machine cannot complete (Compile) + for engine in OPENBENCH_CONFIG['engines'].keys(): if engine not in supported: tests = tests.exclude(engine=engine) + # Remove tests that this Machine cannot complete (Architecture) + for engine, data in OPENBENCH_CONFIG['engines'].items(): + for flag in data['build']['cpuflags']: + if flag not in cpuflags: + tests = tests.exclude(engine=engine) + # If we don't get a Test back, there was an error test = selectWorkload(tests, machine) if type(test) == str: return test @@ -364,7 +362,7 @@ def workloadDictionary(test, result, machine): # The Client must know his Machine ID, his Result ID, and his Test # ID. Also, all information about the Test and the associated engines - return { + return json.dumps({ 'machine' : { 'id' : machine.id }, @@ -381,19 +379,19 @@ def workloadDictionary(test, result, machine): 'dev' : { 'id' : test.dev.id, 'name' : test.dev.name, - 'source' : test.dev.source, 'protocol' : test.dev.protocol, - 'sha' : test.dev.sha, 'bench' : test.dev.bench, - 'options' : test.devoptions, 'network' : test.devnetwork, + 'source' : test.dev.source, 'sha' : test.dev.sha, + 'bench' : test.dev.bench, 'options' : test.devoptions, + 'network' : test.devnetwork, }, 'base' : { 'id' : test.base.id, 'name' : test.base.name, - 'source' : test.base.source, 'protocol' : test.base.protocol, - 'sha' : test.base.sha, 'bench' : test.base.bench, - 'options' : test.baseoptions, 'network' : test.basenetwork, + 'source' : test.base.source, 'sha' : test.base.sha, + 'bench' : test.base.bench, 'options' : test.baseoptions, + 'network' : test.basenetwork, }, }, - } + }) def updateTest(request, user): diff --git a/OpenBench/views.py b/OpenBench/views.py index e823e7f..d09a197 100644 --- a/OpenBench/views.py +++ b/OpenBench/views.py @@ -18,7 +18,7 @@ # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # -import os, hashlib, mimetypes, datetime +import os, hashlib, mimetypes, datetime, json import django.http import django.shortcuts @@ -38,9 +38,14 @@ from django.views.decorators.csrf import csrf_exempt from django.core.files.storage import FileSystemStorage from htmlmin.decorators import not_minified_response -def render(request, template, content={}): +# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # +# GENERAL UTILITIES # +# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # - template = 'OpenBench/{0}'.format(template) +class UnableToAuthenticate(Exception): + pass + +def render(request, template, content={}): data = content.copy() data.update({'config' : OpenBench.config.OPENBENCH_CONFIG}) @@ -56,8 +61,22 @@ def render(request, template, content={}): if request.user.is_authenticated and not profile.first(): data.update({'error' : data['config']['error']['fakeuser']}) - return django.shortcuts.render(request, template, data) + return django.shortcuts.render(request, 'OpenBench/{0}'.format(template), data) +def authenticate(request): + + try: + user = django.contrib.auth.authenticate( + username = request.POST['username'], + password = request.POST['password']) + + except Exception: + raise UnableToAuthenticate() + + if user is None: + raise UnableToAuthenticate() + + return user # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # ADMINISTRATIVE VIEWS # @@ -103,25 +122,22 @@ def login(request): # # # GET : Return the HTML template used for logging in a User # # # - # POST : Attempt to login the User and authenticate their credentials. # - # If their login is invalid, let them know. In all cases, return # - # the User back to the main page # + # POST : Attempt to login the User. If their login is invalid, let them # + # know. In all cases, return the User back to the main page # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # if request.method == 'GET': return render(request, 'login.html') - user = django.contrib.auth.authenticate( - username=request.POST['username'], - password=request.POST['password']) + try: + user = authenticate(request) + django.contrib.auth.login(request, user) + return django.http.HttpResponseRedirect('/index/') - if user is None: + except UnableToAuthenticate: return index(request, error='Unable to Authenticate User') - django.contrib.auth.login(request, user) - return django.http.HttpResponseRedirect('/index/') - def logout(request): # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # @@ -452,18 +468,19 @@ def newTest(request): # NETWORK MANAGEMENT VIEWS # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # -def networks(request, action=None, sha256=None): +def networks(request, action=None, sha256=None, client=False): # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # GET : There are three possible GET lookups. [1] Fetch a view of all # # the Networks on the framework. [2] Fetch a template to upload a # # new Network to the framework. [3] Download the contents of a # - # Network that is already saved on the framework. # + # Network that is already saved on the framework. Anyone may view # + # the list of Network weights, but only some may interact # # # - # POST : There are four possible POST lookups. Download, Upload, Default # - # and Delete. Downloads are open, but all others are gated by the # - # credentials of the User. # + # POST : There are three possible POST lookups. They are Upload, Default # + # and Delete. All of these are placed behind a login and approver # + # flag wall. This view is not meant to distribute Networks # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # @@ -471,24 +488,10 @@ def networks(request, action=None, sha256=None): networks = Network.objects.all().order_by('-id') return render(request, 'networks.html', {'networks' : networks}) - if action.upper() == 'DOWNLOAD': - - if not Network.objects.filter(sha256=sha256): - return index(request, error='No Network found with matching SHA256') - - netfile = os.path.join(MEDIA_ROOT, sha256) - fwrapper = FileWrapper(open(netfile, 'rb'), 8192) - response = FileResponse(fwrapper, content_type='application/octet-stream') - - response['Expires'] = (datetime.datetime.utcnow() + datetime.timedelta(days=7)).ctime() - response['Content-Length'] = os.path.getsize(netfile) - response['Content-Disposition'] = 'attachment; filename=' + sha256 - return response - if not request.user.is_authenticated: return django.http.HttpResponseRedirect('/login/') - if not Profile.objects.get(user=request.user).approver: + if not client and not Profile.objects.get(user=request.user).approver: return django.http.HttpResponseRedirect('/index/') if action.upper() == 'UPLOAD': @@ -510,7 +513,7 @@ def networks(request, action=None, sha256=None): Network.objects.create( sha256=sha256, name=request.POST['name'], - engine=engine, author=request.user.username); + engine=engine, author=request.user.username) return index(request) @@ -535,6 +538,20 @@ def networks(request, action=None, sha256=None): return django.http.HttpResponseRedirect('/networks/') + if action.upper() == 'DOWNLOAD': + + if not Network.objects.filter(sha256=sha256): + return index(request, error='No Network found with matching SHA256') + + netfile = os.path.join(MEDIA_ROOT, sha256) + fwrapper = FileWrapper(open(netfile, 'rb'), 8192) + response = FileResponse(fwrapper, content_type='application/octet-stream') + + response['Expires'] = (datetime.datetime.utcnow() + datetime.timedelta(days=7)).ctime() + response['Content-Length'] = os.path.getsize(netfile) + response['Content-Disposition'] = 'attachment; filename=' + sha256 + return response + # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # CLIENT HOOK VIEWS # @@ -545,8 +562,7 @@ def clientGetFiles(request): # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # - # GET : Return a URL pointing to the location of Cutechess-cli, as well # - # as any DLLs or Shared Object files needed for Cutechess-cli # + # GET : Return a URL to the location of Cutechess for Windows and Linux # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # @@ -562,10 +578,10 @@ def clientGetBuildInfo(request): # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # - data = {} # Return all engine-compiler information + data = {} for engine, config in OpenBench.config.OPENBENCH_CONFIG['engines'].items(): - data[engine] = config['build']['compilers'] - return HttpResponse(str(data)) + data[engine] = config['build'] + return HttpResponse(json.dumps(data)) @csrf_exempt @not_minified_response @@ -582,14 +598,23 @@ def clientGetWorkload(request): # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # Verify the User's credentials - user = django.contrib.auth.authenticate( - username=request.POST['username'], - password=request.POST['password']) - if user == None: return HttpResponse('Bad Credentials') + try: user = authenticate(request) + except UnableToAuthenticate: return HttpResponse('Bad Credentials') # getWorkload() will verify the integrity of the request return HttpResponse(OpenBench.utils.getWorkload(user, request)) +@csrf_exempt +@not_minified_response +def clientGetNetwork(request, sha256): + + # Verify the User's credentials + try: django.contrib.auth.login(request, authenticate(request)) + except UnableToAuthenticate: return HttpResponse('Bad Credentials') + + # Return the requested Neural Network file for the Client + return networks(request, action='DOWNLOAD', sha256=sha256, client=True) + @csrf_exempt @not_minified_response def clientWrongBench(request): @@ -603,10 +628,8 @@ def clientWrongBench(request): # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # Verify the User's credentials - user = django.contrib.auth.authenticate( - username=request.POST['username'], - password=request.POST['password']) - if user == None: return HttpResponse('Bad Credentials') + try: user = authenticate(request) + except UnableToAuthenticate: return HttpResponse('Bad Credentials') # Verify the Machine belongs to the User machine = Machine.objects.get(id=int(request.POST['machineid'])) @@ -646,10 +669,8 @@ def clientSubmitNPS(request): # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # Verify the User's credentials - user = django.contrib.auth.authenticate( - username=request.POST['username'], - password=request.POST['password']) - if user == None: return HttpResponse('Bad Credentials') + try: user = authenticate(request) + except UnableToAuthenticate: return HttpResponse('Bad Credentials') # Verify the Machine belongs to the User machine = Machine.objects.get(id=int(request.POST['machineid'])) @@ -672,10 +693,8 @@ def clientSubmitError(request): # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # Verify the User's credentials - user = django.contrib.auth.authenticate( - username=request.POST['username'], - password=request.POST['password']) - if user == None: return HttpResponse('Bad Credentials') + try: user = authenticate(request) + except UnableToAuthenticate: return HttpResponse('Bad Credentials') # Verify the Machine belongs to the User machine = Machine.objects.get(id=int(request.POST['machineid'])) @@ -698,10 +717,8 @@ def clientSubmitError(request): def clientSubmitResults(request): # Verify the User's credentials - user = django.contrib.auth.authenticate( - username=request.POST['username'], - password=request.POST['password']) - if user == None: return HttpResponse('Bad Credentials') + try: user = authenticate(request) + except UnableToAuthenticate: return HttpResponse('Bad Credentials') # Verify the Machine belongs to the User machine = Machine.objects.get(id=int(request.POST['machineid']))