From 27e6017bfb8508b4c84689cac4eb08946a8a1177 Mon Sep 17 00:00:00 2001 From: andrew Date: Wed, 17 May 2023 02:05:53 -0400 Subject: [PATCH] Finalize? --- Books/books.json | 7 + Client/Client.py | 261 +++++++++++++----------------- Engines/Laser.json | 2 +- OpenBench/config.py | 2 +- OpenBench/urls.py | 18 +-- OpenBench/utils.py | 134 +++++---------- OpenBench/views.py | 209 +++++++++++------------- Templates/OpenBench/machines.html | 2 - Templates/OpenBench/test.html | 2 - 9 files changed, 268 insertions(+), 369 deletions(-) diff --git a/Books/books.json b/Books/books.json index 883dc42..2aa0b49 100644 --- a/Books/books.json +++ b/Books/books.json @@ -1,35 +1,42 @@ { "2moves_v1.epd" : { + "name" : "2moves_v1.epd", "sha" : "7bec98239836f219dc41944a768c0506abed950aaec48da69a0782643e90f237", "source" : "https://raw.githubusercontent.com/AndyGrant/OpenBench/master/Books/2moves_v1.epd.zip" }, "8moves_v3.epd" : { + "name" : "8moves_v3.epd", "sha" : "1f055af431656f09ee6a09d2448e0b876125f78bb7b404fca2031c403a1541e5", "source" : "https://raw.githubusercontent.com/AndyGrant/OpenBench/master/Books/8moves_v3.epd.zip" }, "3moves_FRC.epd" : { + "name" : "3moves_FRC.epd", "sha" : "6bf81e1ada6a3306bbc8356f7bca1e2984a2828d658799992d5443b7179c934d", "source" : "https://raw.githubusercontent.com/AndyGrant/OpenBench/master/Books/3moves_FRC.epd.zip" }, "4moves_noob.epd" : { + "name" : "4moves_noob.epd", "sha" : "4be746a91e3f8af0c9344b1e72d611e9fcfe486843867a55760970a4896f284d", "source" : "https://raw.githubusercontent.com/AndyGrant/OpenBench/master/Books/4moves_noob.epd.zip" }, "Pohl.epd" : { + "name" : "Pohl.epd", "sha" : "b3e64e0dab84cf451a9ac7ef031f5a2bbcf16c7e21be95298fb03cbf021f5466", "source" : "https://raw.githubusercontent.com/AndyGrant/OpenBench/master/Books/Pohl.epd.zip" }, "Pohl.pgn" : { + "name" : "Pohl.pgn", "sha" : "aaa7559c5d94e592fe5cca3586cb099d8fc5f13428d4ce84afc4b97811241c7e", "source" : "https://raw.githubusercontent.com/AndyGrant/OpenBench/master/Books/Pohl.pgn.zip" }, "DFRC.epd" : { + "name" : "DFRC.epd", "sha" : "648c447ef40614a44d13b78911e81470d8ddb0d3b2711c1b180e990871f5db4f", "source" : "https://raw.githubusercontent.com/AndyGrant/OpenBench/master/Books/DFRC.epd.zip" } diff --git a/Client/Client.py b/Client/Client.py index 1a1ed5a..b289485 100644 --- a/Client/Client.py +++ b/Client/Client.py @@ -52,7 +52,7 @@ from itertools import combinations_with_replacement TIMEOUT_HTTP = 30 # Timeout in seconds for HTTP requests TIMEOUT_ERROR = 10 # Timeout in seconds when any errors are thrown TIMEOUT_WORKLOAD = 30 # Timeout in seconds between workload requests -CLIENT_VERSION = '7' # Client version to send to the Server +CLIENT_VERSION = '8' # Client version to send to the Server SYZYGY_WDL_PATH = None # Pathway to WDL Syzygy Tables FLEET_MODE = False # Exit when there are no workloads @@ -76,11 +76,6 @@ ERRORS = { IS_WINDOWS = platform.system() == 'Windows' IS_LINUX = platform.system() != 'Windows' -COMPILERS = {} # Compiler for each Engine, + CPU Flags -CPUINFO = '' # Result of ``echo | gcc -march=native -E -dM -`` -OSNAME = '%s %s' % (platform.system(), platform.release()) -DEBUG = True - SYSTEM_COMPILERS = {} SYSTEM_GIT_TOKENS = {} SYSTEM_CPU_FLAGS = [] @@ -102,28 +97,28 @@ def get_version(program): try: process = Popen([program, '--version'], stdout=PIPE, stderr=PIPE) - stdout = process.communicate()[0].decode('utf-8') + stdout = process.communicate()[0].decode('utf-8') return re.search(r'\d+\.\d+(\.\d+)?', stdout).group() except: process = Popen([program, 'version'], stdout=PIPE, stderr=PIPE) - stdout = process.communicate()[0].decode('utf-8') + stdout = process.communicate()[0].decode('utf-8') return re.search(r'\d+\.\d+(\.\d+)?', stdout).group() -def locate_utility(util, force_exit=True, report_error=True, report_found=True): +def locate_utility(util, force_exit=True, report_error=True): try: - version = get_version(util) - if report_found: - print('Located %s (%s)' % (util, version)) - return version + return get_version(util) except Exception: + if report_error: print('[Error] Unable to locate %s' % (util)) + if force_exit: sys.exit() - return False + + return False def scan_for_compilers(data): @@ -134,7 +129,7 @@ def scan_for_compilers(data): for engine, build_info in data.items(): # Private engines don't need to be compiled - if build_info['private']: continue + if 'artifacts' in build_info: continue # Try to find at least one working compiler for compiler in build_info['compilers']: @@ -166,7 +161,7 @@ def scan_for_private_tokens(data): for engine, build_info in data.items(): # Public engines don't need access tokens - if not build_info['private']: continue + if not 'artifacts' in build_info: continue # Private engines expect a credentials.engine file for the main repo has_token = os.path.exists('credentials.%s' % (engine.replace(' ', '').lower())) @@ -234,7 +229,8 @@ def init_client(arguments): def cleanup_client(): SECONDS_PER_DAY = 60 * 60 * 24 - SECONDS_PER_MONTH = SECONDS_PER_DAY * 30 + SECONDS_PER_WEEK = SECONDS_PER_DAY * 7 + SECONDS_PER_MONTH = SECONDS_PER_WEEK * 4 file_age = lambda x: time.time() - os.path.getmtime(x) @@ -243,7 +239,7 @@ def cleanup_client(): os.remove(os.path.join('PGNs', file)) for file in os.listdir('Engines'): - if file_age(os.path.join('Engines', file)) > SECONDS_PER_DAY: + if file_age(os.path.join('Engines', file)) > SECONDS_PER_WEEK: os.remove(os.path.join('Engines', file)) for file in os.listdir('Networks'): @@ -305,7 +301,7 @@ def try_until_success(mesg): print('[Error]', mesg); if FLEET_MODE: sys.exit() time.sleep(TIMEOUT_ERROR) - if DEBUG: traceback.print_exc() + traceback.print_exc() return __try_until_success return _try_until_success @@ -330,7 +326,7 @@ def unzip_delete_file(source, outdir): def make_command(arguments, engine, src_path, network_path): command = 'make %s=%s EXE=%s -j%d' % ( - ['CC', 'CXX']['++' in SYSTEM_COMPILERS[engine]], SYSTEM_COMPILERS[engine], engine, arguments.threads) + ['CC', 'CXX']['++' in SYSTEM_COMPILERS[engine][0]], SYSTEM_COMPILERS[engine][0], engine, arguments.threads) if network_path != None: path = os.path.relpath(os.path.abspath(network_path), src_path) @@ -461,7 +457,7 @@ def server_download_cutechess(arguments): # 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') + timeout=TIMEOUT_HTTP).json()['location'] if arguments.proxy: source = 'https://ghproxy.com/' + source @@ -477,7 +473,7 @@ def server_download_cutechess(arguments): # 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') + timeout=TIMEOUT_HTTP).json()['location'] if arguments.proxy: source = 'https://ghproxy.com/' + source @@ -492,6 +488,8 @@ def server_download_cutechess(arguments): @try_until_success(mesg=ERRORS['configure']) def server_configure_worker(arguments): + global SYSTEM_MACHINE_ID, SYSTEM_SECRET_TOKEN + # Server tells us how to build or obtain binaries target = url_join(arguments.server, 'clientGetBuildInfo') data = requests.get(target, timeout=TIMEOUT_HTTP).json() @@ -539,8 +537,10 @@ def server_configure_worker(arguments): with open('machine.txt', 'w') as fout: fout.write(str(response['machine_id'])) + # Save it within the code as well for future requests + SYSTEM_MACHINE_ID = str(response['machine_id']) + # Save the secret token, to send with all future requests - global SYSTEM_SECRET_TOKEN SYSTEM_SECRET_TOKEN = response['secret'] @try_until_success(mesg=ERRORS['request']) @@ -548,28 +548,43 @@ def server_request_workload(arguments): print('\nRequesting Workload from Server...') - supported = ' '.join(COMPILERS.keys() - ['cpuflags']) + payload = { 'machine_id' : SYSTEM_MACHINE_ID, 'secret' : SYSTEM_SECRET_TOKEN } + target = url_join(arguments.server, 'clientGetWorkload') + response = requests.post(target, data=payload, timeout=TIMEOUT_HTTP).json() + + # The 'error' header is included if there was an issue + if 'error' in response: + print('[Error] %s\n' % (response['error'])) + sys.exit() + + # Log the start of a new Workload + if 'workload' in response: + engine = response['workload']['test']['engine'] + dev = response['workload']['test']['dev' ]['name'] + base = response['workload']['test']['base' ]['name'] + print('Workload [%s] %s vs %s\n' % (engine, dev, base)) + + return None if 'workload' not in response else response['workload'] + +def server_report_nps(arguments, workload, dev_nps, base_nps): payload = { - 'username' : arguments.username, 'threads' : arguments.threads, - 'password' : arguments.password, 'ncutechess' : arguments.ncutechess, - 'machineid' : machine_id, 'osname' : OSNAME, - 'supported' : supported, 'syzygy_wdl' : bool(SYZYGY_WDL_PATH), - 'version' : CLIENT_VERSION, 'cpuflags' : COMPILERS['cpuflags'], + 'machine_id' : SYSTEM_MACHINE_ID, + 'secret' : SYSTEM_SECRET_TOKEN, + 'nps' : (dev_nps + base_nps) // 2 } - target = url_join(arguments.server, 'clientGetWorkload') - return requests.post(target, data=payload, timeout=TIMEOUT_HTTP) + target = url_join(arguments.server, 'clientSubmitNPS') + response = requests.post(target, data=payload, timeout=TIMEOUT_ERROR) def server_report_missing_artifact(arguments, workload, branch, artifact_name, artifact_json): payload = { - 'username' : arguments.username, - 'password' : arguments.password, - 'testid' : workload['test']['id'], - 'machineid' : workload['machine']['id'], - 'error' : 'Artifact %s missing' % (artifact_name), - 'logs' : json.dumps(artifact_json, indent=2), + 'machine_id' : SYSTEM_MACHINE_ID, + 'secret' : SYSTEM_SECRET_TOKEN, + 'test_id' : workload['test']['id'], + 'error' : 'Artifact %s missing' % (artifact_name), + 'logs' : json.dumps(artifact_json, indent=2), } target = url_join(arguments.server, 'clientSubmitError') @@ -578,43 +593,16 @@ def server_report_missing_artifact(arguments, workload, branch, artifact_name, a def server_report_build_fail(arguments, workload, branch, compiler_output): payload = { - 'username' : arguments.username, - 'password' : arguments.password, - 'testid' : workload['test']['id'], - 'machineid' : workload['machine']['id'], - 'error' : '%s build failed' % (workload['test'][branch]['name']), - 'logs' : compiler_output, + 'machine_id' : SYSTEM_MACHINE_ID, + 'secret' : SYSTEM_SECRET_TOKEN, + 'test_id' : workload['test']['id'], + 'error' : '%s build failed' % (workload['test'][branch]['name']), + 'logs' : compiler_output, } target = url_join(arguments.server, 'clientSubmitError') requests.post(target, data=payload, timeout=TIMEOUT_HTTP) -def server_report_bad_bench(arguments, workload, branch, bench): - - branch = workload['test'][branch] - - data = { - 'username' : arguments.username, 'testid' : workload['test']['id'], - 'password' : arguments.password, 'machineid' : workload['machine']['id'], - 'correct' : branch['bench'], 'engine' : branch['name'], - 'wrong' : bench, - } - - target = url_join(arguments.server, 'clientWrongBench') - requests.post(target, data=data, timeout=TIMEOUT_HTTP) - -def server_report_nps(arguments, workload, dev_nps, base_nps): - - data = { - 'username' : arguments.username, - 'password' : arguments.password, - 'machineid' : workload['machine']['id'], - 'nps' : (dev_nps + base_nps) // 2 - } - - target = url_join(arguments.server, 'clientSubmitNPS') - requests.post(target, data=data, timeout=TIMEOUT_ERROR) - def server_report_engine_error(arguments, workload, cutechess_str, pgn): pairing = cutechess_str.split('(')[1].split(')')[0] @@ -625,32 +613,48 @@ def server_report_engine_error(arguments, workload, cutechess_str, pgn): error = error.replace('Black', '-'.join(black.split('-')[1:]).rstrip()) payload = { - 'username' : arguments.username, - 'password' : arguments.password, - 'testid' : workload['test']['id'], - 'machineid' : workload['machine']['id'], - 'error' : error, - 'logs' : pgn, + 'machine_id' : SYSTEM_MACHINE_ID, + 'secret' : SYSTEM_SECRET_TOKEN, + 'test_id' : workload['test']['id'], + 'error' : error, + 'logs' : pgn, } target = url_join(arguments.server, 'clientSubmitError') requests.post(target, data=payload, timeout=TIMEOUT_HTTP) +def server_report_bad_bench(arguments, workload, branch, bench): + + payload = { + 'machine_id' : SYSTEM_MACHINE_ID, + 'secret' : SYSTEM_SECRET_TOKEN, + 'test_id' : workload['test']['id'], + 'engine' : workload['test'][branch]['name'], + 'correct' : workload['test'][branch]['bench'], + 'wrong' : bench, + } + + target = url_join(arguments.server, 'clientWrongBench') + requests.post(target, data=payload, timeout=TIMEOUT_HTTP) + def server_report_results(arguments, workload, stats): wins, losses, draws, crashes, timelosses = stats payload = { - 'username' : arguments.username, 'wins' : wins, - 'password' : arguments.password, 'losses' : losses, - 'machineid' : workload['machine']['id'], 'draws' : draws, - 'resultid' : workload['result']['id'], 'crashes' : crashes, - 'testid' : workload['test']['id'], 'timeloss' : timelosses, + 'machine_id' : SYSTEM_MACHINE_ID, + 'secret' : SYSTEM_SECRET_TOKEN, + 'test_id' : workload['test']['id'], + 'result_id' : workload['result']['id'], + 'wins' : wins, + 'losses' : losses, + 'draws' : draws, + 'crashes' : crashes, + 'timeloss' : timelosses, } target = url_join(arguments.server, 'clientSubmitResults') - try: return requests.post(target, data=payload, timeout=TIMEOUT_HTTP).text - except: print('[NOTE] Unable To Reach Server'); return 'Unable' + return requests.post(target, data=payload, timeout=TIMEOUT_HTTP).json() # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # @@ -658,45 +662,6 @@ def server_report_results(arguments, workload, stats): # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # -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') - if not FLEET_MODE: 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 - - # We must match the server's version number - if raw_text == 'Bad Client Version': - print('[ERROR] Client Version Outdated') - sys.exit() - - # 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' ) @@ -811,7 +776,7 @@ def download_engine(arguments, workload, branch, network): commit_sha = workload['test'][branch]['sha'] source = workload['test'][branch]['source'] build_path = workload['test']['build']['path'] - private = workload['engine']['private'] + private = 'artifacts' in workload['test']['build'] # Naming as Engine-CommitSha[:8]-NetworkSha[:8] final_name = '%s-%s' % (engine, commit_sha.upper()[:8]) @@ -830,11 +795,14 @@ def download_engine(arguments, workload, branch, network): auth_headers = { 'Authorization' : 'token %s' % fin.readlines()[0].rstrip() } artifacts = requests.get(url=source, headers=auth_headers).json()['artifacts'] + # For sanity, just avoid using PEXT/BMI2 on AMD Chips + ryzen = 'AMD' in SYSTEM_CPU_NAME.upper() + ryzen = 'RYZEN' in SYSTEM_CPU_NAME.upper() or ryzen + # Construct the artifact string for the desired binary - old_ryzen = '__znver1' in str(CPUINFO) or '__znver2' in str(CPUINFO) os_string = ['windows', 'linux' ][IS_LINUX] - avx_string = ['avx2' , 'avx512']['__AVX512VNNI__ 1' in str(CPUINFO)] - bit_string = ['popcnt' , 'pext' ]['__BMI2__ 1' in str(CPUINFO) and not old_ryzen] + avx_string = ['avx2' , 'avx512']['AVX512_VNNI' in str(SYSTEM_CPU_FLAGS)] + bit_string = ['popcnt' , 'pext' ]['BMI2' in str(SYSTEM_CPU_FLAGS) and not ryzen] desired = '%s-%s-%s' % (os_string, avx_string, bit_string) # Search for our artifact in the list provided @@ -903,7 +871,7 @@ def run_benchmarks(arguments, workload, branch, engine, network): cores = arguments.threads queue = multiprocessing.Queue() name = workload['test'][branch]['name'] - private = workload['engine']['private'] + private = 'artifacts' in workload['test']['build'] print('\nRunning %dx Benchmarks for %s' % (cores, name)) for ii in range(cores): @@ -941,7 +909,7 @@ def build_cutechess_command(arguments, workload, dev_cmd, base_cmd, nps, cuteche base_options += ' SyzygyPath=%s' % (path) # Add EvalFile to the options for Private engines using Networks - if workload['engine']['private']: + if 'artifacts' in workload['test']['build']: dev_network = workload['test']['dev' ]['network'] if dev_network and dev_network != 'None': @@ -1031,22 +999,26 @@ def run_and_parse_cutechess(arguments, workload, concurrency, command, cutechess # Only report scores after every eight games score = list(map(int, score_reason.split()[0:5:2])) - if ((sum(score) - sum(sent)) % workload['test']['report_rate'] != 0): continue + if ((sum(score) - sum(sent)) % workload['test']['report_rate'] != 0): + continue - # Report to the server but allow failed reports to delay - wld = [score[ii] - sent[ii] for ii in range(3)] - stats = wld + [crashes, timelosses] - status = server_report_results(arguments, workload, stats) + try: + # Report new results to the server + wld = [score[ii] - sent[ii] for ii in range(3)] + stats = wld + [crashes, timelosses] + status = server_report_results(arguments, workload, stats) - # Check for the task being aborted, or Client being killed - if status.upper() == 'STOP' or os.path.isfile('openbench.exit'): - kill_cutechess(cutechess) - return - - # If the update was succesful reset the results - if status.upper() != 'UNABLE': + except: + # Failed to connect, but we can delay the reports until later + print('[NOTE] Unable To Reach Server'); crashes = timelosses = 0 sent = score[::] + continue + + # Check for openbench.exit, or server instructing us to exit + if os.path.isfile('openbench.exit') or 'stop' in status: + kill_cutechess(cutechess) + return # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # @@ -1102,19 +1074,16 @@ if __name__ == '__main__': server_download_cutechess(arguments) server_configure_worker(arguments) - exit(1) - while True: - try: - # Request a new workload + # Cleanup on each workload request cleanup_client() - response = server_request_workload(arguments) - workload = check_workload_response(arguments, response) # Fleet workers exit when there are no workloads - if workload: complete_workload(arguments, workload) + if workload := server_request_workload(arguments): + complete_workload(arguments, workload) elif FLEET_MODE: break + else: time.sleep(TIMEOUT_WORKLOAD) # Check for exit signal via openbench.exit if os.path.isfile('openbench.exit'): diff --git a/Engines/Laser.json b/Engines/Laser.json index 6be10ae..9211618 100644 --- a/Engines/Laser.json +++ b/Engines/Laser.json @@ -9,7 +9,7 @@ "win_adj" : "movecount=3 score=400", "draw_adj" : "movenumber=40 movecount=8 score=10", - "build": { + "build" : { "path" : "src", "compilers" : ["g++"], "cpuflags" : ["POPCNT"] diff --git a/OpenBench/config.py b/OpenBench/config.py index 1c5cd8a..b685293 100644 --- a/OpenBench/config.py +++ b/OpenBench/config.py @@ -38,7 +38,7 @@ REQUIRE_MANUAL_REGISTRATION = True # Disable the public facing registration pag OPENBENCH_CONFIG = { # Server Client version control - 'client_version' : '7', + 'client_version' : '8', # Generic Error Messages useful to those setting up their own instance 'error' : { diff --git a/OpenBench/urls.py b/OpenBench/urls.py index 871c710..1d8a54a 100644 --- a/OpenBench/urls.py +++ b/OpenBench/urls.py @@ -60,15 +60,15 @@ urlpatterns = [ django.urls.path(r'scripts/', OpenBench.views.scripts), # 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'clientWorkerInfo/', OpenBench.views.clientWorkerInfo), - 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), - django.urls.path(r'clientSubmitResults/', OpenBench.views.clientSubmitResults), + django.urls.path(r'clientGetFiles/', OpenBench.views.client_get_files), + django.urls.path(r'clientGetBuildInfo/', OpenBench.views.client_get_build_info), + django.urls.path(r'clientWorkerInfo/', OpenBench.views.client_worker_info), + django.urls.path(r'clientGetWorkload/', OpenBench.views.client_get_workload), + django.urls.path(r'clientGetNetwork//', OpenBench.views.client_get_network), + django.urls.path(r'clientWrongBench/', OpenBench.views.client_wrong_bench), + django.urls.path(r'clientSubmitNPS/', OpenBench.views.client_submit_nps), + django.urls.path(r'clientSubmitError/', OpenBench.views.client_submit_error), + django.urls.path(r'clientSubmitResults/', OpenBench.views.client_submit_results), # Redirect anything else to the Index django.urls.path(r'', OpenBench.views.index), diff --git a/OpenBench/utils.py b/OpenBench/utils.py index 3792d7d..6c43bf7 100644 --- a/OpenBench/utils.py +++ b/OpenBench/utils.py @@ -424,101 +424,61 @@ def get_machine(machineid, user, info): return machine - -def getMachine(machineid, user, osname, threads): - - # Create a new Machine if needed - if machineid == 'None': - return Machine(user=user, osname=osname, threads=threads) - - # Fetch and verify the requested Machine - try: machine = Machine.objects.get(id=int(machineid)) - except: return 'Bad Machine' - if machine.user != user: return 'Bad Machine' - if machine.osname != osname: return 'Bad Machine' - - # Update the Machine's running status - machine.threads = threads - machine.mnps = 0.00 - return machine - -def getResult(test, machine): - - # Try to find an already existing Result - results = Result.objects.filter(test=test) - results = list(results.filter(machine=machine)) - if results != []: return results[0] - - # Create a new Result if none is found - return Result(test=test, machine=machine) - -def getWorkload(user, request): - - # Extract worker information - machineid = request.POST['machineid'] - osname = request.POST['osname' ] - threads = request.POST['threads' ] - - # If we don't get a Machine back, there was an error - machine = getMachine(machineid, user, osname, int(threads)) - if type(machine) == str: return machine +def get_workload(machine): # Check to make sure we have a potential workload - tests = get_valid_workloads(machine, request) - if not tests: return 'None' + if not (tests := get_valid_workloads(machine)): + return {} # Select from valid workloads and create a Result object - test = select_workload(machine, tests) - result = getResult(test, machine) + test = select_workload(machine, tests) + result = Result(test=test, machine=machine) - # Success. Update the Machine's status and save everything + # Update the Machine's status and save everything machine.workload = test; machine.save(); result.save() - return str(workload_to_dictionary(test, result, machine)) + return { 'workload' : workload_to_dictionary(test, result) } -# Purely Helper functions for getWorkload() +# Purely Helper functions for get_workload() -def get_valid_workloads(machine, request): +def get_valid_workloads(machine): # Skip anything that is not running tests = get_active_tests() - # Skip engines that the Machine cannot build + # Skip engines that the Machine cannot handle for engine in OPENBENCH_CONFIG['engines'].keys(): - if engine not in request.POST['supported'].split(): + if engine not in machine.info['supported']: tests = tests.exclude(engine=engine) - # Skip engines that the Machine cannot run - for engine, data in OPENBENCH_CONFIG['engines'].items(): - for flag in data['build']['cpuflags']: - if flag not in request.POST['cpuflags'].split(): - tests = tests.exclude(engine=engine) - # Skip tests with unmet Syzygy requirments - if request.POST['syzygy_wdl'] == 'False': + if not machine.info['syzygy_wdl']: tests = tests.exclude(syzygy_adj='REQUIRED') tests = tests.exclude(syzygy_wdl='REQUIRED') # Skip tests that would waste available Threads or exceed them - ncutechess = int(request.POST['ncutechess']) - options = [x for x in tests if test_maps_onto_thread_count(machine, x, ncutechess)] + threads = machine.info['concurrency'] + ncutechess = machine.info['ncutechesses'] + hyperthreads = machine.info['physical_cores'] < threads + options = [x for x in tests if + test_maps_onto_thread_count(x, threads, ncutechess, hyperthreads)] # Finally refine for tests of the highest priority if not options: return [] highest_prio = max(options, key=lambda x: x.priority).priority return [test for test in options if test.priority == highest_prio] -def test_maps_onto_thread_count(machine, test, ncutechess): +def test_maps_onto_thread_count(test, threads, ncutechess, hyperthreads): dev_threads = int(extractOption(test.devoptions, 'Threads')) base_threads = int(extractOption(test.baseoptions, 'Threads')) # Each individual cutechess copy must have access to sufficient Threads - if max(dev_threads, base_threads) > (machine.threads / ncutechess): + if max(dev_threads, base_threads) > (threads / ncutechess): return False - # Intentional Thread Imbalance, or evenly distributed Threads - return dev_threads != base_threads or (machine.threads / ncutechess) % dev_threads == 0 + # Intentional Thread Imbalance, or real cores, or evenly distributed + return dev_threads != base_threads or not hyperthreads or (threads / ncutechess) % dev_threads == 0 def select_workload(machine, tests, variance=0.25): @@ -526,7 +486,7 @@ def select_workload(machine, tests, variance=0.25): table = { test : 0 for test in tests } for m in getRecentMachines(): if m.workload in tests and m != machine: - table[m.workload] = table[m.workload] + m.threads + table[m.workload] = table[m.workload] + m.info['concurrency'] # Find the tests most deserving of resources currently ratios = [table[test] / test.throughput for test in tests] @@ -545,36 +505,22 @@ def select_workload(machine, tests, variance=0.25): # Fallback to simply doing the least attention given test return tests[random.choice(lowest_idxs)] -def workload_to_dictionary(test, result, machine): +def workload_to_dictionary(test, result): - # Convert the workload into a Dictionary to be used by the Client. - # 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 }, - - 'result' : { 'id' : result.id }, - - 'engine' : { - 'private' : OPENBENCH_CONFIG['engines'][test.engine]['private'] - }, - - 'test' : { + 'result' : { 'id' : result.id }, + 'test' : { 'id' : test.id, 'engine' : test.engine, 'timecontrol' : test.timecontrol, 'syzygy_wdl' : test.syzygy_wdl, - 'syzygy_adj' : test.syzygy_adj, 'win_adj' : test.win_adj, 'draw_adj' : test.draw_adj, - 'report_rate' : test.report_rate, 'workload_size' : test.workload_size, - 'nps' : OPENBENCH_CONFIG['engines'][test.engine]['nps'], 'build' : OPENBENCH_CONFIG['engines'][test.engine]['build'], 'book' : OPENBENCH_CONFIG['books'][test.bookname], @@ -593,28 +539,28 @@ def workload_to_dictionary(test, result, machine): 'network' : test.basenetwork, }, }, - }) + } -def updateTest(request, user): +def update_test(request, machine): # New results from the Worker - wins = int(request.POST['wins']) - losses = int(request.POST['losses']) - draws = int(request.POST['draws']) - crashes = int(request.POST['crashes']) + wins = int(request.POST['wins' ]) + losses = int(request.POST['losses' ]) + draws = int(request.POST['draws' ]) + crashes = int(request.POST['crashes' ]) timeloss = int(request.POST['timeloss']) games = wins + losses + draws # Worker knows where to save the results - machineid = int(request.POST['machineid']) - resultid = int(request.POST['resultid']) - testid = int(request.POST['testid']) + machineid = int(request.POST['machine_id']) + resultid = int(request.POST['result_id' ]) + testid = int(request.POST['test_id' ]) # Prevent updating a finished test test = Test.objects.get(id=testid) if test.finished or test.deleted: - return 'Stop' + return { 'stop' : True } # Tally up the updated WLD stats swins = test.wins + wins @@ -642,11 +588,11 @@ def updateTest(request, user): sprt = 0.0 # Hack to "update" the currentllr # Update total games played by the Player - Profile.objects.filter(user=user).update(games=F('games') + games) - Profile.objects.get(user=user).save() + Profile.objects.filter(user=machine.user).update(games=F('games') + games) + Profile.objects.get(user=machine.user).save() # Update the datetime in the Machine - Machine.objects.get(id=machineid).save() + machine.save() # Update individual Result entry for the Player Result.objects.filter(id=resultid).update( @@ -665,4 +611,4 @@ def updateTest(request, user): # Force a refresh of the updated field when finished if finished: Test.objects.get(id=testid).save() - return ['None', 'Stop'][finished] + return [{}, {'stop' : True}][finished] diff --git a/OpenBench/views.py b/OpenBench/views.py index 86539d4..258a2a2 100644 --- a/OpenBench/views.py +++ b/OpenBench/views.py @@ -31,7 +31,6 @@ from OpenBench.models import * from django.contrib.auth.models import User from OpenSite.settings import MEDIA_ROOT -from ipware import get_client_ip from wsgiref.util import FileWrapper from django.db.models import F from django.http import HttpResponse, FileResponse, JsonResponse @@ -88,28 +87,6 @@ def authenticate(request, requireEnabled=False): return user -def authenticate_client(request): - - # Fetch the Machine associated with the Client Request - try: machine = Machine.objects.get(id=int(request.POST['machineid'])) - except: raise Exception('Bad Machine') - - # Try to compare the saved IP address of the machine - client_ip, _ = get_client_ip(request) - - # Authenticate via comparing current to recent IP addresses ( Fast ) - if client_ip and machine.lastaddr == str(client_ip): - return User.objects.get(username=request.POST['username']), machine - - # Authenticate the User associated with the Client Request ( Slow ) - try: user = authenticate(request, True) - except: raise Exception('Bad Credentials') - - # After Authentication, we may save the Client's IP Address for later - if client_ip: machine.lastaddr = str(client_ip); machine.save() - - return user, machine - # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # ADMINISTRATIVE VIEWS # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # @@ -626,16 +603,36 @@ def scripts(request): # CLIENT HOOK VIEWS # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # -@not_minified_response -def clientGetFiles(request): +def client_verify_worker(request): + + ## Returns the machine, or None. Returns a JsonResponse or None. + ## Presence of a JsonResponse indicates a failure to verify + + # Get the machine, assuming it exists + try: machine = Machine.objects.get(id=int(request.POST['machine_id'])) + except: return None, JsonResponse({ 'error' : 'Bad Machine Id' }) + + # Ensure the Client is using the same version as the Server + if machine.info['client_ver'] != OpenBench.config.OPENBENCH_CONFIG['client_version']: + expected_ver = OpenBench.config.OPENBENCH_CONFIG['client_version'] + return machine, JsonResponse({ 'error' : 'Bad Client Version: Expected %s' % (expected_ver)}) + + # Use the secret token as our soft verification + if machine.secret != request.POST['secret']: + return machine, JsonResponse({ 'error' : 'Invalid Secret Token' }) + + return machine, None + +@csrf_exempt +def client_get_files(request): ## Location of static compile of Cutechess for Windows and Linux. ## OpenBench does not serve these files, but points to a repo ideally. - return HttpResponse(OpenBench.config.OPENBENCH_CONFIG['corefiles']) + return JsonResponse( {'location' : OpenBench.config.OPENBENCH_CONFIG['corefiles'] }) -@not_minified_response -def clientGetBuildInfo(request): +@csrf_exempt +def client_get_build_info(request): ## Information pulled from the config about how to build each engine. ## Toss in a private flag as well to indicate the need for Github Tokens. @@ -643,12 +640,10 @@ def clientGetBuildInfo(request): data = {} for engine, config in OpenBench.config.OPENBENCH_CONFIG['engines'].items(): data[engine] = config['build'] - data[engine]['private'] = config['private'] return JsonResponse(data) @csrf_exempt -@not_minified_response -def clientWorkerInfo(request): +def client_worker_info(request): # Verify the User's credentials try: user = authenticate(request, True) @@ -663,45 +658,47 @@ def clientWorkerInfo(request): if not machine: return JsonResponse({ 'error' : 'Bad Machine Id' }) - # Save the machine's latest information + # Save the machine's latest information and Secret Token for this session + machine.info = info machine.secret = secrets.token_hex(32) + + # Tag engines that the Machine can build and/or run with binaries + machine.info['supported'] = [] + for engine, data in OpenBench.config.OPENBENCH_CONFIG['engines'].items(): + + # Must have all CPU flags, for both Public and Private engines + if any([flag not in machine.info['cpu_flags'] for flag in data['build']['cpuflags']]): + continue + + # Private engines must have, or think they have, a Git Token + if data['private'] and engine not in machine.info['tokens']: + continue + + # Public engines must have a compiler of a sufficient version + if not data['private'] and engine not in machine.info['compilers'].keys(): + continue + + # All requirements are met, and this Machine can play with the given engine + machine.info['supported'].append(engine) + + # Finish up machine.save() # Pass back the Machine Id, and Secret Token for this session return JsonResponse({ 'machine_id' : machine.id, 'secret' : machine.secret }) @csrf_exempt -@not_minified_response -def clientGetWorkload(request): +def client_get_workload(request): - # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # - # # - # POST : Return a Dictionary of data in order to complete a workload. If # - # there are no tests for the User, 'None' will be returned. If we # - # cannot authenticate the User, 'Bad Credentials' is returned. If # - # the posted Machine does not belong the the User, 'Bad Machine' # - # is returned. # - # # - # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # + # Pass along any error messages if they appear + machine, response = client_verify_worker(request) + if response != None: return response - # Verify the User's credentials - try: user = authenticate(request, True) - except UnableToAuthenticate: return HttpResponse('Bad Credentials') - - # Make sure the Client passed its version number - if 'version' not in request.POST: - return HttpResponse('Bad Client Version') - - # Make sure the Client & Server version numbers match - if request.POST['version'] != OpenBench.config.OPENBENCH_CONFIG['client_version']: - return HttpResponse('Bad Client Version') - - # getWorkload() will verify the integrity of the request - return HttpResponse(OpenBench.utils.getWorkload(user, request)) + # Contains keys 'workload', otherwise none + return JsonResponse(OpenBench.utils.get_workload(machine)) @csrf_exempt -@not_minified_response -def clientGetNetwork(request, sha256): +def client_get_network(request, sha256): # Verify the User's credentials try: django.contrib.auth.login(request, authenticate(request, True)) @@ -711,8 +708,7 @@ def clientGetNetwork(request, sha256): return networks(request, action='DOWNLOAD', sha256=sha256, client=True) @csrf_exempt -@not_minified_response -def clientWrongBench(request): +def client_wrong_bench(request): # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # @@ -722,99 +718,84 @@ def clientWrongBench(request): # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # - # Authenticate the User/Machine combination - try: user, machine = authenticate_client(request) - except Exception as error: return HttpResponse(str(error)) + # Pass along any error messages if they appear + machine, response = client_verify_worker(request) + if response != None: return response # Find and stop the test with the bad bench if int(request.POST['wrong']) != 0: - test = Test.objects.get(id=int(request.POST['testid'])) + test = Test.objects.get(id=int(request.POST['test_id'])) test.finished = True; test.save() # Collect information on the Error - wrong = request.POST['wrong'] - correct = request.POST['correct'] + wrong = int(request.POST['wrong']) + correct = int(request.POST['correct']) name = request.POST['engine'] - # Format a nice Error message - message = 'Got {0} Expected {1} for {2}' - message = message.format(wrong, correct, name) - # Log the error into the Events table LogEvent.objects.create( - author = user.username, - summary = message, + author = machine.user.username, + summary = 'Got %d Expected %d for %s' % (wrong, correct, name), log_file = '', - machine_id = int(request.POST['machineid']), - test_id = int(request.POST['testid'])) + machine_id = int(request.POST['machine_id']), + test_id = int(request.POST['test_id'])) - return HttpResponse('None') + return JsonResponse({}) @csrf_exempt -@not_minified_response -def clientSubmitNPS(request): +def client_submit_nps(request): - # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # - # # - # POST : Report the speed of the engines in the currently running Test # - # for the User and his Machine. We save this value to display # - # # - # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # + # Pass along any error messages if they appear + machine, response = client_verify_worker(request) + if response != None: return response - # Authenticate the User/Machine combination - try: user, machine = authenticate_client(request) - except Exception as error: return HttpResponse(str(error)) - - # Update the NPS and return 'None' to signal no errors + # Update the NPS counter for the GUI views machine.mnps = float(request.POST['nps']) / 1e6; machine.save() - return HttpResponse('None') + + # Pass back an empty JSON response + return JsonResponse({}) @csrf_exempt -@not_minified_response -def clientSubmitError(request): +def client_submit_error(request): - # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # - # # - # POST : Report en Engine error to the server. This could be a crash, a # - # timeloss, a disconnect, or an illegal move. Log the Error into # - # the Events table. # - # # - # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # + ## Report an error when working on test. This could be one three kinds. + ## 1. Error building the engine. Does not compile, for whatever reason. + ## 2. Error getting the artifacts. Does not exist, lacks credentials. + ## 3. Error during actual gameplay. Timeloss, Disconnect, Crash, etc. - # Authenticate the User/Machine combination - try: user, machine = authenticate_client(request) - except Exception as error: return HttpResponse(str(error)) + # Pass along any error messages if they appear + machine, response = client_verify_worker(request) + if response != None: return response # Flag the Test as having an error except for time losses - test = Test.objects.get(id=int(request.POST['testid'])) + test = Test.objects.get(id=int(request.POST['test_id'])) if 'loses on time' not in request.POST['error']: test.error = True; test.save() # Log the Error into the Events table event = LogEvent.objects.create( - author = user.username, + author = machine.user.username, summary = request.POST['error'], log_file = '', - machine_id = int(request.POST['machineid']), - test_id = int(request.POST['testid'])) + machine_id = int(request.POST['machine_id']), + test_id = int(request.POST['test_id'])) # Save the Logs to /Media/ to be viewed later logfile = ContentFile(request.POST['logs']) FileSystemStorage().save('event%d.log' % (event.id), logfile) event.log_file = 'event%d.log' % (event.id); event.save() - return HttpResponse('None') + return JsonResponse({}) @csrf_exempt -@not_minified_response -def clientSubmitResults(request): +def client_submit_results(request): - # Authenticate the User/Machine combination - try: user, machine = authenticate_client(request) - except Exception as error: return HttpResponse(str(error)) + # Pass along any error messages if they appear + machine, response = client_verify_worker(request) + if response != None: return response - # updateTest() will return 'None' or 'Stop' - return HttpResponse(OpenBench.utils.updateTest(request, user)) + # Returns {}, or { 'stop' : True } + return JsonResponse(OpenBench.utils.update_test(request, machine)) # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # BUSINESS VIEWS # diff --git a/Templates/OpenBench/machines.html b/Templates/OpenBench/machines.html index 3d8573f..71ef33f 100644 --- a/Templates/OpenBench/machines.html +++ b/Templates/OpenBench/machines.html @@ -28,8 +28,6 @@ {% endfor %} - - {% endblock %} diff --git a/Templates/OpenBench/test.html b/Templates/OpenBench/test.html index bb376d7..8f30995 100644 --- a/Templates/OpenBench/test.html +++ b/Templates/OpenBench/test.html @@ -155,7 +155,6 @@ # User - OS Updated Games Won @@ -169,7 +168,6 @@ {{result.machine.id}} {{result.machine.user.username|capfirst|slice:"6"}} - {{result.machine.osname|truncatewords:1|slice:":-2"}} {{result.updated|date:'U'}} {{result.games}} {{result.wins}}