diff --git a/.gitignore b/.gitignore index 75fb2a5..09f477f 100644 --- a/.gitignore +++ b/.gitignore @@ -1,9 +1,13 @@ *.pyc Client/* -!Client/cleanup.sh OpenBench/migrations/* + credentials +credentials.* +db.sqlite3 Scripts/Binaries/* Scripts/Networks/* -Scripts/Repositories/* \ No newline at end of file +Scripts/Repositories/* + +Media/* \ No newline at end of file diff --git a/Books/books.json b/Books/books.json new file mode 100644 index 0000000..2aa0b49 --- /dev/null +++ b/Books/books.json @@ -0,0 +1,43 @@ +{ + "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" + } +} \ No newline at end of file diff --git a/Client/Client.py b/Client/Client.py index df666fa..5cf3517 100644 --- a/Client/Client.py +++ b/Client/Client.py @@ -19,17 +19,21 @@ # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # import argparse +import cpuinfo import hashlib +import json +import multiprocessing import os import platform +import psutil import re import requests +import shutil import sys import time import traceback +import uuid import zipfile -import shutil -import multiprocessing from subprocess import PIPE, Popen, call, STDOUT from itertools import combinations_with_replacement @@ -45,31 +49,18 @@ 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 = '4' # Client version to send to the Server +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 = '9' # Client version to send to the Server -SYZYGY_WDL_PATH = None # Pathway to WDL Syzygy Tables -BASE_GAMES_PER_CORE = 32 # Typical games played per-thread -FLEET_MODE = False # Exit when there are no workloads - -CUSTOM_SETTINGS = { - 'Ethereal' : [], 'Laser' : [], - 'Weiss' : [], 'Demolito' : [], - 'Rubichess' : [], 'FabChess' : [], - 'Igel' : [], 'Winter' : [], - 'Halogen' : [], 'Stash' : [], - 'Seer' : [], 'Koivisto' : [], - 'Drofa' : [], 'Bit-Genie' : [], - 'Berserk' : [], 'Zahak' : [], - 'BlackMarlin' : [], -}; +SYZYGY_WDL_PATH = None # Pathway to WDL Syzygy Tables +FLEET_MODE = False # Exit when there are no workloads ERRORS = { - 'cutechess' : 'Unable to fetch Cutechess location and download it!', - 'configure' : 'Unable to fetch and determine acceptable workloads!', - 'request' : 'Unable to reach server for workload request!', + 'cutechess' : 'Unable to fetch Cutechess location and download it!', + 'configure' : 'Unable to fetch and determine acceptable workloads!', + 'request' : 'Unable to reach server for workload request!', } # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # @@ -85,36 +76,145 @@ ERRORS = { 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 +SYSTEM_COMPILERS = {} +SYSTEM_GIT_TOKENS = {} +SYSTEM_CPU_FLAGS = [] +SYSTEM_CPU_NAME = '' +SYSTEM_OS_NAME = platform.system() +SYSTEM_OS_VER = platform.release() +SYSTEM_PYTHON_VER = platform.python_version() +SYSTEM_MAC_ADDRESS = hex(uuid.getnode()).upper()[2:] +SYSTEM_LOGICAL_CORES = psutil.cpu_count(logical=True) +SYSTEM_PHYSICAL_CORES = psutil.cpu_count(logical=False) +SYSTEM_RAM_TOTAL_MB = psutil.virtual_memory().total // (1024 ** 2) +SYSTEM_MACHINE_ID = 'None' +SYSTEM_SECRET_TOKEN = 'None' + +def get_version(program): + + # Try to execute the program from the command line + # First with `--version`, and again with just `version` + + try: + process = Popen([program, '--version'], stdout=PIPE, stderr=PIPE) + 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') + return re.search(r'\d+\.\d+(\.\d+)?', stdout).group() def locate_utility(util, force_exit=True, report_error=True): 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, ver.group())) - return True + return get_version(util) except Exception: + if report_error: print('[Error] Unable to locate %s' % (util)) + if force_exit: sys.exit() - return False -def check_for_utilities(): + return False - print('\nScanning For Basic Utilities...') - for utility in ['gcc', 'make']: - locate_utility(utility) + +def scan_for_compilers(data): + + print ('\nScanning for Compilers...') + + # For each engine, attempt to find a valid compiler + for engine, build_info in data.items(): + + # Private engines don't need to be compiled + if 'artifacts' in build_info: continue + + # Try to find at least one working compiler + 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 confirm this compiler is present, and new enough + try: + match = get_version(compiler) + if tuple(map(int, match.split('.'))) >= version: + print('%-16s | %-8s (%s)' % (engine, compiler, match)) + SYSTEM_COMPILERS[engine] = (compiler, match) + break + except: continue # Unable to execute compiler + + # Report missing engines in case the User is not expecting it + if engine not in SYSTEM_COMPILERS: + print('%-16s | Missing %s' % (engine, data[engine]['compilers'])) + +def scan_for_private_tokens(data): + + print ('\nScanning for Private Tokens...') + + # For each engine, attempt to find a valid compiler + for engine, build_info in data.items(): + + # Public engines don't need access tokens + 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())) + print('%-16s | %s' % (engine, ['Missing', 'Found'][has_token])) + if has_token: SYSTEM_GIT_TOKENS[engine] = True + +def scan_for_cpu_flags(data): + + print('\nScanning for CPU Flags...') + + # Get all flags, and for sanity uppercase them + info = cpuinfo.get_cpu_info() + actual = [x.upper() for x in info['flags']] + + # Set the CPU name which has to be done via global + global SYSTEM_CPU_NAME, SYSTEM_CPU_FLAGS + SYSTEM_CPU_NAME = info['brand_raw'] + + # This should cover virtually all compiler flags that we would care about + desired = ['POPCNT', 'BMI2'] + desired += ['SSSE3', 'SSE4_1', 'SSE4_2', 'SSE4A', 'AVX', 'AVX2', 'FMA'] + desired += ['AVX512_VNNI', 'AVX512BW', 'AVX512CD', 'AVX512DQ', 'AVX512F'] + + # Add any custom flags from the OpenBench configs, just in case we missed one + requested = set(sum([info['cpuflags'] for engine, info in data.items()], [])) + for flag in [x for x in requested if x not in desired]: desired.append(flag) + SYSTEM_CPU_FLAGS = [x for x in desired if x in actual] + + # Report the results of our search, including any "missing flags + print ('Found |', ' '.join(SYSTEM_CPU_FLAGS)) + print ('Missing |', ' '.join([x for x in desired if x not in actual])) + +def scan_for_machine_id(): + + # If we don't have one, the server will give us one, and then include it + # in future HTTP responses. We simply need to save the a .txt file, later + + global SYSTEM_MACHINE_ID + + if os.path.isfile('machine.txt'): + with open('machine.txt') as fin: + SYSTEM_MACHINE_ID = fin.readlines()[0] + + if SYSTEM_MACHINE_ID == 'None': + print('[NOTE] This machine is currently unregistered') def init_client(arguments): + # Verify that we have make installed + print('\nScanning For Basic Utilities...') + locate_utility('make') + # Use Client.py's path as the base pathway os.chdir(os.path.dirname(os.path.abspath(__file__))) @@ -129,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) @@ -138,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'): @@ -154,17 +255,14 @@ def validate_syzygy_exists(): 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') # Reset the configuration if the file is missing - if SYZYGY_WDL_PATH and not os.path.isfile(wdlpath): SYZYGY_WDL_PATH = None # Report final results, which may conflict with the original configuration - if SYZYGY_WDL_PATH: print('Verified Syzygy WDL (%s)' % (SYZYGY_WDL_PATH)) else: print('Syzygy WDL Not Found') @@ -203,13 +301,13 @@ 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 -def download_file(source, outname, post_data=None): +def download_file(source, outname, post_data=None, headers=None): - arguments = { 'stream' : True, 'timeout' : TIMEOUT_ERROR } + arguments = { 'stream' : True, 'timeout' : TIMEOUT_ERROR, 'headers' : headers } function = [requests.get, requests.post][post_data != None] if post_data: arguments['data'] = post_data @@ -227,11 +325,8 @@ def unzip_delete_file(source, outdir): def make_command(arguments, engine, src_path, network_path): - command = 'make %s=%s EXE=%s -j%s' % ( - ['CC', 'CXX']['++' in COMPILERS[engine]], COMPILERS[engine], engine, arguments.threads) - - if engine in CUSTOM_SETTINGS: - command += ' '.join(CUSTOM_SETTINGS[engine]) + command = 'make %s=%s EXE=%s -j%d' % ( + ['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) @@ -244,36 +339,48 @@ def parse_bench_output(stream): nps = bench = None # Search through output Stream for line in stream.decode('ascii').strip().split('\n')[::-1]: - # Try to match a wide array of patterns + # Convert non alpha-numerics to spaces line = re.sub(r'[^a-zA-Z0-9 ]+', ' ', line) - nps_pattern = r'([0-9]+ NPS)|(NPS[ ]+[0-9]+)' - bench_pattern = r'([0-9]+ NODES)|(NODES[ ]+[0-9]+)' - re_nps = re.search(nps_pattern, line.upper()) - re_bench = re.search(bench_pattern, line.upper()) - # Replace only if not already found earlier - if not nps and re_nps: nps = re_nps.group() - if not bench and re_bench: bench = re_bench.group() + # Multiple methods, including Ethereal and Stockfish + nps_pattern = r'(\d+\s+nps)|(nps\s+\d+)|(nodes second\s+\d+)' + bench_pattern = r'(\d+\s+nodes)|(nodes\s+\d+)|(nodes searched\s+\d+)' + + # Search for and set only once the NPS value + if (re_nps := re.search(nps_pattern, line, re.IGNORECASE)): + nps = nps if nps else re_nps.group() + + # Search for and set only once the Bench value + if (re_bench := re.search(bench_pattern, line, re.IGNORECASE)): + bench = bench if bench else re_bench.group() # Parse out the integer portion from our matches - nps = int(re.search(r'[0-9]+', nps).group()) if nps else None - bench = int(re.search(r'[0-9]+', bench).group()) if bench else None - return (nps, bench) + nps = int(re.search(r'\d+', nps ).group()) if nps else None + bench = int(re.search(r'\d+', bench).group()) if bench else None -def run_bench(engine, outqueue): + return (bench, nps) + +def run_bench(engine, outqueue, private_net=None): try: + # We may need to set an EvalFile via the UCI Options + if not private_net: cmd = ['./' + engine, 'bench'] + else: cmd = ['./' + engine, 'setoption name EvalFile value %s' % (private_net), 'bench', 'quit'] + # Launch the engine and parse output for statistics - process = Popen(['./' + engine, 'bench'], stdout=PIPE, stderr=PIPE) - stdout, stderr = process.communicate() + stdout, stderr = Popen(cmd, stdout=PIPE, stderr=STDOUT).communicate() outqueue.put(parse_bench_output(stdout)) except Exception: outqueue.put((0, 0)) -def scale_time_control(workload, nps): +def scale_time_control(workload, nps, branch): + + # Extract everything from the workload dictionary + reference_nps = workload['test'][branch]['nps'] + time_control = workload['test'][branch]['time_control'] # Searching for Nodes or Depth time controls ("N=", "D=") pattern = '(?P((N))|(D))=(?P(\d+))' - results = re.search(pattern, workload['test']['timecontrol'].upper()) + results = re.search(pattern, time_control.upper()) # No scaling is needed for fixed nodes or fixed depth games if results: @@ -282,16 +389,16 @@ def scale_time_control(workload, nps): # Searching for MoveTime or Fixed Time Controls ("MT=") pattern = '(?P(MT))=(?P(\d+))' - results = re.search(pattern, workload['test']['timecontrol'].upper()) + results = re.search(pattern, time_control.upper()) # Scale the time based on this machine's NPS. Add a time Margin to avoid time losses. if results: mode, value = results.group('mode', 'value') - return 'st=%.2f timemargin=100' % (float(value) * int(workload['test']['nps']) / (1000 * nps)) + return 'st=%.2f timemargin=100' % ((float(value) * reference_nps) / (1000 * nps)) # Searching for "X/Y+Z" time controls pattern = '(?P(\d+/)?)(?P\d*(\.\d+)?)(?P\+(\d+\.)?\d+)?' - results = re.search(pattern, workload['test']['timecontrol']) + results = re.search(pattern, time_control) moves, base, inc = results.group('moves', 'base', 'inc') # Strip the trailing and leading symbols @@ -299,8 +406,8 @@ def scale_time_control(workload, nps): inc = 0.0 if inc is None else inc.lstrip('+') # Scale the time based on this machine's NPS - base = float(base) * int(workload['test']['nps']) / nps - inc = float(inc ) * int(workload['test']['nps']) / nps + base = float(base) * reference_nps / nps + inc = float(inc ) * reference_nps / nps # Format the time control for cutechess if moves is None: return 'tc=%.2f+%.2f' % (base, inc) @@ -358,7 +465,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 @@ -374,7 +481,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 @@ -389,134 +496,129 @@ def server_download_cutechess(arguments): @try_until_success(mesg=ERRORS['configure']) def server_configure_worker(arguments): - print ('\nScanning for Compilers...') + global SYSTEM_MACHINE_ID, SYSTEM_SECRET_TOKEN - # Fetch { Engine -> Compilers } from the server + # Server tells us how to build or obtain binaries target = url_join(arguments.server, 'clientGetBuildInfo') data = requests.get(target, timeout=TIMEOUT_HTTP).json() - def get_version(compiler): + scan_for_compilers(data) # Public engines + scan_for_private_tokens(data) # Private engines + scan_for_cpu_flags(data) # For executing binaries + scan_for_machine_id() # None, or the content of machine.txt - # Try to execute the compiler from the command line - # First with `--version`, and again with just `version` + system_info = { + 'compilers' : SYSTEM_COMPILERS, # Key: Engine, Value: (Compiler, Version) + 'tokens' : SYSTEM_GIT_TOKENS, # Key: Engine, Value: True, for tokens we have + 'cpu_flags' : SYSTEM_CPU_FLAGS, # List of CPU flags found in the Client or Server + 'cpu_name' : SYSTEM_CPU_NAME, # Raw CPU name as per py-cpuinfo + 'os_name' : SYSTEM_OS_NAME, # Should be Windows, Linux, or Darwin + 'os_ver' : SYSTEM_OS_VER, # Release version of the OS + 'python_ver' : SYSTEM_PYTHON_VER, # Python version running the Client + 'mac_address' : SYSTEM_MAC_ADDRESS, # Used to softly verify the Machine IDs + 'logical_cores' : SYSTEM_LOGICAL_CORES, # Logical cores, to differentiate hyperthreads + 'physical_cores' : SYSTEM_PHYSICAL_CORES, # Physical cores, to differentiate hyperthreads + 'ram_total_mb' : SYSTEM_RAM_TOTAL_MB, # Total RAM on the system, to avoid over assigning + 'machine_id' : SYSTEM_MACHINE_ID, # Assigned value, or None. Will be replaced if wrong + 'concurrency' : arguments.threads, # Threads to use to play games + 'ncutechesses' : arguments.ncutechess, # Cutechess copies, usually equal to Socket count + 'client_ver' : CLIENT_VERSION, # Version of the Client, which the server may reject + 'syzygy_wdl' : bool(SYZYGY_WDL_PATH), # Whether or not the machine has Syzygy support + } - try: - process = Popen([compiler, '--version'], stdout=PIPE, stderr=PIPE) - stdout = process.communicate()[0].decode('utf-8') - return re.search(r'[0-9]+\.[0-9]+\.[0-9]+', stdout).group() + payload = { + 'username' : arguments.username, + 'password' : arguments.password, + 'system_info' : json.dumps(system_info), + } - except: - process = Popen([compiler, 'version'], stdout=PIPE, stderr=PIPE) - stdout = process.communicate()[0].decode('utf-8') - return re.search(r'[0-9]+\.[0-9]+\.[0-9]+', stdout).group() + # Send all of this to the server, and get a Machine Id + Secret Token + target = url_join(arguments.server, 'clientWorkerInfo') + response = requests.post(target, data=payload, timeout=TIMEOUT_HTTP).json() - # For each engine, attempt to find a valid compiler - for engine, build_info in data.items(): - for compiler in build_info['compilers']: + # Delete the machine.txt if we have saved an invalid machine number + if 'error' in response and response['error'].lower() == "bad machine id": + os.remove('machine.txt') - # Compilers may require a specific version - if '>=' in compiler: - compiler, version = compiler.split('>=') - version = tuple(map(int, version.split('.'))) - else: version = (0, 0, 0) + # The 'error' header is included if there was an issue + if 'error' in response: + print('[Error] %s\n' % (response['error'])) + sys.exit() - try: match = get_version(compiler) - except: continue # Unable to execute compiler + # Save the machine id, to avoid re-registering every time + with open('machine.txt', 'w') as fout: + fout.write(str(response['machine_id'])) - # Compiler version was sufficient - if tuple(map(int, match.split('.'))) >= version: - print('%14s | %s (%s)' % (engine, compiler, match)) - COMPILERS[engine] = compiler - break + # Save it within the code as well for future requests + SYSTEM_MACHINE_ID = str(response['machine_id']) - # 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('%14s | 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 -', - 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)) + # Save the secret token, to send with all future requests + SYSTEM_SECRET_TOKEN = response['secret'] @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] + 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() - if machine_id == 'None': - print('[NOTE] This machine is currently unregistered') + # The 'error' header is included if there was an issue + if 'error' in response: + print('[Error] %s\n' % (response['error'])) + sys.exit() - supported = ' '.join(COMPILERS.keys() - ['cpuflags']) + # Log the start of a new Workload + if 'workload' in response: + dev_engine = response['workload']['test']['dev' ]['engine'] + dev_name = response['workload']['test']['dev' ]['name' ] + base_engine = response['workload']['test']['base']['engine'] + base_name = response['workload']['test']['base']['name' ] + print('Workload [%s] %s vs [%s] %s\n' % (dev_engine, dev_name, base_engine, base_name)) + + 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, 'osname' : OSNAME, - 'machineid' : machine_id, 'syzygy_wdl' : bool(SYZYGY_WDL_PATH), - 'supported' : supported, 'cpuflags' : COMPILERS['cpuflags'], - 'version' : CLIENT_VERSION + '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_build_fail(arguments, workload, branch, compiler_output): +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' : '%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' : 'Artifact %s missing' % (artifact_name), + 'logs' : json.dumps(artifact_json, indent=2), } target = url_join(arguments.server, 'clientSubmitError') requests.post(target, data=payload, timeout=TIMEOUT_HTTP) -def server_report_bad_bench(arguments, workload, branch, bench): +def server_report_build_fail(arguments, workload, branch, compiler_output): - branch = workload['test'][branch] + name = workload['test'][branch]['name'] + if workload['test']['dev']['engine'] != workload['test']['base']['engine']: + name = '[%s] %s' % (workload['test'][branch]['engine'], name) - data = { - 'username' : arguments.username, 'testid' : workload['test']['id'], - 'password' : arguments.password, 'machineid' : workload['machine']['id'], - 'correct' : branch['bench'], 'engine' : branch['name'], - 'wrong' : bench, + payload = { + 'machine_id' : SYSTEM_MACHINE_ID, + 'secret' : SYSTEM_SECRET_TOKEN, + 'test_id' : workload['test']['id'], + 'error' : '%s build failed' % (name), + 'logs' : compiler_output, } - 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) + target = url_join(arguments.server, 'clientSubmitError') + requests.post(target, data=payload, timeout=TIMEOUT_HTTP) def server_report_engine_error(arguments, workload, cutechess_str, pgn): @@ -528,32 +630,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() # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # @@ -561,69 +679,49 @@ 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') + dev_network = download_network_weights(arguments, workload, 'dev' ) base_network = download_network_weights(arguments, workload, 'base') - dev_name = download_engine(arguments, workload, 'dev', dev_network) + dev_name = download_engine(arguments, workload, 'dev' , dev_network ) base_name = download_engine(arguments, workload, 'base', base_network) if dev_name == None or base_name == None: return - dev_bench, dev_nps = run_benchmarks(arguments, workload, 'dev', dev_name) - base_bench, base_nps = run_benchmarks(arguments, workload, 'base', base_name) + dev_bench, dev_nps = run_benchmarks(arguments, workload, 'dev' , dev_name , dev_network ) + base_bench, base_nps = run_benchmarks(arguments, workload, 'base', base_name, base_network) + average_nps = (dev_nps + base_nps) // 2 - dev_status = verify_benchmarks(arguments, workload, 'dev', dev_bench) + dev_status = verify_benchmarks(arguments, workload, 'dev' , dev_bench ) base_status = verify_benchmarks(arguments, workload, 'base', base_bench) if not dev_status or not base_status: return server_report_nps(arguments, workload, dev_nps, base_nps) download_opening_book(arguments, workload) - avg_nps = (dev_nps + base_nps) // 2 - concurrency, update_interval, command = build_cutechess_command( - arguments, workload, dev_name, base_name, avg_nps) + # Construct each individual Cutechess argument, which differs by PGN output + cutechess_args = [ + build_cutechess_command(arguments, workload, dev_name, base_name, average_nps, ii) + for ii in range(int(arguments.ncutechess)) + ] - run_and_parse_cutechess(arguments, workload, concurrency, update_interval, command) + # Create a process for the each copy of run_and_parse_cutechess() + processes = [ + multiprocessing.Process( + target=run_and_parse_cutechess, + args=(arguments, workload, *cutechess_args[ii], ii)) + for ii in range(int(arguments.ncutechess)) + ] + + try: + # Launch and wait for each cutechess copy + for process in processes: process.start() + for process in processes: process.join() + + except KeyboardInterrupt: + # Kill everything and pass the error back up + for process in processes: process.kill() + raise KeyboardInterrupt def download_opening_book(arguments, workload): @@ -690,42 +788,83 @@ def download_network_weights(arguments, workload, branch): def download_engine(arguments, workload, branch, network): - engine = workload['test']['engine'] + engine = workload['test'][branch]['engine'] branch_name = workload['test'][branch]['name'] commit_sha = workload['test'][branch]['sha'] source = workload['test'][branch]['source'] - build_path = workload['test']['build']['path'] + build_path = workload['test'][branch]['build']['path'] + private = 'artifacts' in workload['test'][branch]['build'] - if arguments.proxy: source = 'https://ghproxy.com/' + source - - pattern = '\nEngine: [%s] %s\nCommit: %s' - print(pattern % (engine, branch_name, commit_sha.upper())) - - # Naming as Engine-SHA256[:8]-NETSHA256[:8] + # Naming as Engine-CommitSha[:8]-NetworkSha[:8] final_name = '%s-%s' % (engine, commit_sha.upper()[:8]) - if network: final_name += '-%s' % (network[-8:]) + if network and not private: 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_name if os.path.isfile(final_path + '.exe'): return final_name + '.exe' - # Download and unzip the source from Github - download_file(source, '%s.zip' % (engine)) - unzip_delete_file('%s.zip' % (engine), 'tmp/') + if private: - # 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('/')) + # Get the candidate artifacts that we can pick from + print ('\nFetching Artifacts for %s' % branch_name) + with open('credentials.%s' % (engine.replace(' ', '').lower())) as fin: + auth_headers = { 'Authorization' : 'token %s' % fin.readlines()[0].rstrip() } + artifacts = requests.get(url=source, headers=auth_headers).json()['artifacts'] - # Build the engine and drop it into src_path - print('\nBuilding [%s]' % (final_path)) - output_name = os.path.join(src_path, engine) - command = make_command(arguments, engine, src_path, network) - process = Popen(command, cwd=src_path, stdout=PIPE, stderr=STDOUT) - compiler_output = process.communicate()[0].decode('utf-8') - print (compiler_output) + # 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 + os_string = ['windows', 'linux' ][IS_LINUX] + 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 + artifact_id = None + for artifact in artifacts: + if artifact['name'] == '%s-%s' % (commit_sha, desired): + artifact_id = artifact['id'] + + # Artifact was missing, workload cannot be completed + if artifact_id == None: + server_report_missing_artifact(arguments, workload, branch, desired, artifacts) + return None + + # Download the binary that matches our desired artifact + print ('Downloading [%s] %s' % (branch_name, desired)) + base = source.split('/runs/')[0] + url = url_join(base, 'artifacts', str(artifact_id), 'zip').rstrip('/') + download_file(url, 'artifact.zip', None, auth_headers) + + # Unzip the binary, and determine where to move the binary + unzip_delete_file('artifact.zip', 'tmp/') + output_name = os.path.join('tmp', engine.replace(' ', '').lower()) + + # Binaries don't have execute permissions by default + if IS_LINUX: + os.system('chmod 777 %s\n' % (output_name)) + + if not private: + + # 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)) + output_name = os.path.join(src_path, engine) + command = make_command(arguments, engine, src_path, network) + process = Popen(command, cwd=src_path, stdout=PIPE, stderr=STDOUT) + cxx_output = process.communicate()[0].decode('utf-8') + print (cxx_output) # Move the file to the final location ( Linux ) if os.path.isfile(output_name): @@ -739,23 +878,25 @@ def download_engine(arguments, workload, branch, network): shutil.rmtree('tmp') return final_name + '.exe' - # Notify the server if the build failed - server_report_build_fail(arguments, workload, branch, compiler_output) - return None + # Manual builds should have exited by now + if not private: + server_report_build_fail(arguments, workload, branch, cxx_output) + return None -def run_benchmarks(arguments, workload, branch, engine): +def run_benchmarks(arguments, workload, branch, engine, network): - cores = int(arguments.threads) - queue = multiprocessing.Queue() - name = workload['test'][branch]['name'] + cores = arguments.threads + queue = multiprocessing.Queue() + name = workload['test'][branch]['name'] + private = 'artifacts' in workload['test'][branch]['build'] print('\nRunning %dx Benchmarks for %s' % (cores, name)) for ii in range(cores): - args = (os.path.join('Engines', engine), queue,) - proc = multiprocessing.Process(target=run_bench, args=args) - proc.start() + args = [os.path.join('Engines', engine), queue] + if private and network: args.append(network) + multiprocessing.Process(target=run_bench, args=args).start() - nps, bench = list(zip(*[queue.get() for ii in range(cores)])) + bench, nps = list(zip(*[queue.get() for ii in range(cores)])) if len(set(bench)) > 1: return (0, 0) # Flag an error print('Bench for %s is %d' % (name, bench[0])) @@ -767,7 +908,7 @@ def verify_benchmarks(arguments, workload, branch, bench): server_report_bad_bench(arguments, workload, branch, bench) return bench == int(workload['test'][branch]['bench']) -def build_cutechess_command(arguments, workload, dev_name, base_name, nps): +def build_cutechess_command(arguments, workload, dev_cmd, base_cmd, nps, cutechess_idx): dev_options = workload['test']['dev' ]['options'] base_options = workload['test']['base']['options'] @@ -775,51 +916,73 @@ def build_cutechess_command(arguments, workload, dev_name, base_name, nps): dev_threads = int(re.search('(?<=Threads=)\d*', dev_options ).group()) base_threads = int(re.search('(?<=Threads=)\d*', base_options).group()) + dev_network = workload['test']['dev' ]['network'] # Could be empty strings + base_network = workload['test']['base']['network'] # Could be empty strings + + dev_time = scale_time_control(workload, nps, 'dev') + base_time = scale_time_control(workload, nps, 'base') + + dev_name = dev_cmd.rstrip('.exe') # Used to name the PGN file and Headers + base_name = base_cmd.rstrip('.exe') # Used to name the PGN file and Headers + + # Possibly add SyzygyPath to dev and base options if SYZYGY_WDL_PATH and workload['test']['syzygy_wdl'] != 'DISABLED': path = SYZYGY_WDL_PATH.replace('\\', '\\\\') dev_options += ' SyzygyPath=%s' % (path) base_options += ' SyzygyPath=%s' % (path) + # Private engines may need extra options to set their NNUE files + if 'artifacts' in workload['test']['dev']['build'] and dev_network and dev_network != 'None': + dev_options += ' EvalFile=%s' % (os.path.join('../Networks', dev_network)) + dev_name += '-%s' % (dev_network) + + # Private engines may need extra options to set their NNUE files + if 'artifacts' in workload['test']['base']['build'] and base_network and base_network != 'None': + base_options += ' EvalFile=%s' % (os.path.join('../Networks', base_network)) + base_name += '-%s' % (base_network) + + # Join all of the options into a single string dev_options = ' option.'.join([''] + dev_options.split()) base_options = ' option.'.join([''] + base_options.split()) + win_adj = ['', '-resign ' + workload['test']['win_adj' ]][workload['test']['win_adj' ] != 'None'] + draw_adj = ['', '-draw ' + workload['test']['draw_adj']][workload['test']['draw_adj'] != 'None'] + book_name = workload['test']['book']['name'] variant = ['standard', 'fischerandom']['FRC' in book_name.upper()] - flags = '-repeat -recover -resign %s -draw %s ' + flags = '-repeat -recover %s %s ' flags += '-srand %d -variant %s -concurrency %d -games %d ' flags += '-engine dir=Engines/ cmd=./%s proto=uci %s%s name=%s ' flags += '-engine dir=Engines/ cmd=./%s proto=uci %s%s name=%s ' flags += '-openings file=Books/%s format=%s order=random plies=16 ' - flags += '-pgnout PGNs/%s_vs_%s ' + flags += '-pgnout PGNs/%s_vs_%s.%d ' if SYZYGY_WDL_PATH and workload['test']['syzygy_adj'] != 'DISABLED': flags += '-tb %s' % (SYZYGY_WDL_PATH.replace('\\', '\\\\')) - concurrency = int(arguments.threads) // max(dev_threads, base_threads) - update_interval = 8 if max(dev_threads, base_threads) == 1 else 1 + concurrency = arguments.threads / arguments.ncutechess + concurrency = concurrency // max(dev_threads, base_threads) - games = int(concurrency * BASE_GAMES_PER_CORE) + games = int(concurrency * workload['test']['workload_size']) games = max(8, concurrency * 2, games - (games % (2 * concurrency))) - time_control = scale_time_control(workload, nps) - args = ( - 'movecount=3 score=400', 'movenumber=40 movecount=8 score=10', - int(time.time()), variant, concurrency, games, - dev_name, time_control, dev_options, dev_name.rstrip('.exe'), - base_name, time_control, base_options, base_name.rstrip('.exe'), + win_adj, draw_adj, + int(time.time() + cutechess_idx), variant, concurrency, games, + dev_cmd, dev_time, dev_options, dev_name, + base_cmd, base_time, base_options, base_name, book_name, book_name.split('.')[-1], - dev_name.rstrip('.exe'), base_name.rstrip('.exe') + dev_name, base_name, cutechess_idx, ) if IS_LINUX: - return concurrency, update_interval, './cutechess-ob ' + flags % (args) - return concurrency, update_interval, 'cutechess-ob.exe ' + flags % (args) + return concurrency, './cutechess-ob ' + flags % (args) + return concurrency, 'cutechess-ob.exe ' + flags % (args) -def run_and_parse_cutechess(arguments, workload, concurrency, update_interval, command): +def run_and_parse_cutechess(arguments, workload, concurrency, command, cutechess_idx): - print('\nLaunching Cutechess...\n%s\n' % (command)) + print('\n[#%d] Launching Cutechess...\n%s\n' % (cutechess_idx, command)) cutechess = Popen(command.split(), stdout=PIPE) crashes = timelosses = 0 @@ -830,7 +993,7 @@ def run_and_parse_cutechess(arguments, workload, concurrency, update_interval, c # Read each line of output until the pipe closes line = cutechess.stdout.readline().strip().decode('ascii') - if line != '': print(line) + if line != '': print('[#%d] %s' % (cutechess_idx, line)) else: cutechess.wait(); return # Real updates contain a colon @@ -854,23 +1017,28 @@ def run_and_parse_cutechess(arguments, workload, concurrency, update_interval, c # Only report scores after every eight games score = list(map(int, score_reason.split()[0:5:2])) - if ((sum(score) - sum(sent)) % update_interval != 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 - if status.upper() == 'STOP': + # Reset the reporting since this report was a success + crashes = timelosses = 0 + sent = score[::] + + except: + # Failed to connect, but we can delay the reports until later + print('[NOTE] Unable To Reach Server'); + + # Check for openbench.exit, or server instructing us to exit + if os.path.isfile('openbench.exit') or 'stop' in status: kill_cutechess(cutechess) return - # If the update was succesful reset the results - if status.upper() != 'UNABLE': - crashes = timelosses = 0 - sent = score[::] - # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # @@ -885,15 +1053,30 @@ if __name__ == '__main__': help_pass = 'Password. May also be passed as OPENBENCH_PASSWORD environment variable' 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='Webserver', required=True) - p.add_argument('-T', '--threads' , help='Threads' , required=True) + + # Required arguments + 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='Webserver Address' , required=True) + p.add_argument('-T', '--threads' , help='Total Threads' , required=True) + p.add_argument('-N', '--ncutechess' , help='Cutechess Copies' , required=True) + + # Optional arguments p.add_argument('--syzygy', help='Syzygy WDL' , required=False) p.add_argument('--fleet' , help='Fleet Mode' , action='store_true') p.add_argument('--proxy' , help='Github Proxy', action='store_true') + arguments = p.parse_args() + arguments.threads = int(arguments.threads) + arguments.ncutechess = int(arguments.ncutechess) + + # Make sure the thread distibution between Cutechess copies is correct + assert (arguments.threads >= 1) + assert (arguments.ncutechess >= 1) + assert (arguments.threads >= arguments.ncutechess) + assert (arguments.threads % arguments.ncutechess == 0) + if arguments.username is None: arguments.username = os.environ['OPENBENCH_USERNAME'] @@ -906,22 +1089,20 @@ if __name__ == '__main__': if arguments.fleet: FLEET_MODE = True - check_for_utilities() init_client(arguments) server_download_cutechess(arguments) server_configure_worker(arguments) 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/Client/cleanup.sh b/Client/cleanup.sh index 741ea66..ef9dedd 100755 --- a/Client/cleanup.sh +++ b/Client/cleanup.sh @@ -7,4 +7,5 @@ rm -rf Books/ rm -rf PGNs/ rm -rf tmp/ rm -rf *.dll -rm -rf cutechess* \ No newline at end of file +rm -rf cutechess* +rm -rf machine.txt \ No newline at end of file diff --git a/Documentation/openbench.yml b/Documentation/openbench.yml new file mode 100644 index 0000000..bb0b159 --- /dev/null +++ b/Documentation/openbench.yml @@ -0,0 +1,30 @@ +name: OpenBench Build +on: + push: + workflow_dispatch: + +jobs: + build_and_archive: + name: Build and Archive + strategy: + matrix: + os: [ubuntu-latest] + nnue_flags: [avx2, avx512] + cpu_flags: [popcnt, pext] + + runs-on: ${{ matrix.os }} + steps: + - name: Setup Linux GCC ${{ matrix.version }} + uses: egor-tensin/setup-gcc@v1 + with: + version: 11 + platform: x86 + - name: Clone Ethereal + uses: actions/checkout@v3 + - name: Build Ethereal ${{ matrix.flags }} + run: make EVALFILE=none CC=gcc static=1 ${{ matrix.nnue_flags }}=1 ${{ matrix.cpu_flags }}=1 + - name: Archive ${{ matrix.nnue_flags }}-${{ matrix.cpu_flags }} + uses: actions/upload-artifact@v3 + with: + name: ${{ github.sha }}-linux-${{ matrix.nnue_flags }}-${{ matrix.cpu_flags }} + path: ethereal \ No newline at end of file diff --git a/Engines/4ku.json b/Engines/4ku.json new file mode 100644 index 0000000..d94a45a --- /dev/null +++ b/Engines/4ku.json @@ -0,0 +1,48 @@ +{ + "private" : false, + "nps" : 1254000, + "base" : "master", + "source" : "https://github.com/kz04px/4ku", + + "bounds" : "[0.00, 5.00]", + "book" : "Pohl.pgn", + "win_adj" : "movecount=3 score=400", + "draw_adj" : "movenumber=40 movecount=8 score=10", + + "build" : { + "path" : "", + "compilers" : ["g++"], + "cpuflags" : ["POPCNT"] + }, + + "testmodes" : { + + "STC" : { + "options" : "Threads=1 Hash=8", + "timecontrol" : "8.0+0.08", + "report_rate" : 16, + "workload_size" : 32 + }, + + "LTC" : { + "options" : "Threads=1 Hash=64", + "timecontrol" : "40.0+0.4", + "report_rate" : 4, + "workload_size" : 8 + }, + + "SMP STC" : { + "options" : "Threads=8 Hash=64", + "timecontrol" : "5.0+0.05", + "report_rate" : 1, + "workload_size" : 64 + }, + + "SMP LTC" : { + "options" : "Threads=8 Hash=256", + "timecontrol" : "20.0+0.2", + "report_rate" : 1, + "workload_size" : 16 + } + } +} \ No newline at end of file diff --git a/Engines/Berserk.json b/Engines/Berserk.json new file mode 100644 index 0000000..6e45759 --- /dev/null +++ b/Engines/Berserk.json @@ -0,0 +1,48 @@ +{ + "private" : false, + "nps" : 1145000, + "base" : "main", + "source" : "https://github.com/jhonnold/berserk", + + "bounds" : "[0.00, 3.00]", + "book" : "Pohl.epd", + "win_adj" : "movecount=3 score=400", + "draw_adj" : "movenumber=40 movecount=8 score=10", + + "build" : { + "path" : "src", + "compilers" : ["gcc"], + "cpuflags" : ["AVX2", "FMA", "POPCNT"] + }, + + "testmodes" : { + + "STC" : { + "options" : "Threads=1 Hash=8", + "timecontrol" : "8.0+0.08", + "report_rate" : 16, + "workload_size" : 32 + }, + + "LTC" : { + "options" : "Threads=1 Hash=64", + "timecontrol" : "40.0+0.4", + "report_rate" : 4, + "workload_size" : 8 + }, + + "SMP STC" : { + "options" : "Threads=8 Hash=64", + "timecontrol" : "4.0+0.04", + "report_rate" : 1, + "workload_size" : 64 + }, + + "SMP LTC" : { + "options" : "Threads=8 Hash=256", + "timecontrol" : "16.0+0.16", + "report_rate" : 1, + "workload_size" : 16 + } + } +} \ No newline at end of file diff --git a/Engines/Bit-Genie.json b/Engines/Bit-Genie.json new file mode 100644 index 0000000..7240ba5 --- /dev/null +++ b/Engines/Bit-Genie.json @@ -0,0 +1,48 @@ +{ + "private" : false, + "nps" : 2096000, + "base" : "master", + "source" : "https://github.com/Aryan1508/Bit-Genie", + + "bounds" : "[0.00, 5.00]", + "book" : "Pohl.epd", + "win_adj" : "movecount=3 score=400", + "draw_adj" : "movenumber=40 movecount=8 score=10", + + "build" : { + "path" : "src", + "compilers" : ["g++"], + "cpuflags" : ["POPCNT"] + }, + + "testmodes" : { + + "STC" : { + "options" : "Threads=1 Hash=8", + "timecontrol" : "8.0+0.08", + "report_rate" : 16, + "workload_size" : 32 + }, + + "LTC" : { + "options" : "Threads=1 Hash=64", + "timecontrol" : "40.0+0.4", + "report_rate" : 4, + "workload_size" : 8 + }, + + "SMP STC" : { + "options" : "Threads=8 Hash=64", + "timecontrol" : "5.0+0.05", + "report_rate" : 1, + "workload_size" : 64 + }, + + "SMP LTC" : { + "options" : "Threads=8 Hash=256", + "timecontrol" : "20.0+0.2", + "report_rate" : 1, + "workload_size" : 16 + } + } +} \ No newline at end of file diff --git a/Engines/BlackMarlin.json b/Engines/BlackMarlin.json new file mode 100644 index 0000000..711df8d --- /dev/null +++ b/Engines/BlackMarlin.json @@ -0,0 +1,48 @@ +{ + "private" : false, + "nps" : 1106000, + "base" : "main", + "source" : "https://github.com/dsekercioglu/blackmarlin", + + "bounds" : "[0.00, 5.00]", + "book" : "Pohl.epd", + "win_adj" : "movecount=3 score=400", + "draw_adj" : "movenumber=40 movecount=8 score=10", + + "build" : { + "path" : "", + "compilers" : ["cargo>=1.57.0"], + "cpuflags" : [ "AVX2", "FMA", "POPCNT"] + }, + + "testmodes" : { + + "STC" : { + "options" : "Threads=1 Hash=8", + "timecontrol" : "8.0+0.08", + "report_rate" : 16, + "workload_size" : 32 + }, + + "LTC" : { + "options" : "Threads=1 Hash=64", + "timecontrol" : "40.0+0.4", + "report_rate" : 4, + "workload_size" : 8 + }, + + "SMP STC" : { + "options" : "Threads=8 Hash=64", + "timecontrol" : "5.0+0.05", + "report_rate" : 1, + "workload_size" : 64 + }, + + "SMP LTC" : { + "options" : "Threads=8 Hash=256", + "timecontrol" : "20.0+0.2", + "report_rate" : 1, + "workload_size" : 16 + } + } +} \ No newline at end of file diff --git a/Engines/Demolito.json b/Engines/Demolito.json new file mode 100644 index 0000000..7dcced5 --- /dev/null +++ b/Engines/Demolito.json @@ -0,0 +1,48 @@ +{ + "private" : false, + "nps" : 1395000, + "base" : "master", + "source" : "https://github.com/lucasart/Demolito", + + "bounds" : "[0.00, 5.00]", + "book" : "Pohl.epd", + "win_adj" : "movecount=3 score=400", + "draw_adj" : "movenumber=40 movecount=8 score=10", + + "build" : { + "path" : "src", + "compilers" : ["clang", "gcc"], + "cpuflags" : ["POPCNT"] + }, + + "testmodes" : { + + "STC" : { + "options" : "Threads=1 Hash=8", + "timecontrol" : "8.0+0.08", + "report_rate" : 16, + "workload_size" : 32 + }, + + "LTC" : { + "options" : "Threads=1 Hash=32", + "timecontrol" : "32.0+0.32", + "report_rate" : 4, + "workload_size" : 8 + }, + + "SMP STC" : { + "options" : "Threads=8 Hash=32", + "timecontrol" : "4.0+0.04", + "report_rate" : 1, + "workload_size" : 64 + }, + + "SMP LTC" : { + "options" : "Threads=8 Hash=128", + "timecontrol" : "16.0+0.16", + "report_rate" : 1, + "workload_size" : 16 + } + } +} \ No newline at end of file diff --git a/Engines/Drofa.json b/Engines/Drofa.json new file mode 100644 index 0000000..6e1d3bf --- /dev/null +++ b/Engines/Drofa.json @@ -0,0 +1,48 @@ +{ + "private" : false, + "nps" : 1163000, + "base" : "master", + "source" : "https://github.com/justNo4b/Drofa", + + "bounds" : "[0.00, 5.00]", + "book" : "4moves_noob.epd", + "win_adj" : "movecount=3 score=400", + "draw_adj" : "movenumber=40 movecount=8 score=10", + + "build" : { + "path" : "", + "compilers" : ["g++"], + "cpuflags" : ["POPCNT"] + }, + + "testmodes" : { + + "STC" : { + "options" : "Threads=1 Hash=8", + "timecontrol" : "8.0+0.08", + "report_rate" : 16, + "workload_size" : 32 + }, + + "LTC" : { + "options" : "Threads=1 Hash=64", + "timecontrol" : "40.0+0.4", + "report_rate" : 4, + "workload_size" : 8 + }, + + "SMP STC" : { + "options" : "Threads=8 Hash=64", + "timecontrol" : "5.0+0.05", + "report_rate" : 1, + "workload_size" : 64 + }, + + "SMP LTC" : { + "options" : "Threads=8 Hash=256", + "timecontrol" : "20.0+0.2", + "report_rate" : 1, + "workload_size" : 16 + } + } +} \ No newline at end of file diff --git a/Engines/Ethereal.json b/Engines/Ethereal.json new file mode 100644 index 0000000..0e6212c --- /dev/null +++ b/Engines/Ethereal.json @@ -0,0 +1,48 @@ +{ + "private" : false, + "nps" : 1128000, + "base" : "master", + "source" : "https://github.com/AndyGrant/Ethereal", + + "bounds" : "[0.00, 3.00]", + "book" : "Pohl.epd", + "win_adj" : "movecount=3 score=400", + "draw_adj" : "movenumber=40 movecount=8 score=10", + + "build" : { + "path" : "src", + "compilers" : ["clang", "gcc"], + "cpuflags" : ["AVX2", "FMA", "POPCNT"] + }, + + "testmodes" : { + + "STC" : { + "options" : "Threads=1 Hash=8", + "timecontrol" : "10.0+0.1", + "report_rate" : 16, + "workload_size" : 32 + }, + + "LTC" : { + "options" : "Threads=1 Hash=64", + "timecontrol" : "60.0+0.6", + "report_rate" : 4, + "workload_size" : 8 + }, + + "SMP STC" : { + "options" : "Threads=8 Hash=64", + "timecontrol" : "5.0+0.05", + "report_rate" : 1, + "workload_size" : 64 + }, + + "SMP LTC" : { + "options" : "Threads=8 Hash=256", + "timecontrol" : "20.0+0.2", + "report_rate" : 1, + "workload_size" : 16 + } + } +} \ No newline at end of file diff --git a/Engines/FabChess.json b/Engines/FabChess.json new file mode 100644 index 0000000..fcb17e1 --- /dev/null +++ b/Engines/FabChess.json @@ -0,0 +1,48 @@ +{ + "private" : false, + "nps" : 1012000, + "base" : "master", + "source" : "https://github.com/fabianvdW/FabChess", + + "bounds" : "[0.00, 5.00]", + "book" : "Pohl.epd", + "win_adj" : "movecount=3 score=400", + "draw_adj" : "movenumber=40 movecount=8 score=10", + + "build" : { + "path" : "", + "compilers" : ["cargo>=1.41.0"], + "cpuflags" : ["POPCNT"] + }, + + "testmodes" : { + + "STC" : { + "options" : "Threads=1 Hash=8", + "timecontrol" : "8.0+0.08", + "report_rate" : 16, + "workload_size" : 32 + }, + + "LTC" : { + "options" : "Threads=1 Hash=64", + "timecontrol" : "40.0+0.4", + "report_rate" : 4, + "workload_size" : 8 + }, + + "SMP STC" : { + "options" : "Threads=8 Hash=64", + "timecontrol" : "5.0+0.05", + "report_rate" : 1, + "workload_size" : 64 + }, + + "SMP LTC" : { + "options" : "Threads=8 Hash=256", + "timecontrol" : "20.0+0.2", + "report_rate" : 1, + "workload_size" : 16 + } + } +} \ No newline at end of file diff --git a/Engines/Halogen.json b/Engines/Halogen.json new file mode 100644 index 0000000..2213eb1 --- /dev/null +++ b/Engines/Halogen.json @@ -0,0 +1,48 @@ +{ + "private" : false, + "nps" : 1881000, + "base" : "master", + "source" : "https://github.com/KierenP/Halogen", + + "bounds" : "[0.00, 5.00]", + "book" : "Pohl.epd", + "win_adj" : "movecount=3 score=400", + "draw_adj" : "movenumber=40 movecount=8 score=10", + + "build" : { + "path" : "src", + "compilers" : ["g++"], + "cpuflags" : ["POPCNT"] + }, + + "testmodes" : { + + "STC" : { + "options" : "Threads=1 Hash=8", + "timecontrol" : "8.0+0.08", + "report_rate" : 16, + "workload_size" : 32 + }, + + "LTC" : { + "options" : "Threads=1 Hash=64", + "timecontrol" : "40.0+0.4", + "report_rate" : 4, + "workload_size" : 8 + }, + + "SMP STC" : { + "options" : "Threads=8 Hash=64", + "timecontrol" : "5.0+0.05", + "report_rate" : 1, + "workload_size" : 64 + }, + + "SMP LTC" : { + "options" : "Threads=8 Hash=256", + "timecontrol" : "20.0+0.2", + "report_rate" : 1, + "workload_size" : 16 + } + } +} \ No newline at end of file diff --git a/Engines/Igel.json b/Engines/Igel.json new file mode 100644 index 0000000..f1d9c13 --- /dev/null +++ b/Engines/Igel.json @@ -0,0 +1,48 @@ +{ + "private" : false, + "nps" : 470000, + "base" : "master", + "source" : "https://github.com/vshcherbyna/igel", + + "bounds" : "[0.00, 3.00]", + "book" : "Pohl.epd", + "win_adj" : "movecount=3 score=400", + "draw_adj" : "movenumber=40 movecount=8 score=10", + + "build" : { + "path" : "src", + "compilers" : ["g++"], + "cpuflags" : ["POPCNT"] + }, + + "testmodes" : { + + "STC" : { + "options" : "Threads=1 Hash=8", + "timecontrol" : "10.0+0.1", + "report_rate" : 16, + "workload_size" : 32 + }, + + "LTC" : { + "options" : "Threads=1 Hash=64", + "timecontrol" : "60.0+0.6", + "report_rate" : 4, + "workload_size" : 8 + }, + + "SMP STC" : { + "options" : "Threads=8 Hash=64", + "timecontrol" : "5.0+0.05", + "report_rate" : 1, + "workload_size" : 64 + }, + + "SMP LTC" : { + "options" : "Threads=8 Hash=256", + "timecontrol" : "20.0+0.2", + "report_rate" : 1, + "workload_size" : 16 + } + } +} \ No newline at end of file diff --git a/Engines/Koivisto.json b/Engines/Koivisto.json new file mode 100644 index 0000000..9e0d532 --- /dev/null +++ b/Engines/Koivisto.json @@ -0,0 +1,48 @@ +{ + "private" : false, + "nps" : 1346000, + "base" : "master", + "source" : "https://github.com/Luecx/Koivisto", + + "bounds" : "[0.00, 2.50]", + "book" : "Pohl.epd", + "win_adj" : "movecount=3 score=400", + "draw_adj" : "movenumber=40 movecount=8 score=10", + + "build" : { + "path" : "src_files", + "compilers" : ["g++"], + "cpuflags" : ["AVX2", "FMA", "POPCNT"] + }, + + "testmodes" : { + + "STC" : { + "options" : "Threads=1 Hash=8", + "timecontrol" : "8.0+0.08", + "report_rate" : 16, + "workload_size" : 32 + }, + + "LTC" : { + "options" : "Threads=1 Hash=64", + "timecontrol" : "40.0+0.4", + "report_rate" : 4, + "workload_size" : 8 + }, + + "SMP STC" : { + "options" : "Threads=8 Hash=64", + "timecontrol" : "5.0+0.05", + "report_rate" : 1, + "workload_size" : 64 + }, + + "SMP LTC" : { + "options" : "Threads=8 Hash=256", + "timecontrol" : "20.0+0.2", + "report_rate" : 1, + "workload_size" : 16 + } + } +} \ No newline at end of file diff --git a/Engines/Laser.json b/Engines/Laser.json new file mode 100644 index 0000000..099c3e0 --- /dev/null +++ b/Engines/Laser.json @@ -0,0 +1,48 @@ +{ + "private" : false, + "nps" : 941000, + "base" : "master", + "source" : "https://github.com/jeffreyan11/uci-chess-engine", + + "bounds" : "[0.00, 5.00]", + "book" : "Pohl.epd", + "win_adj" : "movecount=3 score=400", + "draw_adj" : "movenumber=40 movecount=8 score=10", + + "build" : { + "path" : "src", + "compilers" : ["g++"], + "cpuflags" : ["POPCNT"] + }, + + "testmodes" : { + + "STC" : { + "options" : "Threads=1 Hash=8", + "timecontrol" : "8.0+0.08", + "report_rate" : 16, + "workload_size" : 32 + }, + + "LTC" : { + "options" : "Threads=1 Hash=64", + "timecontrol" : "40.0+0.4", + "report_rate" : 4, + "workload_size" : 8 + }, + + "SMP STC" : { + "options" : "Threads=8 Hash=64", + "timecontrol" : "5.0+0.05", + "report_rate" : 1, + "workload_size" : 64 + }, + + "SMP LTC" : { + "options" : "Threads=8 Hash=256", + "timecontrol" : "20.0+0.2", + "report_rate" : 1, + "workload_size" : 16 + } + } +} \ No newline at end of file diff --git a/Engines/RubiChess.json b/Engines/RubiChess.json new file mode 100644 index 0000000..873acb5 --- /dev/null +++ b/Engines/RubiChess.json @@ -0,0 +1,48 @@ +{ + "private" : false, + "nps" : 937000, + "base" : "master", + "source" : "https://github.com/Matthies/RubiChess", + + "bounds" : "[0.00, 5.00]", + "book" : "Pohl.epd", + "win_adj" : "movecount=3 score=400", + "draw_adj" : "movenumber=40 movecount=8 score=10", + + "build" : { + "path" : "src", + "compilers" : ["g++"], + "cpuflags" : ["POPCNT"] + }, + + "testmodes" : { + + "STC" : { + "options" : "Threads=1 Hash=8", + "timecontrol" : "10.0+0.1", + "report_rate" : 16, + "workload_size" : 32 + }, + + "LTC" : { + "options" : "Threads=1 Hash=64", + "timecontrol" : "60.0+0.6", + "report_rate" : 4, + "workload_size" : 8 + }, + + "SMP STC" : { + "options" : "Threads=8 Hash=64", + "timecontrol" : "5.0+0.05", + "report_rate" : 1, + "workload_size" : 64 + }, + + "SMP LTC" : { + "options" : "Threads=8 Hash=256", + "timecontrol" : "20.0+0.2", + "report_rate" : 1, + "workload_size" : 16 + } + } +} \ No newline at end of file diff --git a/Engines/Seer.json b/Engines/Seer.json new file mode 100644 index 0000000..773362d --- /dev/null +++ b/Engines/Seer.json @@ -0,0 +1,48 @@ +{ + "private" : false, + "nps" : 736000, + "base" : "main", + "source" : "https://github.com/connormcmonigle/seer-nnue", + + "bounds" : "[0.00, 5.00]", + "book" : "Pohl.epd", + "win_adj" : "movecount=3 score=400", + "draw_adj" : "movenumber=40 movecount=8 score=10", + + "build" : { + "path" : "build", + "compilers" : ["g++>=9.0.0"], + "cpuflags" : ["AVX2", "FMA", "POPCNT"] + }, + + "testmodes" : { + + "STC" : { + "options" : "Threads=1 Hash=32", + "timecontrol" : "8.0+0.08", + "report_rate" : 16, + "workload_size" : 32 + }, + + "LTC" : { + "options" : "Threads=1 Hash=64", + "timecontrol" : "40.0+0.4", + "report_rate" : 4, + "workload_size" : 8 + }, + + "SMP STC" : { + "options" : "Threads=8 Hash=64", + "timecontrol" : "5.0+0.05", + "report_rate" : 1, + "workload_size" : 64 + }, + + "SMP LTC" : { + "options" : "Threads=8 Hash=256", + "timecontrol" : "20.0+0.2", + "report_rate" : 1, + "workload_size" : 16 + } + } +} \ No newline at end of file diff --git a/Engines/Stash.json b/Engines/Stash.json new file mode 100644 index 0000000..83b8699 --- /dev/null +++ b/Engines/Stash.json @@ -0,0 +1,48 @@ +{ + "private" : false, + "nps" : 1689000, + "base" : "master", + "source" : "https://github.com/mhouppin/stash-bot", + + "bounds" : "[0.00, 5.00]", + "book" : "4moves_noob.epd", + "win_adj" : "movecount=3 score=400", + "draw_adj" : "movenumber=40 movecount=8 score=10", + + "build" : { + "path" : "src", + "compilers" : ["gcc", "clang"], + "cpuflags" : ["POPCNT"] + }, + + "testmodes" : { + + "STC" : { + "options" : "Threads=1 Hash=16", + "timecontrol" : "8.0+0.08", + "report_rate" : 16, + "workload_size" : 32 + }, + + "LTC" : { + "options" : "Threads=1 Hash=64", + "timecontrol" : "40.0+0.4", + "report_rate" : 4, + "workload_size" : 8 + }, + + "SMP STC" : { + "options" : "Threads=8 Hash=64", + "timecontrol" : "5.0+0.05", + "report_rate" : 1, + "workload_size" : 64 + }, + + "SMP LTC" : { + "options" : "Threads=8 Hash=256", + "timecontrol" : "20.0+0.2", + "report_rate" : 1, + "workload_size" : 16 + } + } +} \ No newline at end of file diff --git a/Engines/Weiss.json b/Engines/Weiss.json new file mode 100644 index 0000000..45ee574 --- /dev/null +++ b/Engines/Weiss.json @@ -0,0 +1,48 @@ +{ + "private" : false, + "nps" : 1758000, + "base" : "master", + "source" : "https://github.com/TerjeKir/weiss", + + "bounds" : "[0.00, 3.00]", + "book" : "Pohl.epd", + "win_adj" : "movecount=3 score=400", + "draw_adj" : "movenumber=40 movecount=8 score=10", + + "build" : { + "path" : "src", + "compilers" : ["gcc"], + "cpuflags" : ["POPCNT"] + }, + + "testmodes" : { + + "STC" : { + "options" : "Threads=1 Hash=32", + "timecontrol" : "8.0+0.08", + "report_rate" : 16, + "workload_size" : 32 + }, + + "LTC" : { + "options" : "Threads=1 Hash=128", + "timecontrol" : "40.0+0.4", + "report_rate" : 4, + "workload_size" : 8 + }, + + "SMP STC" : { + "options" : "Threads=8 Hash=128", + "timecontrol" : "5.0+0.05", + "report_rate" : 1, + "workload_size" : 64 + }, + + "SMP LTC" : { + "options" : "Threads=8 Hash=512", + "timecontrol" : "20.0+0.2", + "report_rate" : 1, + "workload_size" : 16 + } + } +} \ No newline at end of file diff --git a/Engines/Winter.json b/Engines/Winter.json new file mode 100644 index 0000000..7df2c7e --- /dev/null +++ b/Engines/Winter.json @@ -0,0 +1,48 @@ +{ + "private" : false, + "nps" : 661000, + "base" : "master", + "source" : "https://github.com/rosenthj/Winter", + + "bounds" : "[0.00, 5.00]", + "book" : "Pohl.epd", + "win_adj" : "movecount=3 score=400", + "draw_adj" : "movenumber=40 movecount=8 score=10", + + "build" : { + "path" : "", + "compilers" : ["clang++", "g++"], + "cpuflags" : ["POPCNT"] + }, + + "testmodes" : { + + "STC" : { + "options" : "Threads=1 Hash=8", + "timecontrol" : "8.0+0.08", + "report_rate" : 16, + "workload_size" : 32 + }, + + "LTC" : { + "options" : "Threads=1 Hash=64", + "timecontrol" : "40.0+0.4", + "report_rate" : 4, + "workload_size" : 8 + }, + + "SMP STC" : { + "options" : "Threads=8 Hash=64", + "timecontrol" : "5.0+0.05", + "report_rate" : 1, + "workload_size" : 64 + }, + + "SMP LTC" : { + "options" : "Threads=8 Hash=256", + "timecontrol" : "20.0+0.2", + "report_rate" : 1, + "workload_size" : 16 + } + } +} \ No newline at end of file diff --git a/Engines/Zahak.json b/Engines/Zahak.json new file mode 100644 index 0000000..8199d26 --- /dev/null +++ b/Engines/Zahak.json @@ -0,0 +1,48 @@ +{ + "private" : false, + "nps" : 946000, + "base" : "master", + "source" : "https://github.com/amanjpro/zahak", + + "bounds" : "[0.00, 5.00]", + "book" : "Pohl.epd", + "win_adj" : "movecount=3 score=400", + "draw_adj" : "movenumber=40 movecount=8 score=10", + + "build" : { + "path" : "", + "compilers" : ["go"], + "cpuflags" : ["AVX", "POPCNT"] + }, + + "testmodes" : { + + "STC" : { + "options" : "Threads=1 Hash=8", + "timecontrol" : "8.0+0.08", + "report_rate" : 16, + "workload_size" : 32 + }, + + "LTC" : { + "options" : "Threads=1 Hash=64", + "timecontrol" : "40.0+0.4", + "report_rate" : 4, + "workload_size" : 8 + }, + + "SMP STC" : { + "options" : "Threads=8 Hash=64", + "timecontrol" : "5.0+0.05", + "report_rate" : 1, + "workload_size" : 64 + }, + + "SMP LTC" : { + "options" : "Threads=8 Hash=256", + "timecontrol" : "20.0+0.2", + "report_rate" : 1, + "workload_size" : 16 + } + } +} \ No newline at end of file diff --git a/OpenBench/apps.py b/OpenBench/apps.py index c9b5743..48ea39e 100644 --- a/OpenBench/apps.py +++ b/OpenBench/apps.py @@ -20,5 +20,5 @@ import django.apps -class OpenbenchConfig(django.apps.AppConfig): +class OpenBench(django.apps.AppConfig): name = 'OpenBench' diff --git a/OpenBench/config.py b/OpenBench/config.py index 4ca1d14..1d3a63e 100644 --- a/OpenBench/config.py +++ b/OpenBench/config.py @@ -18,17 +18,34 @@ # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # -USE_CROSS_APPROVAL = False +import json, os.path +from OpenSite.settings import PROJECT_PATH + +def load_json_config(*path): + with open(os.path.join(PROJECT_PATH, *path)) as fin: + return json.load(fin) + +def load_folder_of_configs(*path): + return { + fname.removesuffix('.json') : load_json_config(*path, fname) + for fname in os.listdir(os.path.join(PROJECT_PATH, *path)) if fname.endswith('.json') + } + +USE_CROSS_APPROVAL = False # Require a second user to approve patches +REQUIRE_LOGIN_TO_VIEW = True # Block all content but Login and Regiser by default +REQUIRE_MANUAL_REGISTRATION = False # Disable the public facing registration page OPENBENCH_CONFIG = { # Server Client version control - 'client_version' : '4', + 'client_version' : '9', # Generic Error Messages useful to those setting up their own instance 'error' : { - 'disabled' : 'Account has not been enabled. Contact andrew@grantnet.us', - 'fakeuser' : 'This is not a real OpenBench User. Create an OpenBench account', + 'disabled' : 'Account has not been enabled. Contact andrew@grantnet.us', + 'fakeuser' : 'This is not a real OpenBench User. Create an OpenBench account', + 'requires_login' : 'All pages require a user login to access', + 'manual_registration' : 'Registration can only be done via an Administrator', }, # Link to the repo on the sidebar, as well as the core files @@ -36,466 +53,14 @@ OPENBENCH_CONFIG = { 'corefiles' : 'https://raw.githubusercontent.com/AndyGrant/OpenBench/master/CoreFiles', # Test Configuration. For both SPRT and Fixed Games Tests - 'tests' : { - 'max_games' : '20000', # Default for Fixed Games + 'max_games' : '40000', # Default for Fixed Games 'confidence' : '[0.05, 0.05]', # SPRT Type I/II Confidence }, - # Book Configuration. When addding a book, follow the provided template. - # The SHA is defined by hashlib.sha256(book.read().encode('utf-8')).hexdigest(). - # Client.py has this exact code to generate and verify sha256 values, as an example. + # Take a look at Books/books.json + 'books' : load_json_config('Books', 'books.json'), - 'books' : { - - '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', - }, - }, - - - # Engine Configuration. All engines must have a name, a source repo, - # a set of paramaters for each standard test type, as well as a scaled - # NPS value, which is used to normalize speed across all workers. - - 'engines' : { - - 'Ethereal' : { - - 'nps' : 850000, - 'base' : 'master', - 'book' : 'Pohl.epd', - 'bounds' : '[0.00, 3.00]', - 'source' : 'https://github.com/AndyGrant/Ethereal', - - 'build' : { - 'path' : 'src', - 'compilers' : ['clang', 'gcc'], - 'cpuflags' : ['AVX2', 'AVX', 'FMA', 'POPCNT', 'SSE2', 'SSE'], - }, - - 'testmodes' : [ - { 'id' : 'STC', 'th' : 1, 'hash' : 8, 'tc' : '10.0+0.1' }, - { 'id' : 'LTC', 'th' : 1, 'hash' : 64, 'tc' : '60.0+0.6' }, - { 'id' : 'SMP STC', 'th' : 8, 'hash' : 64, 'tc' : '5.0+0.05' }, - { 'id' : 'SMP LTC', 'th' : 8, 'hash' : 256, 'tc' : '20.0+0.2' }, - { 'id' : 'STC Simplification', 'th' : 1, 'hash' : 8, 'tc' : '10.0+0.1', 'bounds' : '[-3.00, 1.00]' }, - { 'id' : 'LTC Simplification', 'th' : 1, 'hash' : 64, 'tc' : '60.0+0.6', 'bounds' : '[-3.00, 1.00]' }, - { 'id' : 'STC Regression', 'th' : 1, 'hash' : 8, 'tc' : '10.0+0.1', 'book' : '8moves_v3.epd', 'games' : 40000 }, - { 'id' : 'LTC Regression', 'th' : 1, 'hash' : 64, 'tc' : '60.0+0.6', 'book' : '8moves_v3.epd', 'games' : 40000 }, - ], - }, - - 'Laser' : { - - 'nps' : 935000, - 'base' : 'master', - 'book' : 'Pohl.epd', - 'bounds' : '[0.00, 5.00]', - 'source' : 'https://github.com/jeffreyan11/uci-chess-engine', - - 'build' : { - 'path' : 'src', - 'compilers' : ['g++'], - 'cpuflags' : ['POPCNT'], - }, - - 'testmodes' : [ - { 'id' : 'STC', 'th' : 1, 'hash' : 8, 'tc' : '8.0+0.08' }, - { 'id' : 'LTC', 'th' : 1, 'hash' : 64, 'tc' : '40.0+0.4' }, - { 'id' : 'SMP STC', 'th' : 8, 'hash' : 64, 'tc' : '5.0+0.05' }, - { 'id' : 'SMP LTC', 'th' : 8, 'hash' : 256, 'tc' : '20.0+0.2' }, - ], - }, - - 'Weiss' : { - - 'nps' : 1700000, - 'base' : 'master', - 'book' : 'Pohl.epd', - 'bounds' : '[-1.00, 4.00]', - 'source' : 'https://github.com/TerjeKir/weiss', - - 'build' : { - 'path' : 'src', - 'compilers' : ['gcc'], - 'cpuflags' : ['POPCNT'], - }, - - 'testmodes' : [ - { 'id' : 'STC', 'th' : 1, 'hash' : 32, 'tc' : '8.0+0.08' }, - { 'id' : 'LTC', 'th' : 1, 'hash' : 128, 'tc' : '40.0+0.4' }, - { 'id' : 'SMP STC', 'th' : 8, 'hash' : 128, 'tc' : '5.0+0.05' }, - { 'id' : 'SMP LTC', 'th' : 8, 'hash' : 512, 'tc' : '20.0+0.2' }, - ], - }, - - 'Demolito' : { - - 'nps' : 1375000, - 'base' : 'master', - 'book' : 'Pohl.epd', - 'bounds' : '[0.00, 5.00]', - 'source' : 'https://github.com/lucasart/Demolito', - - 'build' : { - 'path' : 'src', - 'compilers' : ['clang', 'gcc'], - 'cpuflags' : ['POPCNT'], - }, - - 'testmodes' : [ - { 'id' : 'STC', 'th' : 1, 'hash' : 8, 'tc' : '8.0+0.08' }, - { 'id' : 'LTC', 'th' : 1, 'hash' : 32, 'tc' : '32.0+0.32'}, - { 'id' : 'SMP STC', 'th' : 8, 'hash' : 32, 'tc' : '4.0+0.04' }, - { 'id' : 'SMP LTC', 'th' : 8, 'hash' : 128, 'tc' : '16.0+0.16'}, - ], - }, - - 'RubiChess' : { - - 'nps' : 885000, - 'base' : 'master', - 'book' : 'Pohl.epd', - 'bounds' : '[0.00, 5.00]', - 'source' : 'https://github.com/Matthies/RubiChess', - - 'build' : { - 'path' : 'src', - 'compilers' : ['g++'], - 'cpuflags' : ['POPCNT'], - }, - - 'testmodes' : [ - { 'id' : 'STC', 'th' : 1, 'hash' : 8, 'tc' : '10.0+0.1' }, - { 'id' : 'LTC', 'th' : 1, 'hash' : 64, 'tc' : '60.0+0.6' }, - { 'id' : 'SMP STC', 'th' : 8, 'hash' : 64, 'tc' : '5.0+0.05' }, - { 'id' : 'SMP LTC', 'th' : 8, 'hash' : 256, 'tc' : '20.0+0.2' }, - ], - }, - - 'FabChess' : { - - 'nps' : 1030000, - 'base' : 'master', - 'book' : 'Pohl.epd', - 'bounds' : '[0.00, 5.00]', - 'source' : 'https://github.com/fabianvdW/FabChess', - - 'build' : { - 'path' : '', - 'compilers' : ['cargo>=1.41.0'], - 'cpuflags' : ['POPCNT'], - }, - - 'testmodes' : [ - { 'id' : 'STC', 'th' : 1, 'hash' : 8, 'tc' : '8.0+0.08' }, - { 'id' : 'LTC', 'th' : 1, 'hash' : 64, 'tc' : '40.0+0.4' }, - { 'id' : 'SMP STC', 'th' : 8, 'hash' : 64, 'tc' : '5.0+0.05' }, - { 'id' : 'SMP LTC', 'th' : 8, 'hash' : 256, 'tc' : '20.0+0.2' }, - ], - }, - - 'Igel' : { - - 'nps' : 450000, - 'base' : 'master', - 'book' : 'Pohl.epd', - 'bounds' : '[0.00, 3.00]', - 'source' : 'https://github.com/vshcherbyna/igel', - - 'build' : { - 'path' : 'src', - 'compilers' : ['g++'], - 'cpuflags' : ['POPCNT'], - }, - - 'testmodes' : [ - { 'id' : 'STC', 'th' : 1, 'hash' : 8, 'tc' : '10.0+0.1' }, - { 'id' : 'LTC', 'th' : 1, 'hash' : 64, 'tc' : '60.0+0.6' }, - { 'id' : 'SMP STC', 'th' : 8, 'hash' : 64, 'tc' : '5.0+0.05' }, - { 'id' : 'SMP LTC', 'th' : 8, 'hash' : 256, 'tc' : '20.0+0.2' }, - ], - }, - - 'Winter' : { - - 'nps' : 610000, - 'base' : 'master', - 'book' : 'Pohl.epd', - 'bounds' : '[0.00, 5.00]', - 'source' : 'https://github.com/rosenthj/Winter', - - 'build' : { - 'path' : '', - 'compilers' : ['clang++', 'g++'], - 'cpuflags' : ['POPCNT'], - }, - - 'testmodes' : [ - { 'id' : 'STC', 'th' : 1, 'hash' : 8, 'tc' : '8.0+0.08' }, - { 'id' : 'LTC', 'th' : 1, 'hash' : 64, 'tc' : '40.0+0.4' }, - { 'id' : 'SMP STC', 'th' : 8, 'hash' : 64, 'tc' : '5.0+0.05' }, - { 'id' : 'SMP LTC', 'th' : 8, 'hash' : 256, 'tc' : '20.0+0.2' }, - ], - }, - - 'Halogen' : { - - 'nps' : 1850000, - 'base' : 'master', - 'book' : 'Pohl.epd', - 'bounds' : '[0.00, 5.00]', - 'source' : 'https://github.com/KierenP/Halogen', - - 'build' : { - 'path' : 'src', - 'compilers' : ['g++'], - 'cpuflags' : ['POPCNT'], - }, - - 'testmodes' : [ - { 'id' : 'STC', 'th' : 1, 'hash' : 8, 'tc' : '8.0+0.08' }, - { 'id' : 'LTC', 'th' : 1, 'hash' : 64, 'tc' : '40.0+0.4' }, - { 'id' : 'SMP STC', 'th' : 8, 'hash' : 64, 'tc' : '5.0+0.05' }, - { 'id' : 'SMP LTC', 'th' : 8, 'hash' : 256, 'tc' : '20.0+0.2' }, - ], - }, - - 'Stash' : { - - 'nps' : 1650000, - 'base' : 'master', - 'book' : '4moves_noob.epd', - 'bounds' : '[0.00, 5.00]', - 'source' : 'https://github.com/mhouppin/stash-bot', - - 'build' : { - 'path' : 'src', - 'compilers' : ['gcc', 'clang'], - 'cpuflags' : ['POPCNT'], - }, - - 'testmodes' : [ - { 'id' : 'STC', 'th' : 1, 'hash' : 16, 'tc' : '8.0+0.08' }, - { 'id' : 'LTC', 'th' : 1, 'hash' : 64, 'tc' : '40.0+0.4' }, - { 'id' : 'SMP STC', 'th' : 8, 'hash' : 64, 'tc' : '5.0+0.05' }, - { 'id' : 'SMP LTC', 'th' : 8, 'hash' : 256, 'tc' : '20.0+0.2' }, - ], - }, - - 'Seer' : { - - 'nps' : 890000, - 'base' : 'main', - 'book' : 'Pohl.epd', - 'bounds' : '[0.00, 5.00]', - 'source' : 'https://github.com/connormcmonigle/seer-nnue', - - 'build' : { - 'path' : 'build', - 'compilers' : ['g++>=9.0.0'], - 'cpuflags' : ['AVX2', 'AVX', 'FMA', 'POPCNT', 'SSE2', 'SSE'], - }, - - 'testmodes' : [ - { 'id' : 'STC', 'th' : 1, 'hash' : 32, 'tc' : '8.0+0.08' }, - { 'id' : 'LTC', 'th' : 1, 'hash' : 64, 'tc' : '40.0+0.4' }, - { 'id' : 'SMP STC', 'th' : 8, 'hash' : 64, 'tc' : '5.0+0.05' }, - { 'id' : 'SMP LTC', 'th' : 8, 'hash' : 256, 'tc' : '20.0+0.2' }, - ], - }, - - 'Koivisto' : { - - 'nps' : 1275000, - 'base' : 'master', - 'book' : 'Pohl.epd', - 'bounds' : '[0.00, 2.50]', - 'source' : 'https://github.com/Luecx/Koivisto', - - 'build' : { - 'path' : 'src_files', - 'compilers' : ['g++'], - 'cpuflags' : ['AVX2', 'AVX', 'FMA', 'POPCNT', 'SSE2', 'SSE'], - }, - - 'testmodes' : [ - { 'id' : 'STC', 'th' : 1, 'hash' : 8, 'tc' : '8.0+0.08' }, - { 'id' : 'LTC', 'th' : 1, 'hash' : 64, 'tc' : '40.0+0.4' }, - { 'id' : 'SMP STC', 'th' : 8, 'hash' : 64, 'tc' : '5.0+0.05' }, - { 'id' : 'SMP LTC', 'th' : 8, 'hash' : 256, 'tc' : '20.0+0.2' }, - ], - }, - - 'Drofa' : { - - 'nps' : 1275000, - 'base' : 'master', - 'book' : '4moves_noob.epd', - 'bounds' : '[0.00, 5.00]', - 'source' : 'https://github.com/justNo4b/Drofa', - - 'build' : { - 'path' : '', - 'compilers' : ['g++'], - 'cpuflags' : ['POPCNT'], - }, - - 'testmodes' : [ - { 'id' : 'STC', 'th' : 1, 'hash' : 8, 'tc' : '8.0+0.08' }, - { 'id' : 'LTC', 'th' : 1, 'hash' : 64, 'tc' : '40.0+0.4' }, - { 'id' : 'SMP STC', 'th' : 8, 'hash' : 64, 'tc' : '5.0+0.05' }, - { 'id' : 'SMP LTC', 'th' : 8, 'hash' : 256, 'tc' : '20.0+0.2' }, - ], - }, - - 'Bit-Genie' : { - - 'nps' : 1990000, - 'base' : 'master', - 'book' : 'Pohl.epd', - 'bounds' : '[0.00, 5.00]', - 'source' : 'https://github.com/Aryan1508/Bit-Genie', - - 'build' : { - 'path' : 'src', - 'compilers' : ['g++'], - 'cpuflags' : ['POPCNT'], - }, - - 'testmodes' : [ - { 'id' : 'STC', 'th' : 1, 'hash' : 8, 'tc' : '8.0+0.08' }, - { 'id' : 'LTC', 'th' : 1, 'hash' : 64, 'tc' : '40.0+0.4' }, - { 'id' : 'SMP STC', 'th' : 8, 'hash' : 64, 'tc' : '5.0+0.05' }, - { 'id' : 'SMP LTC', 'th' : 8, 'hash' : 256, 'tc' : '20.0+0.2' }, - ], - }, - - 'Berserk' : { - - 'nps' : 1025000, - 'base' : 'main', - 'book' : 'Pohl.epd', - 'bounds' : '[0.00, 3.00]', - 'source' : 'https://github.com/jhonnold/berserk', - - 'build' : { - 'path' : 'src', - 'compilers' : ['gcc'], - 'cpuflags' : ['AVX2', 'AVX', 'FMA', 'POPCNT', 'SSE2', 'SSE'], - }, - - 'testmodes' : [ - { 'id' : 'STC', 'th' : 1, 'hash' : 8, 'tc' : '8.0+0.08' }, - { 'id' : 'LTC', 'th' : 1, 'hash' : 64, 'tc' : '40.0+0.4' }, - { 'id' : 'SMP STC', 'th' : 8, 'hash' : 64, 'tc' : '4.0+0.04' }, - { 'id' : 'SMP LTC', 'th' : 8, 'hash' : 256, 'tc' : '16.0+0.16' }, - ], - }, - - 'Zahak' : { - - 'nps' : 850000, - 'base' : 'master', - 'book' : 'Pohl.epd', - 'bounds' : '[0.00, 5.00]', - 'source' : 'https://github.com/amanjpro/zahak', - - 'build' : { - 'path' : '', - 'compilers' : ['go'], - 'cpuflags' : ['AVX', 'POPCNT'], - }, - - 'testmodes' : [ - { 'id' : 'STC', 'th' : 1, 'hash' : 8, 'tc' : '8.0+0.08' }, - { 'id' : 'LTC', 'th' : 1, 'hash' : 64, 'tc' : '40.0+0.4' }, - { 'id' : 'SMP STC', 'th' : 8, 'hash' : 64, 'tc' : '5.0+0.05' }, - { 'id' : 'SMP LTC', 'th' : 8, 'hash' : 256, 'tc' : '20.0+0.2' }, - ], - }, - - 'BlackMarlin' : { - - 'nps' : 1075000, - 'base' : 'main', - 'book' : 'Pohl.epd', - 'bounds' : '[0.00, 5.00]', - 'source' : 'https://github.com/dsekercioglu/blackmarlin', - - 'build' : { - 'path' : '', - 'compilers': ['cargo>=1.57.0'], - 'cpuflags' : ['AVX2', 'AVX', 'FMA', 'POPCNT', 'SSE2', 'SSE'], - }, - - 'testmodes' : [ - { 'id' : 'STC', 'th' : 1, 'hash' : 8, 'tc' : '8.0+0.08' }, - { 'id' : 'LTC', 'th' : 1, 'hash' : 64, 'tc' : '40.0+0.4' }, - { 'id' : 'SMP STC', 'th' : 8, 'hash' : 64, 'tc' : '5.0+0.05' }, - { 'id' : 'SMP LTC', 'th' : 8, 'hash' : 256, 'tc' : '20.0+0.2' }, - ], - }, - - '4ku' : { - - 'nps' : 1515000, - 'base' : 'master', - 'book' : 'Pohl.pgn', - 'bounds' : '[0.00, 5.00]', - 'source' : 'https://github.com/kz04px/4ku', - - 'build' : { - 'path' : '', - 'compilers' : ['g++'], - 'cpuflags' : ['POPCNT'], - }, - - 'testmodes' : [ - { 'id' : 'STC', 'th' : 1, 'hash' : 64, 'tc' : '8.0+0.08' }, - { 'id' : 'LTC', 'th' : 1, 'hash' : 64, 'tc' : '40.0+0.4' }, - { 'id' : 'SMP STC', 'th' : 8, 'hash' : 64, 'tc' : '5.0+0.05' }, - { 'id' : 'SMP LTC', 'th' : 8, 'hash' : 256, 'tc' : '20.0+0.2' }, - ], - }, - }, + # Take a look at json file in Engines/ + 'engines' : load_folder_of_configs('Engines'), } diff --git a/OpenBench/management/__init__.py b/OpenBench/management/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/OpenBench/management/commands/__init__.py b/OpenBench/management/commands/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/OpenBench/management/commands/runserver.py b/OpenBench/management/commands/runserver.py new file mode 100644 index 0000000..4f2f003 --- /dev/null +++ b/OpenBench/management/commands/runserver.py @@ -0,0 +1,48 @@ +import django.apps +import threading, time +import OpenBench.utils + +from django.core.management.commands.runserver import Command as BaseRunserverCommand + +class ArtifactWatcher(threading.Thread): + + def update_test(self, test): + + dev_has_all = test.dev.source.endswith('artifacts') + base_has_all = test.base.source.endswith('artifacts') + + dev_headers = OpenBench.utils.read_git_credentials(test.dev_engine) + base_headers = OpenBench.utils.read_git_credentials(test.base_engine) + + if dev_headers and not dev_has_all: + test.dev.source, dev_has_all = OpenBench.utils.fetch_artifact_url( + test.dev.source, test.dev_engine, dev_headers, test.dev.sha) + test.dev.save() + + if base_headers and not base_has_all: + test.base.source, base_has_all = OpenBench.utils.fetch_artifact_url( + test.base.source, test.base_engine, base_headers, test.base.sha) + test.base.save() + + if dev_has_all and base_has_all: + test.awaiting = False + test.save() + + def run(self): + while True: + for test in OpenBench.utils.get_awaiting_tests(): + self.update_test(test) + time.sleep(10) + +class Command(BaseRunserverCommand): + + def inner_run(self, *args, **options): + self.pre_start() + super().inner_run(*args, **options) + self.pre_quit() + + def pre_start(self): + self.watcher = ArtifactWatcher().start() + + def pre_quit(self): + self.watcher.kill() diff --git a/OpenBench/models.py b/OpenBench/models.py index ef32e14..9667459 100644 --- a/OpenBench/models.py +++ b/OpenBench/models.py @@ -19,7 +19,7 @@ # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # from django.db.models import CharField, IntegerField, BooleanField, FloatField -from django.db.models import ForeignKey, DateTimeField, OneToOneField +from django.db.models import JSONField, ForeignKey, DateTimeField, OneToOneField from django.db.models import CASCADE, PROTECT, Model from django.contrib.auth.models import User @@ -38,7 +38,7 @@ class Profile(Model): user = ForeignKey(User, PROTECT, related_name='user') games = IntegerField(default=0) tests = IntegerField(default=0) - repo = CharField(max_length=256, blank=True) + repos = JSONField(default=dict) engine = CharField(max_length=128, blank=True) enabled = BooleanField(default=False) approver = BooleanField(default=False) @@ -50,15 +50,14 @@ class Profile(Model): class Machine(Model): user = ForeignKey(User, PROTECT, related_name='owner') - osname = CharField(max_length=128) - threads = IntegerField(default=0) mnps = FloatField(default=0.00) updated = DateTimeField(auto_now=True) - lastaddr = CharField(max_length=64, default='None') - workload = ForeignKey('Test', PROTECT, related_name='workload', default=1) + secret = CharField(max_length=64, default='None') + info = JSONField() + workload = IntegerField(default=0) def __str__(self): - return '{0}-{1} ({2})'.format(self.user.username, self.osname, self.id) + return '[%d] %s' % (self.id, self.user.username) class Result(Model): @@ -77,61 +76,72 @@ class Result(Model): class Test(Model): - author = CharField(max_length=64) - engine = CharField(max_length=64) - test_mode = CharField(max_length=16, default='SPRT') + # Misc information + author = CharField(max_length=64) + book_name = CharField(max_length=32) - dev = ForeignKey('Engine', PROTECT, related_name='dev') - base = ForeignKey('Engine', PROTECT, related_name='base') - source = CharField(max_length=1024) + # Dev Engine, and all of its settings + dev = ForeignKey('Engine', PROTECT, related_name='dev') + dev_repo = CharField(max_length=1024) + dev_engine = CharField(max_length=64) + dev_options = CharField(max_length=256) + dev_network = CharField(max_length=256) + dev_netname = CharField(max_length=256) + dev_time_control = CharField(max_length=32) - devoptions = CharField(max_length=256) - baseoptions = CharField(max_length=256) + # Base Engine, and all of its settings + base = ForeignKey('Engine', PROTECT, related_name='base') + base_repo = CharField(max_length=1024) + base_engine = CharField(max_length=64) + base_options = CharField(max_length=256) + base_network = CharField(max_length=256) + base_netname = CharField(max_length=256) + base_time_control = CharField(max_length=32) - devnetwork = CharField(max_length=256) - basenetwork = CharField(max_length=256) + # Changable Test Parameters + report_rate = IntegerField(default=8) + workload_size = IntegerField(default=32) + priority = IntegerField(default=0) + throughput = IntegerField(default=0) - devnetname = CharField(max_length=256) - basenetname = CharField(max_length=256) - - bookname = CharField(max_length=32) - timecontrol = CharField(max_length=16) - - priority = IntegerField(default=0) - throughput = IntegerField(default=0) - - syzygy_adj = CharField(max_length=16, default='OPTIONAL') + # Tablebases and Cutechess adjudicatoins syzygy_wdl = CharField(max_length=16, default='OPTIONAL') + syzygy_adj = CharField(max_length=16, default='OPTIONAL') + win_adj = CharField(max_length=64, default='movecount=3 score=400') + draw_adj = CharField(max_length=64, default='movenumber=40 movecount=8 score=10') - # Only for SPRT Tests - elolower = FloatField(default=0.0) - eloupper = FloatField(default=0.0) - alpha = FloatField(default=0.0) - beta = FloatField(default=0.0) - lowerllr = FloatField(default=0.0) - currentllr = FloatField(default=0.0) - upperllr = FloatField(default=0.0) - - # Only for Fixed-Games Tests - max_games = IntegerField(default=0) + # Test Mode specific values, either SPRT or GAMES + test_mode = CharField(max_length=16, default='SPRT') + elolower = FloatField(default=0.0) # SPRT + eloupper = FloatField(default=0.0) # SPRT + alpha = FloatField(default=0.0) # SPRT + beta = FloatField(default=0.0) # SPRT + lowerllr = FloatField(default=0.0) # SPRT + currentllr = FloatField(default=0.0) # SPRT + upperllr = FloatField(default=0.0) # SPRT + max_games = IntegerField(default=0) # GAMES + # Summary of all associated result objects games = IntegerField(default=0) wins = IntegerField(default=0) draws = IntegerField(default=0) losses = IntegerField(default=0) error = BooleanField(default=False) + # All status flags associated with the test passed = BooleanField(default=False) failed = BooleanField(default=False) finished = BooleanField(default=False) deleted = BooleanField(default=False) approved = BooleanField(default=False) + awaiting = BooleanField(default=False) + # Datetime house keeping for meta data creation = DateTimeField(auto_now_add=True) updated = DateTimeField(auto_now=True) def __str__(self): - return '{0} vs {1} @ {2}'.format(self.dev.name, self.base.name, self.timecontrol) + return '{0} vs {1} @ {2}'.format(self.dev.name, self.base.name, self.dev_time_control) class LogEvent(Model): diff --git a/OpenBench/static/base.css b/OpenBench/static/base.css new file mode 100644 index 0000000..1e4a577 --- /dev/null +++ b/OpenBench/static/base.css @@ -0,0 +1,331 @@ +.w-25 { + width: 25%; +} + +.w-21 { + width: 21%; +} + +.w-50 { + width: 50%; +} + +.w-75 { + width: 75%; +} + +.w-100 { + width: 100%; +} + +.mw-25 { + max-width: 25%; +} + +.mw-50 { + max-width: 50%; +} + +.mw-75 { + max-width: 75%; +} + +.mw-100 { + max-width: 100%; +} + +.mt-0 { + margin-top: 0.00rem; +} + +.mt-1 { + margin-top: 0.25rem; +} + +.mt-2 { + margin-top: 0.5rem; +} + +.mt-3 { + margin-top: 1rem; +} + +.mt-4 { + margin-top: 1.5rem; +} + +.mt-5 { + margin-top: 3rem; +} + +.mb-0 { + margin-bottom: 0.00rem; +} + +.mb-1 { + margin-bottom: 0.25rem; +} + +.mb-2 { + margin-bottom: 0.5rem; +} + +.mb-3 { + margin-bottom: 1rem; +} + +.mb-4 { + margin-bottom: 1.5rem; +} + +.mb-5 { + margin-bottom: 3rem; +} + +.ml-0 { + margin-left: 0.00rem; +} + +.ml-1 { + margin-left: 0.25rem; +} + +.ml-2 { + margin-left: 0.5rem; +} + +.ml-3 { + margin-left: 1rem; +} + +.ml-4 { + margin-left: 1.5rem; +} + +.ml-5 { + margin-left: 3rem; +} + +.mr-0 { + margin-right: 0.00rem; +} + +.mr-1 { + margin-right: 0.25rem; +} + +.mr-2 { + margin-right: 0.5rem; +} + +.mr-3 { + margin-right: 1rem; +} + +.mr-4 { + margin-right: 1.5rem; +} + +.mr-5 { + margin-right: 3rem; +} + +.mx-1 { + margin-left: 0.25rem; + margin-right: 0.25rem; +} + +.mx-2 { + margin-left: 0.5rem; + margin-right: 0.5rem; +} + +.mx-3 { + margin-left: 1rem; + margin-right: 1rem; +} + +.mx-4 { + margin-left: 1.5rem; + margin-right: 1.5rem; +} + +.mx-5 { + margin-left: 3rem; + margin-right: 3rem; +} + +.my-1 { + margin-top: 0.25rem; + margin-bottom: 0.25rem; +} + +.my-2 { + margin-top: 0.5rem; + margin-bottom: 0.5rem; +} + +.my-3 { + margin-top: 1rem; + margin-bottom: 1rem; +} + +.my-4 { + margin-top: 1.5rem; + margin-bottom: 1.5rem; +} + +.my-5 { + margin-top: 3rem; + margin-bottom: 3rem; +} + +.p-1{ + padding: 0.25rem; +} + +.p-2{ + padding: 0.5rem; +} + +.p-3{ + padding: 0.75rem; +} + +.p-4{ + padding: 1.0rem; +} + +.p-5{ + padding: 1.25rem; +} + +.pt-1 { + padding-top: 0.25rem; +} + +.pt-2 { + padding-top: 0.5rem; +} + +.pt-3 { + padding-top: 1rem; +} + +.pt-4 { + padding-top: 1.5rem; +} + +.pt-5 { + padding-top: 3rem; +} + +.pb-1 { + padding-bottom: 0.25rem; +} + +.pb-2 { + padding-bottom: 0.5rem; +} + +.pb-3 { + padding-bottom: 1rem; +} + +.pb-4 { + padding-bottom: 1.5rem; +} + +.pb-5 { + padding-bottom: 3rem; +} + +.pl-1 { + padding-left: 0.25rem; +} + +.pl-2 { + padding-left: 0.5rem; +} + +.pl-3 { + padding-left: 1rem; +} + +.pl-4 { + padding-left: 1.5rem; +} + +.pl-5 { + padding-left: 3rem; +} + +.pr-1 { + padding-right: 0.25rem; +} + +.pr-2 { + padding-right: 0.5rem; +} + +.pr-3 { + padding-right: 1rem; +} + +.pr-4 { + padding-right: 1.5rem; +} + +.pr-5 { + padding-right: 3rem; +} + +.px-1 { + padding-left: 0.25rem; + padding-right: 0.25rem; +} + +.px-2 { + padding-left: 0.5rem; + padding-right: 0.5rem; +} + +.px-3 { + padding-left: 1rem; + padding-right: 1rem; +} + +.px-4 { + padding-left: 1.5rem; + padding-right: 1.5rem; +} + +.px-5 { + padding-left: 3rem; + padding-right: 3rem; +} + +.py-1 { + padding-top: 0.25rem; + padding-bottom: 0.25rem; +} + +.py-2 { + padding-top: 0.5rem; + padding-bottom: 0.5rem; +} + +.py-3 { + padding-top: 1rem; + padding-bottom: 1rem; +} + +.py-4 { + padding-top: 1.5rem; + padding-bottom: 1.5rem; +} + +.py-5 { + padding-top: 3rem; + padding-bottom: 3rem; +} \ No newline at end of file diff --git a/OpenBench/static/create_test.js b/OpenBench/static/create_test.js new file mode 100644 index 0000000..726ef75 --- /dev/null +++ b/OpenBench/static/create_test.js @@ -0,0 +1,143 @@ +var config = JSON.parse(document.getElementById("json-config" ).textContent); +var networks = JSON.parse(document.getElementById("json-networks").textContent); + +function create_network_options(field_id, engine) { + + var has_default = false; + var network_options = document.getElementById(field_id); + + while (network_options.length) + network_options.remove(0); + + for (const network of networks) { + + if (network.engine !== engine) + continue; + + var opt = document.createElement("option"); + opt.text = network.name; + opt.value = network.sha256; + opt.selected = network.default; + network_options.add(opt) + + has_default = has_default || network.default; + } + + { + var opt = document.createElement("option"); + opt.text = "None"; + opt.value = ""; + opt.selected = !has_default; + network_options.add(opt); + } +} + +function create_testmode_buttons(engine) { + + // Clear out all of the existing buttons + var button_div = document.getElementById("test-mode-buttons"); + while (button_div.hasChildNodes()) + button_div.removeChild(button_div.lastChild); + + var index = 0; + for (let mode in config.engines[engine].testmodes) { + + // Create a new button for the test mode + var btn = document.createElement('button') + btn.innerHTML = mode; + btn.onclick = function() { set_test_mode(mode); }; + + // Apply all of our CSS bootstrapping + btn.classList.add("anchorbutton"); + btn.classList.add("btn-preset"); + btn.classList.add("mt-2"); + btn.classList.add("w-100"); + + // Put the button in a div, so we can handle padding + var div = document.createElement('div') + div.appendChild(btn) + div.classList.add("col-half"); + + // Left pad everything but the first + if ((index % 4) != 0) + div.classList.add("pl-1"); + + // Right pad everything but the last + if ((index % 4) != 3) + div.classList.add("pr-1"); + + button_div.append(div); + index++; + } +} + + +function set_test_type() { + + var selectA = document.getElementById("test_mode"); + var mode = selectA.options[selectA.selectedIndex].value; + + var selectB = document.getElementById("dev_engine"); + var engine = selectB.options[selectB.selectedIndex].value; + + + if (mode == "SPRT") { + document.getElementById("test_bounds" ).value = config.engines[engine].bounds + document.getElementById("test_confidence").value = config.tests.confidence; + document.getElementById("test_max_games" ).value = "N/A"; + } + + if (mode == "GAMES") { + document.getElementById("test_bounds" ).value = "N/A"; + document.getElementById("test_confidence").value = "N/A"; + document.getElementById("test_max_games" ).value = config.tests.max_games; + } +} + +function set_test_mode(mode_str) { + + var selection = document.getElementById("dev_engine"); + var engine = selection.options[selection.selectedIndex].value; + var mode = config.engines[engine].testmodes[mode_str]; + + document.getElementById("report_rate" ).value = mode["report_rate"] || 8; + document.getElementById("workload_size").value = mode["workload_size"] || 32; + document.getElementById("book_name" ).value = mode["book"] || config.engines[engine].book; + + document.getElementById("dev_options" ).value = mode["options"] || "Threads=1 Hash=8"; + document.getElementById("dev_time_control" ).value = mode["timecontrol"] || "10.0+0.1"; + + document.getElementById("base_options" ).value = mode["options"] || "Threads=1 Hash=8"; + document.getElementById("base_time_control").value = mode["timecontrol"] || "10.0+0.1"; + + if (mode["bounds"] != null) { + document.getElementById("test_mode").value = "SPRT"; set_test_type(); + document.getElementById("test_bounds").value = mode["bounds"]; + } + + if (mode["games"] != null) { + document.getElementById("test_mode").value = "GAMES"; set_test_type(); + document.getElementById("test_max_games").value = mode["games"]; + } + + if (mode["bounds"] == null && mode["games"] == null) { + document.getElementById("test_mode").value = "SPRT"; set_test_type(); + } +} + +function set_engine(engine, target) { + + document.getElementById(target + "_engine").value = engine; + + if (target == 'dev') { + create_testmode_buttons(engine); + set_test_mode('STC'); + } + + create_network_options(target + "_network", engine); + + document.getElementById("base_branch").value = config.engines[engine].base; + document.getElementById("book_name" ).value = config.engines[engine].book; + document.getElementById("win_adj" ).value = config.engines[engine].win_adj; + document.getElementById("draw_adj" ).value = config.engines[engine].draw_adj; +} diff --git a/OpenBench/static/ethereal.css b/OpenBench/static/ethereal.css new file mode 100644 index 0000000..347a0ef --- /dev/null +++ b/OpenBench/static/ethereal.css @@ -0,0 +1,307 @@ +body { + font-family: "Courier Prime"; + font-size: 18px; + background: #303030; +} + +a:link, a:visited, a:hover, a:active { + text-decoration: none; + color: #FFFFFF; +} + +#sidebar { + float: left; + margin: 16px; + margin-top: 60px; +} + +#sidebar ul { + list-style-type: none; + padding: 0px 16px 0px 8px; + line-height: 1.75; +} + +#sidebar li a { + color: #A2A2A2; + padding: 0px 16px; + font-size: 1.0rem; +} + +#sidebar li:hover { + background-color: #666666; + border-radius: 8px; +} + +#sidebar .header { + color: #00AF00; + padding: 0px 16px; + font-size: 1.0rem; +} + +#sidebar .header:hover { + background-color: #303030; +} + +#content { + float: left; + margin-top: 0; + color: #EAEAEA; +} + +#content label { + width: 128px; + padding-right: 10px; + text-align: right; + display: inline-block; + color: #A2A2A2; + font-size: 14px; +} + +#content input, #content select { + background-color: #BBBBBB; + color: #000000; + padding: 10px; + margin: 1px 0px; + width: 320px; + box-sizing: border-box; + -moz-box-sizing: border-box; + -webkit-box-sizing: border-box; +} + +#content button { + padding: 8px 0px; + margin: 2px 0px; + display: inline-block; + vertical-align: middle; + width: 290px; + background-color: #777777; + color: black; + border: none; + border-radius: 16px; + cursor: pointer; + font-weight: bold; +} + +#content button:hover { + background-color: #00AF00; +} + +#content input[type=submit] { + background-color: #00AF00; + color: #000000; + border: none; + border-radius: 16px; + cursor: pointer; + width: 100%; + font-weight: bold; +} + +#content input:read-only { + font-weight: bold; +} + +#content input:-moz-read-only { + font-weight: bold; +} + +#content #configuration { + float: left; + margin-top: 20px; +} + +#content #actions { + margin-left: 32px; + float: right; +} + +#content #actions h4 { + color: #A2A2A2; + font-size: 15px; + font-weight: bold; +} + +#content #actions .anchorbutton { + color: #000000; + padding: 8px 8px; + margin: 0px 8px; + border-radius: 16px; + font-weight: bold; + text-align: center; + display: inline-block; + width: 25%; +} + +#content #actions .anchorbutton a:hover { + background-color: #00AF00; +} + +#content #actions #approvebutton { + background-color: #9DF779; +} + +#content #actions #stopbutton { + background-color: #EEF788; +} + +#content #actions #restartbutton { + background-color: #EEF788; +} + +#content #actions #deletebutton { + background-color: #FA8E8E; +} + +#content #actions .deadbutton { + background-color: #808080; + pointer-events: none; +} + +#content #actions input { + width: 260px; +} + +#content #actions input[type=submit] { + width: 100%; +} + +#content .left-align { + text-align: left; +} + +#content tr:hover { + background-color: #666666; +} + +#content th { + color: #00AF00; + font-size: 16px; + font-weight: 100; + padding: 7px 12px 5px 12px; + background-color: #000000; +} + +#content td { + padding: 7px 12px 5px 12px; +} + +#content .numeric { + text-align: right; +} + +#content tr { + background-color: #202020; +} + +#content .table-spacer th { + background: #303030; + height: 16px; +} + +#content .statblock { + line-height: 70%; + color: black; + background-color: #CCCCCC; + border-radius: 4px; + font-family: "Courier New"; +} + +#content .green { + background-color: #9DF779 +} + +#content .yellow { + background-color: #EEF788 +} + +#content .red { + background-color: #FA8E8E +} + +#content #results { + display: inline-block; + width: inherit; +} + +#content table { + line-height: 96%; +} + +#content .textcenter { + text-align: center; +} + +#content strong { + font-size: 14px; + font-weight: bold; +} + +#content a:not(.TitleLink) { + font-weight: 100; + color: #8BBAD6; +} + +#content a.redlink { + color: #FF4D4D; +} + +#content a.unstarred { + color: #808080; +} + +#content h1, h2, h3 { + color: #a7a7a7; + text-align: center; +} + +#content #pagebrowse { + text-align: center; + margin: 16px 0px 16px 0px; +} + +#content .page { + text-align: center; + display: inline-block; + padding: 8px 0px; + width: 5%; + background-color: #1A1A1A; + border-radius: 8px; +} + +#content .page:hover { + background-color: #00AF00; +} + +#error { + background-color: #EE7676; + padding: 8px; + text-align: center; +} + +#content form h3 { + margin-left: 110px; + margin-bottom: 2px; + font-size: 16px; + font-weight: normal; + color: #00AF00; +} + +#content h4 a { + font-size: 18px; +} + +#content form .settings-column { + float: left; + padding-bottom: 16px; +} + +#content #test-mode-buttons button { + width: 49.8%; +} + +#content #test-mode-buttons .left-floated { + float: left; +} + +#content #test-mode-buttons .right-floated { + float: right; +} \ No newline at end of file diff --git a/OpenBench/static/form.css b/OpenBench/static/form.css new file mode 100644 index 0000000..5b1c162 --- /dev/null +++ b/OpenBench/static/form.css @@ -0,0 +1,119 @@ +#content .form .col-half { + display: inline-block; + width: 25%; + white-space: normal; + box-sizing: border-box; + vertical-align: top; +} + +#content .form .col { + display: inline-block; + width: 50%; + white-space: normal; + margin-left: 0; + box-sizing: border-box; + vertical-align: top; +} + +#content .form .col-full { + display: block; + width: 100%; + white-space: normal; + margin-left: 0; + box-sizing: border-box; + vertical-align: top; +} + +/* Styles for screen widths less than 600px */ + +@media (max-width: 1024px) { + #content .form .col { + display: block; + width: 100%; + } +} + +#content .form h3 { + font-size: 14px; + color: var(--color-font3); + text-align: left; + padding-left: 1.5rem; +} + +#content .form .row { + display: flex; + align-items: center; + margin-bottom: 0.5rem; +} + +#content .row label { + font-size: 14px; + width: 25%; + min-width: 128px; + margin-right: 1rem; + text-align: right; + color: var(--color-font2) +} + +#content .row input, #content .row select { + flex-grow: 1; + min-width: 0; + border: 1px solid var(--color3); + border-radius: 4px; + padding: 9px 6px 6px; + background-color: var(--color2); + color: var(--color-font2); + font-family: "Courier Prime", serif; +} + +#content .row input[type="file"]{ + padding: 2px 2px; +} + +#content .row input:focus, #content .row select:focus { + outline: none; + border-color: var(--color3); + box-shadow: 0 0 0 3px rgba(77, 144, 254, 0.25); + background-color: var(--color2); + color: var(--color-font2); +} + +#content .row select > option{ + font-family: "Helvetica", serif; +} + +#content .row input[type="file"]::file-selector-button { + background-color: var(--color3); + border: 1px solid var(--color2); + border-radius: 4px; + padding: 6px 6px 3px; + color: var(--color-font2); + cursor: pointer; + transition: background-color 0.3s, border-color 0.3s; + font-family: "Courier Prime", serif; +} + +#content .row input[type="file"]::file-selector-button:hover { + background-color: rgba(77, 144, 254, 0.8); + border-color: var(--color2); +} + +#content .form .flex { + display: flex; + flex-wrap: wrap; + max-width: 100%; + justify-content: flex-start; +} + +#content .form .flex button{ + max-width: 100%; +} + +#content #engines-container span { + margin: 0px 4px 0px 4px; + cursor: pointer; +} + +#content #engines-container span input { + cursor: pointer; +} \ No newline at end of file diff --git a/OpenBench/static/paging.css b/OpenBench/static/paging.css new file mode 100644 index 0000000..53024b2 --- /dev/null +++ b/OpenBench/static/paging.css @@ -0,0 +1,48 @@ +.pagination { + display: inline-flex; + justify-content: center; + align-items: center; +} + +#pagebrowse { + display: flex; + justify-content: center; +} + +.page, .ellipsis { + display: inline-block; + padding: 6px 1rem; + margin: 0; + border-left: 1px solid var(--color1); + border-right: 1px solid var(--color1); + background-color: var(--color2); /* Dark background color */ + color: var(--color-font2); + text-decoration: none; + cursor: pointer; + transition: background-color 0.2s; /* Add a smooth transition effect to background color */ + height: 24px; /* This is just an example, adjust according to your needs */ + line-height: 24px; /* Should be same as height */ + min-width: 1.6rem; + text-align: center; + vertical-align: middle; +} + +.page:hover { + background-color: var(--color3); /* Darker background color on hover */ +} + +.previous { + border-top-left-radius: 7px; + border-bottom-left-radius: 7px; +} + +.next { + border-top-right-radius: 7px; + border-bottom-right-radius: 7px; +} + +.ellipsis, .fa-solid { + /*margin: 0 4px;*/ + pointer-events: none; /* Disable click events on ellipsis */ + vertical-align: middle; /* Ensure icons are vertically centered */ +} diff --git a/OpenBench/static/style.css b/OpenBench/static/style.css index ff3a21e..d1de851 100644 --- a/OpenBench/static/style.css +++ b/OpenBench/static/style.css @@ -1,220 +1,297 @@ -body { - font-family: "Courier Prime"; - font-size: 18px; - background: #303030; -} a:link, a:visited, a:hover, a:active { text-decoration: none; - color: #FFFFFF; + color: #8BBAD6; +} + +body { + --color1: #222222; + --color2: #2D2D2D; + --color3: #3B3B3B; + + --color-font1: #DBDEE1; + --color-font2: #949BA4; + --color-font3: #008F11; + + background-color: var(--color1); + + font-size: 16px; + font-family: "Courier Prime", serif; + display:flex; +} + +body, html, main{ + padding: 0; + margin: 0; + min-width: 100%; + max-width: 100%; + white-space: nowrap; } #sidebar { - float: left; - margin: 16px; - margin-top: 60px; + padding: 60px 16px 16px 16px; + flex-basis: calc(min(300px, max(200px, 15%))); } +#content-parent{ + flex-grow: 1; + justify-content: left; + height: 100%; + + box-sizing: border-box; + padding-left: 2rem; + padding-right: 2rem; +} + +#content{ + max-width: calc(min(100%,1000px)); + width: 100%; + white-space: nowrap; + display: inline-block; +} + + +/* Styles for screen widths less than 600px */ +@media (max-width: 599px) { + #sidebar { + flex-basis: 100%; + padding: 16px; + } + + #content-parent { + height: auto; + flex-grow: 0; + flex-basis: 100%; + } + + body { + flex-direction: column; + } +} + + #sidebar ul { list-style-type: none; padding: 0px 16px 0px 8px; line-height: 1.75; } -#sidebar li a { - color: #A2A2A2; - padding: 0px 16px; +#sidebar li { + padding: 4px 16px 2px; font-size: 1.0rem; + border-radius: 4px; + transition: background-color 0.2s ease-in-out; +} + +#sidebar li a { + color: var(--color-font2); } #sidebar li:hover { - background-color: #666666; - border-radius: 8px; -} - -#sidebar .header { - color: #00AF00; - padding: 0px 16px; - font-size: 1.0rem; -} - -#sidebar .header:hover { background-color: #303030; } -#content { - float: left; - margin-top: 0; - color: #EAEAEA; -} - -#content label { - width: 128px; - padding-right: 10px; - text-align: right; - display: inline-block; - color: #A2A2A2; - font-size: 14px; -} - -#content input, #content select { - background-color: #BBBBBB; - color: #000000; - padding: 10px; - margin: 1px 0px; - width: 320px; - box-sizing: border-box; - -moz-box-sizing: border-box; - -webkit-box-sizing: border-box; -} - -#content button { - padding: 8px 0px; - margin: 2px 0px; - display: inline-block; - vertical-align: middle; - width: 290px; - background-color: #777777; - color: black; - border: none; - border-radius: 16px; - cursor: pointer; - font-weight: bold; -} - -#content button:hover { - background-color: #00AF00; -} - -#content input[type=submit] { - background-color: #00AF00; - color: #000000; - border: none; - border-radius: 16px; - cursor: pointer; - width: 100%; - font-weight: bold; -} - -#content input:read-only { - font-weight: bold; -} - -#content input:-moz-read-only { - font-weight: bold; -} - -#content #configuration { - float: left; - margin-top: 20px; -} - -#content #actions { - margin-left: 32px; - float: right; -} - -#content #actions h4 { - color: #A2A2A2; - font-size: 15px; - font-weight: bold; -} - -#content #actions .anchorbutton { - color: #000000; - padding: 8px 8px; - margin: 0px 8px; - border-radius: 16px; - font-weight: bold; - text-align: center; - display: inline-block; - width: 25%; -} - -#content #actions .anchorbutton a:hover { - background-color: #00AF00; -} - -#content #actions #approvebutton { - background-color: #9DF779; -} - -#content #actions #stopbutton { - background-color: #EEF788; -} - -#content #actions #restartbutton { - background-color: #EEF788; -} - -#content #actions #deletebutton { - background-color: #FA8E8E; -} - -#content #actions .deadbutton { - background-color: #808080; +#sidebar .header { + color: var(--color-font3); + font-size: 1.1rem; pointer-events: none; } -#content #actions input { - width: 260px; +#sidebar hr { + border: 1px var(--color2) solid; } -#content #actions input[type=submit] { - width: 100%; +/* Table Striping, with overriding for the Table Header */ + +#content .stripes tr:nth-child(odd):not(.table-header) { + background-color: var(--color1); } -#content .left-align { - text-align: left; +#content .stripes tr:nth-child(even):not(.table-header) { + background-color: var(--color2); } -#content tr:hover { - background-color: #666666; +#content .stripes th { + background-color: black; } -#content th { - color: #00AF00; - font-size: 16px; - font-weight: 100; - padding: 7px 12px 5px 12px; - background-color: #000000; +/* Tables that have hoverable table rows */ + +#content .hoverable tr:nth-child(odd):hover:not(.table-header) { + background-color: #323232; +} + +#content .hoverable tr:nth-child(even):hover:not(.table-header) { + background-color: #323232; +} + +#content .hoverable tr:hover{ + background-color: var(--color1); +} + +/* Tables that are too long can wrap words*/ + +#content .wrappable td{ + white-space: pre-wrap; + word-break: break-word; + word-wrap: break-word; +} + +/* Table Headers in General */ + +#content .table-header th:first-child { + border-top-left-radius: 12px; +} + +#content .table-header th:last-child { + border-top-right-radius: 12px; +} + +#content .table-header th { + color: var(--color-font3); + font-weight: 400; + background-color: #171717; +} + +/* Table Spacer for chaining Tables as a hack */ + +#content .table-spacer th { + background-color: var(--color1); + height: 1rem; +} + +/* Generic Table CSS for all Tables */ + +#content table { + line-height: 96%; + border-collapse: collapse; } #content td { - padding: 7px 12px 5px 12px; + color: var(--color-font2); + border-bottom: 1px #444444 solid; } -#content .numeric { - text-align: right; +#content th, #content td { + padding: 10px 12px 6px 12px; } -#content tr { - background-color: #202020; +#content .anchorbutton { + border-radius: 4px; + padding: 8px 8px 6px; + border-color: transparent; + color: var(--color-font1); + display: inline-block; + text-align: center; + transition: background-color 0.3s ease; + font-family: "Courier Prime", serif; } -#content .table-spacer th { - background: #303030; - height: 16px; +#content .btn-blue { + background-color: #1C2D40; } +#content .btn-start { + background-color: #384A5F; + width: 100%; +} + +#content .btn-preset { + background-color: #046c52; +} + +#content .btn-yellow { + background-color: #7A4E09; +} + +#content .btn-red { + background-color: #74261E; +} + +#content .btn-disabled { + background-color: var(--color3); +} + +#content .btn-blue:hover { + background-color: #2E3F57; +} + +#content .btn-start:hover { + background-color: #2E3F57; +} + +#content .btn-preset:hover { + background-color: #11a983; +} + +#content .btn-yellow:hover { + background-color: #9B6B0F; +} + +#content .btn-red:hover { + background-color: #8E3D28; +} + +#content .btn-disabled:hover { + background-color: var(--color3); + cursor: not-allowed; + transform: none; +} + +#content .copy-button { + color: var(--color-font2); + transition: color 0.2s ease-in-out; +} + +#content .copy-button:hover { + color: var(--color-font3); +} + +/* Short StatBlock to show SPRT and Test Results */ + #content .statblock { - line-height: 70%; + font-size: 13px; color: black; + line-height: 96%; background-color: #CCCCCC; - border-radius: 4px; font-family: "Courier New"; + border-radius: 4px; + padding: 9px 10px 6px; } -#content .green { - background-color: #9DF779 +#content .statblock-green { + background-color: #76D576; } -#content .yellow { - background-color: #EEF788 +#content .statblock-yellow { + background-color: #EFF891 } -#content .red { - background-color: #FA8E8E +#content .statblock-red { + background-color: #FA9696 +} + +#content .redlink { + color: #FF4D4D; +} + +/* Long StatBlock which we can copy */ + +#content .long-statblock { + background-color: var(--color3); + color: var(--color-font2); + border-radius: 4px; + padding: 0.50rem 0.75rem; +} + +/* Test Views */ + +#content #config { + float: left; +} + +#content #actions { + float: left; } #content #results { @@ -222,86 +299,29 @@ a:link, a:visited, a:hover, a:active { width: inherit; } -#content table { - line-height: 96%; +#content .test-config { + font-size: 1.0rem; } -#content .textcenter { - text-align: center; +#content .test-config .td-label { + color: var(--color-font1); } -#content strong { - font-size: 14px; - font-weight: bold; +/* ??? */ + +td pre { + margin: 0px; + padding: 0px; } -#content a:not(.TitleLink) { - font-weight: 100; - color: #8BBAD6; +#content .error-message { + color: red; } -#content a.redlink { - color: #FF4D4D; +#content .status-message { + color: green; } -#content a.unstarred { - color: #808080; -} - -#content h1, h2, h3 { - color: #a7a7a7; - text-align: center; -} - -#content #pagebrowse { - text-align: center; - margin: 16px 0px 16px 0px; -} - -#content .page { - text-align: center; - display: inline-block; - padding: 8px 0px; - width: 5%; - background-color: #1A1A1A; - border-radius: 8px; -} - -#content .page:hover { - background-color: #00AF00; -} - -#error { - background-color: #EE7676; - padding: 8px; - text-align: center; -} - -#content form h3 { - margin-left: 110px; - margin-bottom: 2px; - font-size: 16px; - font-weight: normal; - color: #00AF00; -} - -#content h4 a { - font-size: 18px; -} - -#content form .settings-column { - float: left; - padding-bottom: 16px; -} - -#content #test-mode-buttons button { - width: 49.8%; -} - -#content #test-mode-buttons .left-floated { - float: left; -} - -#content #test-mode-buttons .right-floated { - float: right; +#content .site-title { + color: var(--color-font3); } diff --git a/OpenBench/templatetags/mytags.py b/OpenBench/templatetags/mytags.py index cf059c5..4bf1595 100644 --- a/OpenBench/templatetags/mytags.py +++ b/OpenBench/templatetags/mytags.py @@ -19,7 +19,7 @@ # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # import re, django -import OpenBench.utils, OpenBench.stats, OpenBench.models +import OpenBench.config, OpenBench.utils, OpenBench.stats, OpenBench.models def oneDigitPrecision(value): @@ -51,15 +51,21 @@ def gitDiffLink(test): base = test['base']['source'] devsha = test['dev']['sha'] basesha = test['base']['sha'] + engine = test['dev_engine'] else: dev = test.dev.source base = test.base.source devsha = test.dev.sha basesha = test.base.sha + engine = test.dev_engine - repo = OpenBench.utils.pathjoin(*dev.split('/')[:-2]) - return OpenBench.utils.pathjoin(repo, 'compare', + if OpenBench.config.OPENBENCH_CONFIG['engines'][engine]['private']: + repo = OpenBench.config.OPENBENCH_CONFIG['engines'][engine]['source'] + else: + repo = OpenBench.utils.path_join(*dev.split('/')[:-2]) + + return OpenBench.utils.path_join(repo, 'compare', '{0}...{1}'.format(basesha[:8], devsha[:8])) def shortStatBlock(test): @@ -90,9 +96,8 @@ def shortStatBlock(test): def longStatBlock(test): - tokens = test.devoptions.split(' ') - threads = tokens[0].split('=')[1] - hash = tokens[1].split('=')[1] + threads = OpenBench.utils.extract_option(test.dev_options, 'Threads') + hash = OpenBench.utils.extract_option(test.dev_options, 'Hash') lower, elo, upper = OpenBench.stats.ELO(test.wins, test.losses, test.draws) error = max(upper - elo, elo - lower) @@ -102,21 +107,24 @@ def longStatBlock(test): if test.test_mode == 'SPRT': - lowerllr = twoDigitPrecision(test.lowerllr) - currentllr = twoDigitPrecision(test.currentllr) - upperllr = twoDigitPrecision(test.upperllr) - elolower = twoDigitPrecision(test.elolower) - eloupper = twoDigitPrecision(test.eloupper) + lowerllr = twoDigitPrecision(test.lowerllr) + currentllr = twoDigitPrecision(test.currentllr) + upperllr = twoDigitPrecision(test.upperllr) + elolower = twoDigitPrecision(test.elolower) + eloupper = twoDigitPrecision(test.eloupper) + timecontrol = test.dev_time_control + ['s', '']['=' in test.dev_time_control] return 'ELO | {0} +- {1} (95%)\n'.format(elo, error) \ - + 'SPRT | {0}s Threads={1} Hash={2}MB\n'.format(test.timecontrol, threads, hash) \ + + 'SPRT | {0} Threads={1} Hash={2}MB\n'.format(timecontrol, threads, hash) \ + 'LLR | {0} ({1}, {2}) [{3}, {4}]\n'.format(currentllr, lowerllr, upperllr, elolower, eloupper) \ + 'GAMES | N: {0} W: {1} L: {2} D: {3}'.format(test.games, test.wins, test.losses, test.draws) if test.test_mode == 'GAMES': + timecontrol = test.dev_time_control + ['s', '']['=' in test.dev_time_control] + return 'ELO | {0} +- {1} (95%)\n'.format(elo, error) \ - + 'CONF | {0}s Threads={1} Hash={2}MB\n'.format(test.timecontrol, threads, hash) \ + + 'CONF | {0} Threads={1} Hash={2}MB\n'.format(timecontrol, threads, hash) \ + 'GAMES | N: {0} W: {1} L: {2} D: {3}'.format(test.games, test.wins, test.losses, test.draws) def testResultColour(test): @@ -140,13 +148,26 @@ def prettyName(name): return name def prettyDevName(test): - if test.dev.name == test.base.name and test.devnetname != '': - try: return OpenBench.models.Network.objects.get(sha256=test.devnetwork).name - except: return test.devnetname # File has since been deleted ? + + # If engines are different, use the base name + branch + if test.dev_engine != test.base_engine: + return '[%s] %s' % (test.base_engine, test.base.name) + + # If testing different Networks, possibly use the Network name + if test.dev.name == test.base.name and test.dev_netname != '': + + # Nets match as well, so revert back to the branch name + if test.dev_network == test.base_network: + return prettyName(test.dev.name) + + # Use the network's name, if we still have it saved + try: return OpenBench.models.Network.objects.get(sha256=test.dev_network).name + except: return test.dev_netname # File has since been deleted ? + return prettyName(test.dev.name) def testIsFRC(test): - return "FRC" in test.bookname.upper() or "960" in test.bookname.upper() + return "FRC" in test.book_name.upper() or "960" in test.book_name.upper() def resolveNetworkURL(sha256): if OpenBench.models.Network.objects.filter(sha256=sha256): @@ -157,7 +178,40 @@ def testIdToPrettyName(test_id): return prettyName(OpenBench.models.Test.objects.get(id=test_id).dev.name) def testIdToTimeControl(test_id): - return OpenBench.models.Test.objects.get(id=test_id).timecontrol + return OpenBench.models.Test.objects.get(id=test_id).dev_time_control + +def cpuflagsBlock(machine, N=8): + + reported = [] + flags = machine.info['cpu_flags'] + + general_flags = ['BMI2', 'POPCNT'] + broad_avx_flags = ['AVX2', 'AVX', 'SSE4_2', 'SSE4_1', 'SSSE3'] + + for flag in general_flags: + if flag in flags: + reported.append(flag) + break + + for flag in broad_avx_flags: + if flag in flags: + reported.append(flag) + break + + for flag in flags: + if flag not in general_flags and flag not in broad_avx_flags: + reported.append(flag) + + return ' '.join(reported) + +def compilerBlock(machine): + string = '' + for engine, info in machine.info['compilers'].items(): + string += '%-16s %-8s (%s)\n' % (engine, info[0], info[1]) + return string + +def removePrefix(value, prefix): + return value.removeprefix(prefix) register = django.template.Library() register.filter('oneDigitPrecision', oneDigitPrecision) @@ -174,3 +228,6 @@ register.filter('testIsFRC', testIsFRC) register.filter('resolveNetworkURL', resolveNetworkURL) register.filter('testIdToPrettyName', testIdToPrettyName) register.filter('testIdToTimeControl', testIdToTimeControl) +register.filter('cpuflagsBlock', cpuflagsBlock) +register.filter('compilerBlock', compilerBlock) +register.filter('removePrefix', removePrefix) diff --git a/OpenBench/urls.py b/OpenBench/urls.py index 50dc759..d6b42e7 100644 --- a/OpenBench/urls.py +++ b/OpenBench/urls.py @@ -22,27 +22,31 @@ import django.urls, OpenBench.views urlpatterns = [ - # Links for account managment + # Links for account management django.urls.path(r'register/', OpenBench.views.register), django.urls.path(r'login/', OpenBench.views.login), django.urls.path(r'logout/', OpenBench.views.logout), django.urls.path(r'profile/', OpenBench.views.profile), + django.urls.path(r'profileConfig/', OpenBench.views.profile_config), # Links for viewing test tables django.urls.path(r'index/', OpenBench.views.index), django.urls.path(r'index//', OpenBench.views.index), + django.urls.path(r'user//', OpenBench.views.user), + django.urls.path(r'user///', OpenBench.views.user), django.urls.path(r'greens/', OpenBench.views.greens), django.urls.path(r'greens//', OpenBench.views.greens), django.urls.path(r'search/', OpenBench.views.search), - django.urls.path(r'user//', OpenBench.views.user), - django.urls.path(r'user///', OpenBench.views.user), - django.urls.path(r'event//', OpenBench.views.event), # Links for viewing general information tables django.urls.path(r'users/', OpenBench.views.users), - django.urls.path(r'events/', OpenBench.views.events), - django.urls.path(r'events//', OpenBench.views.events), + django.urls.path(r'event//', OpenBench.views.event), + django.urls.path(r'events/', OpenBench.views.events_actions), + django.urls.path(r'events//', OpenBench.views.events_actions), + django.urls.path(r'errors/', OpenBench.views.events_errors), + django.urls.path(r'errors//', OpenBench.views.events_errors), django.urls.path(r'machines/', OpenBench.views.machines), + django.urls.path(r'machines//', OpenBench.views.machines), # Links for viewing and managing tests (maintain Legacy) django.urls.path(r'test//', OpenBench.views.test), @@ -52,25 +56,27 @@ 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), + django.urls.path(r'networks///', OpenBench.views.networks), # Links for interacting with OpenBench via scripting 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'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'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), - # Link for Ethereal 13.00 PRO Sales + # Link for Ethereal Sales django.urls.path(r'Ethereal/', OpenBench.views.buyEthereal), ] diff --git a/OpenBench/utils.py b/OpenBench/utils.py index befec4a..7a5b986 100644 --- a/OpenBench/utils.py +++ b/OpenBench/utils.py @@ -32,10 +32,10 @@ from OpenBench.config import * from OpenBench.models import Engine, Profile, Machine, Result, Test, Network -def pathjoin(*args): - return "/".join([f.lstrip("/").rstrip("/") for f in args]) + "/" +def path_join(*args): + return "/".join([f.lstrip("/").rstrip("/") for f in args]).rstrip('/') -def extractOption(options, option): +def extract_option(options, option): match = re.search('(?<={0}=")[^"]*'.format(option), options) if match: return match.group() @@ -46,7 +46,7 @@ def extractOption(options, option): match = re.search('(?<={0}=)[^ ]*'.format(option), options) if match: return match.group() -def parseTimeControl(time_control): +def parse_time_control(time_control): # Display Nodes as N=, Depth as D=, MoveTime as MT= conversion = { @@ -77,22 +77,29 @@ def parseTimeControl(time_control): raise Exception('Unable to parse Time Control (%s)' % (time_control)) -def getPendingTests(): - pending = OpenBench.models.Test.objects.filter(approved=False) - pending = pending.exclude(finished=True) - pending = pending.exclude(deleted=True) - return pending.order_by('-creation') +def get_pending_tests(): + t = OpenBench.models.Test.objects.filter(approved=False) + t = t.exclude(finished=True) + t = t.exclude(deleted=True) + return t.order_by('-creation') -def getActiveTests(): - active = OpenBench.models.Test.objects.filter(approved=True) - active = active.exclude(finished=True) - active = active.exclude(deleted=True) - return active.order_by('-priority', '-currentllr') +def get_active_tests(): + t = OpenBench.models.Test.objects.filter(approved=True) + t = t.exclude(awaiting=True) + t = t.exclude(finished=True) + t = t.exclude(deleted=True) + return t.order_by('-priority', '-currentllr') -def getCompletedTests(): - completed = OpenBench.models.Test.objects.filter(finished=True) - completed = completed.exclude(deleted=True) - return completed.order_by('-updated') +def get_completed_tests(): + t = OpenBench.models.Test.objects.filter(finished=True) + t = t.exclude(deleted=True) + return t.order_by('-updated') + +def get_awaiting_tests(): + t = OpenBench.models.Test.objects.filter(awaiting=True) + t = t.exclude(finished=True) + t = t.exclude(deleted=True) + return t.order_by('-creation') def getRecentMachines(minutes=5): @@ -109,8 +116,38 @@ def getMachineStatus(username=None): machines = machines.filter(user__username=username) return ": {0} Machines / ".format(len(machines)) + \ - "{0} Threads / ".format(sum([f.threads for f in machines])) + \ - "{0} MNPS ".format(round(sum([f.threads * f.mnps for f in machines]), 2)) + "{0} Threads / ".format(sum([f.info['concurrency'] for f in machines])) + \ + "{0} MNPS ".format(round(sum([f.info['concurrency'] * f.mnps for f in machines]), 2)) + +def get_test_context(test): + + # Select the Test, and all Result objects attached + results = Result.objects.filter(test=test).order_by('machine_id') + data = { 'test' : test, 'results': {} } + + for result in results: + + # Insert the Result into the results + if result.machine.id not in data['results'].keys(): + data['results'][result.machine.id] = { + 'games' : 0, 'wins' : 0, 'losses' : 0, + 'draws' : 0, 'timeloss' : 0, 'crashes' : 0, + } + + # Always use the latest Time stamp, by virtue of sorting Results + data['results'][result.machine.id]['machine_id'] = result.machine.id + data['results'][result.machine.id]['username' ] = result.machine.user.username + data['results'][result.machine.id]['updated' ] = result.updated + + # Sum up all results from a given machine into a single value + data['results'][result.machine.id]['games' ] += result.games + data['results'][result.machine.id]['wins' ] += result.wins + data['results'][result.machine.id]['losses' ] += result.losses + data['results'][result.machine.id]['draws' ] += result.draws + data['results'][result.machine.id]['timeloss' ] += result.timeloss + data['results'][result.machine.id]['crashes' ] += result.crashes + + return data def getPaging(content, page, url, pagelen=25): @@ -148,144 +185,312 @@ def getEngine(source, name, sha, 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): - branch = request.POST['{0}branch'.format(name)] +def read_git_credentials(engine): + fname = 'credentials.%s' % (engine.replace(' ', '').lower()) + if os.path.exists(fname): + with open(fname) as fin: + return { 'Authorization' : 'token %s' % fin.readlines()[0].rstrip() } + +def requests_illegal_fork(request, field): + + # Strip trailing '/'s for sanity + engine = OPENBENCH_CONFIG['engines'][request.POST['%s_engine' % (field)]] + eng_src = engine['source'].rstrip('/') + tar_src = request.POST['%s_repo' % (field)].rstrip('/') + + # Illegal if sources do not match for Private engines + return engine['private'] and eng_src != tar_src + +def determine_bench(request, field, message): + + # Use the provided bench if possible + try: return int(request.POST['{0}_bench'.format(field)]) + except: pass + + # Fallback to try to parse the Bench from the commit + try: + benches = re.findall('(?:BENCH|NODES)[ :=]+([0-9,]+)', message, re.IGNORECASE) + return int(benches[-1].replace(',', '')) + except: return None + +def collect_github_info(request, errors, field): + + # Get branch name, whether it is a commit SHA, and the API path for it + branch = request.POST['{0}_branch'.format(field)] bysha = bool(re.search('[0-9a-fA-F]{40}', branch)) url = 'commits' if bysha else 'branches' - repo = request.POST['source'] - target = repo.replace('github.com', 'api.github.com/repos') - target = pathjoin(target, url, branch).rstrip('/') + # All API requests will share this common path. Some engines are private. + base = request.POST['%s_repo' % (field)].replace('github.com', 'api.github.com/repos') + engine = request.POST['%s_engine' % (field)] + private = OPENBENCH_CONFIG['engines'][engine]['private'] + headers = {} - # Avoid leaking our credentials to other sites - if not target.startswith('https://api.github.com/'): + ## Step 1: Verify the target of the API requests + ## [A] We will not attempt to reach any site other than api.github.com + ## [B] Private engines may only use their main repo for sources of tests + ## [C] Determine which, if any, credentials we want to pass along + + # Private engines must have a token stored in credentials.enginename + if private and not (headers := read_git_credentials(engine)): + errors.append('Server does not have access tokens for this engine') + return (None, None) + + # Do not allow private engines to use forked repos ( We don't have a token! ) + if requests_illegal_fork(request, field): + errors.append('Forked Repositories are not allowed for Private engines') + return (None, None) + + # Avoid leaking our credentials to other websites + if not base.startswith('https://api.github.com/'): errors.append('OpenBench may only reach Github\'s API') - return (None, None, None, None) + return (None, None) - # Check for a (User, Token) credentials file - if os.path.exists('credentials'): - with open('credentials') as fin: - user, token = fin.readlines()[0].rstrip().split() - auth = requests.auth.HTTPBasicAuth(user, token) - else: auth = None + ## Step 2: Connect to the Github API for the given Branch or Commit SHA. + ## [A] We will attempt to parse the most recent commit message for a + ## bench, unless one was supplied. + ## [B] We will translate any branch name into a commit SHA for later use, + ## so we may compare branches and generate diff URLs + ## [C] If the engine is public, we will construct the URL to download the + ## source code from Github into a .zip file. + ## [D] If the engine is private, we will carry onto Step 3. try: # Fetch data from the Github API - data = requests.get(target, auth=auth).json() + path = 'commits' if bysha else 'branches' + url = path_join(base, path, branch) + data = requests.get(url, headers=headers).json() data = data if bysha else data['commit'] except: # Unable to connect for whatever reason - lookup = 'Commit Sha' if bysha else 'Branch' - errors.append('{0} {1} could not be found'.format(lookup, branch)) - return (None, None, None, None) + path = 'Commit Sha' if bysha else 'Branch' + errors.append('{0} {1} could not be found'.format(path, branch)) + return (None, None) - treeurl = data['commit']['tree']['sha'] + '.zip' - source = pathjoin(repo, 'archive', treeurl).rstrip('/') + # Extract the bench from the web form, or from the commit message + if not (bench := determine_bench(request, field, data['commit']['message'])): + errors.append('Unable to parse a Bench for %s' % (branch)) + return (None, None) - try: # Use the provided Bench if there is one - bench = int(request.POST['{0}bench'.format(name)]) - return (source, branch, data['sha'], bench) - except: pass + # Public Engines: Construct the .zip download and return everything + if not OPENBENCH_CONFIG['engines'][engine]['private']: + treeurl = data['commit']['tree']['sha'] + '.zip' + source = path_join(request.POST['%s_repo' % (field)], 'archive', treeurl) + return (source, branch, data['sha'], bench), True - try: # Fallback to try to parse the Bench from the commit - message = data['commit']['message'] - benches = re.findall('(?:BENCH|NODES)[ :=]+([0-9,]+)', message, re.IGNORECASE) - bench = int(benches[-1].replace(',', '')) - return (source, branch, data['sha'], bench) + ## Step 3: Construct the URL for the API request to list all Artifacts + ## [A] OpenBench artifacts are always run via a file named openbench.yml + ## [B] These should contain combinations for windows/linux, avx2/avx512, popcnt/pext + ## [C] If those artifacts are not found, we flag the test as awaiting, and try later. - except: # Neither method found a viable Bench - errors.append('Unable to parse a Bench for {0}'.format(branch)) - return (None, None, None, None) + url, has_all = fetch_artifact_url(base, engine, headers, data['sha']) + return (url, branch, data['sha'], bench), has_all -def verifyNewTest(request): +def fetch_artifact_url(base, engine, headers, sha): + + try: + # Fetch the run id for the openbench workflow for this comment + url = path_join(base, 'actions', 'workflows', 'openbench.yml', 'runs') + url += '?head_sha=%s' % (sha) + run_id = requests.get(url=url, headers=headers).json()['workflow_runs'][0]['id'] + + # Construct the final URL that will be used to look at artifacts + url = path_join(base, 'actions', 'runs', str(run_id), 'artifacts') + artifacts = requests.get(url=url, headers=headers).json()['artifacts'] + + # Verify that all of the artifacts exist and are not expired + available = [ f['name'] for f in artifacts if f['expired'] == False ] + required = OPENBENCH_CONFIG['engines'][engine]['build']['artifacts'] + has_all = all(['%s-%s' % (sha, name) in available for name in required]) + + # Return the URL iff we found them; otherwise base + return (url if has_all else base, has_all) + + except Exception as error: + # If anything goes wrong, retry later with the same base URL + return (base, False) + +def verify_test_creation(request): errors = [] - def verifyInteger(field, fieldName): + def verify_integer(field, field_name): try: int(request.POST[field]) - except: errors.append('{0} is not an Integer'.format(fieldName)) + except: errors.append('"{0}" is not an Integer'.format(field_name)) - def verifyGreaterThan(field, fieldName, value, valueName): - if not float(request.POST[field]) > value: - errors.append('{0} is not greater than {1}'.format(fieldName, valueName)) + def verify_greater_than(field, field_name, value): + try: assert int(request.POST[field]) > value + except: errors.append('"{0}" is not greater than {1}'.format(field_name, value)) - def verifyOptions(field, option, fieldName): - if extractOption(request.POST[field], option) == None: - errors.append('{0} was not found as an option for {1}'.format(option, fieldName)) - elif int(extractOption(request.POST[field], option)) < 1: - errors.append('{0} needs to be at least 1 for {1}'.format(option, fieldName)) + def verify_options(field, option, field_name): + try: assert int(extract_option(request.POST[field], option)) >= 1 + except: errors.append('"{0}" needs to be at least 1 for {1}'.format(option, field_name)) - def verifyConfiguration(field, fieldName, parent): - if request.POST[field] not in OpenBench.config.OPENBENCH_CONFIG[parent].keys(): - errors.append('{0} was not found in the configuration'.format(fieldName)) + def verify_configuration(field, field_name, parent): + try: assert request.POST[field] in OpenBench.config.OPENBENCH_CONFIG[parent].keys() + except: errors.append('{0} was not found in the configuration'.format(field_name)) - def verifyTimeControl(field, fieldName): - try: parseTimeControl(request.POST[field]) - except: errors.append('{0} is not a parsable {1}'.format(request.POST[field], fieldName)) + def verify_time_control(field, field_name): + try: parse_time_control(request.POST[field]) + except: errors.append('{0} is not a parsable'.format(field_name)) + + def verify_win_adj(field): + try: + if (content := request.POST[field]) == 'None': return + assert re.match('movecount=[0-9]+ score=[0-9]+', content) + except: errors.append('Invalid Win Adjudication Setting. Try "None"?') + + def verify_draw_adj(field): + try: + if (content := request.POST[field]) == 'None': return + assert re.match('movenumber=[0-9]+ movecount=[0-9]+ score=[0-9]+', content) + except: errors.append('Invalid Draw Adjudication Setting. Try "None"?') + + def verify_github_repo(field): + try: assert request.POST[field].startswith('https://github.com/') + except: errors.append('Sources must be found on https://github.com/') + + def verify_network(field, fieldName): + try: + if request.POST[field] == '': return + Network.objects.get(sha256=request.POST[field]) + except: errors.append('Unknown Network Provided for {0}'.format(fieldName)) + + def verify_test_mode(field): + try: assert request.POST[field] in ['SPRT', 'GAMES'] + except: errors.append('Unknown Test Mode') + + def verify_sprt_bounds(field): + try: + if request.POST['test_mode'] != 'SPRT': return + pattern = r'^\[(-?\d+(?:\.\d+)?), (-?\d+(?:\.\d+)?)\]$' + match = re.match(pattern, request.POST['test_bounds']) + assert float(match.group(1)) < float(match.group(2)) + except: errors.append('SPRT Bounds must be formatted as [float1, float2]') + + def verify_sprt_conf(field): + try: + if request.POST['test_mode'] != 'SPRT': return + pattern = r'^\[(-?\d+(?:\.\d+)?), (-?\d+(?:\.\d+)?)\]$' + match = re.match(pattern, request.POST['test_confidence']) + assert 0.00 < float(match.group(1)) < 1.00 + assert 0.00 < float(match.group(2)) < 1.00 + except: errors.append('Confidence Bounds must be formatted as [float1, float2], within (0.00, 1.00)') + + def verify_max_games(field): + try: + if request.POST['test_mode'] != 'GAMES': return + assert int(request.POST['test_max_games']) > 0 + except: errors.append('Fixed Games Tests must last at least one game') + + def verify_syzygy_field(field, field_name): + try: assert request.POST[field] in ['OPTIONAL', 'REQUIRED', 'DISABLED'] + except: errors.append('{0} must be OPTIONAL, REQUIRED, or DISABLED'.format(field_name)) verifications = [ - (verifyInteger, 'priority', 'Priority'), - (verifyInteger, 'throughput', 'Throughput'), - (verifyGreaterThan, 'throughput', 'Throughput', 0, '0'), - (verifyOptions, 'devoptions', 'Threads', 'Dev Options'), - (verifyOptions, 'devoptions', 'Hash', 'Dev Options'), - (verifyOptions, 'baseoptions', 'Threads', 'Base Options'), - (verifyOptions, 'baseoptions', 'Hash', 'Base Options'), - (verifyConfiguration, 'enginename', 'Engine', 'engines'), - (verifyConfiguration, 'bookname', 'Book', 'books'), - (verifyTimeControl, 'timecontrol', 'Time Control'), + + # Verify everything about the Dev Engine + (verify_configuration, 'dev_engine', 'Dev Engine', 'engines'), + (verify_github_repo , 'dev_repo'), + (verify_network , 'dev_network', 'Dev Network'), + (verify_options , 'dev_options', 'Threads', 'Dev Options'), + (verify_options , 'dev_options', 'Hash', 'Dev Options'), + (verify_time_control , 'dev_time_control', 'Dev Time Control'), + + # Verify everything about the Base Engine + (verify_configuration, 'base_engine', 'Base Engine', 'engines'), + (verify_github_repo , 'base_repo'), + (verify_network , 'base_network', 'Base Network'), + (verify_options , 'base_options', 'Threads', 'Base Options'), + (verify_options , 'base_options', 'Hash', 'Base Options'), + (verify_time_control , 'base_time_control', 'Base Time Control'), + + # Verify everything about the Test Settings + (verify_configuration, 'book_name', 'Book', 'books'), + (verify_test_mode , 'test_mode'), + (verify_sprt_bounds , 'test_bounds'), + (verify_sprt_conf , 'test_confidence'), + (verify_max_games , 'test_max_games'), + + # Verify everything about the General Settings + (verify_integer , 'priority', 'Priority'), + (verify_greater_than , 'throughput', 'Throughput', 0), + (verify_syzygy_field , 'syzygy_wdl', 'Syzygy WDL'), + + # Verify everything about the Workload Settings + (verify_greater_than , 'report_rate', 'Report Rate', 0), + (verify_greater_than , 'workload_size', 'Workload Size', 0), + + # Verify everything about the Adjudicaton Settings + (verify_syzygy_field , 'syzygy_adj', 'Syzygy Adjudication'), + (verify_win_adj , 'win_adj'), + (verify_draw_adj , 'draw_adj'), ] for verification in verifications: - try: verification[0](*verification[1:]) - except: pass + verification[0](*verification[1:]) return errors -def createNewTest(request): +def create_new_test(request): - errors = []; verifyNewTest(request) + # Verify all of the fields in the request + if (errors := verify_test_creation(request)): + return None, errors + + # Collect Github meta information (Shas, Sources, Benches) + devinfo, dev_has_all = collect_github_info(request, errors, 'dev') + baseinfo, base_has_all = collect_github_info(request, errors, 'base') if errors != []: return None, errors - devinfo = getBranch(request, errors, 'dev') - baseinfo = getBranch(request, errors, 'base') - if errors != []: return None, errors + test = Test() + test.author = request.user.username + test.book_name = request.POST['book_name'] - test = Test() - test.author = request.user.username - test.engine = request.POST['enginename'] - test.test_mode = request.POST['test_mode'] - test.source = request.POST['source'] - test.devoptions = request.POST['devoptions'].rstrip(' ') - test.baseoptions = request.POST['baseoptions'].rstrip(' ') - test.devnetwork = request.POST['devnetwork'] - test.basenetwork = request.POST['basenetwork'] - test.bookname = request.POST['bookname'] - test.timecontrol = parseTimeControl(request.POST['timecontrol']) - test.priority = int(request.POST['priority']) - test.throughput = int(request.POST['throughput']) - test.syzygy_adj = request.POST['syzygy_adj'] - test.syzygy_wdl = request.POST['syzygy_wdl'] + test.dev = getEngine(*devinfo) + test.dev_repo = request.POST['dev_repo'] + test.dev_engine = request.POST['dev_engine'] + test.dev_options = request.POST['dev_options'] + test.dev_network = request.POST['dev_network'] + test.dev_time_control = parse_time_control(request.POST['dev_time_control']) - if request.POST['test_mode'] == 'SPRT': - test.elolower = float(request.POST['bounds'].split(',')[0].lstrip('[')) - test.eloupper = float(request.POST['bounds'].split(',')[1].rstrip(']')) - test.alpha = float(request.POST['confidence'].split(',')[1].rstrip(']')) - test.beta = float(request.POST['confidence'].split(',')[0].lstrip('[')) + test.base = getEngine(*baseinfo) + test.base_repo = request.POST['base_repo'] + test.base_engine = request.POST['base_engine'] + test.base_options = request.POST['base_options'] + test.base_network = request.POST['base_network'] + test.base_time_control = parse_time_control(request.POST['base_time_control']) + + test.report_rate = int(request.POST['report_rate']) + test.workload_size = int(request.POST['workload_size']) + test.priority = int(request.POST['priority']) + test.throughput = int(request.POST['throughput']) + + test.syzygy_wdl = request.POST['syzygy_wdl'] + test.syzygy_adj = request.POST['syzygy_adj'] + test.win_adj = request.POST['win_adj'] + test.draw_adj = request.POST['draw_adj'] + + test.test_mode = request.POST['test_mode'] + test.awaiting = not (dev_has_all and base_has_all) + + if test.test_mode == 'SPRT': + test.elolower = float(request.POST['test_bounds'].split(',')[0].lstrip('[')) + test.eloupper = float(request.POST['test_bounds'].split(',')[1].rstrip(']')) + test.alpha = float(request.POST['test_confidence'].split(',')[1].rstrip(']')) + test.beta = float(request.POST['test_confidence'].split(',')[0].lstrip('[')) test.lowerllr = math.log(test.beta / (1.0 - test.alpha)) test.upperllr = math.log((1.0 - test.beta) / test.alpha) - if request.POST['test_mode'] == 'GAMES': - test.max_games = int(request.POST['max_games']) + if test.test_mode == 'GAMES': + test.max_games = int(request.POST['test_max_games']) - if request.POST['devnetwork']: - test.devnetname = Network.objects.get(sha256=request.POST['devnetwork']).name + if test.dev_network: + test.dev_netname = Network.objects.get(sha256=test.dev_network ).name - if request.POST['basenetwork']: - test.basenetname = Network.objects.get(sha256=request.POST['basenetwork']).name + if test.base_network: + test.base_netname = Network.objects.get(sha256=test.base_network).name - test.dev = getEngine(*devinfo) - test.base = getEngine(*baseinfo) test.save() profile = Profile.objects.get(user=request.user) @@ -295,189 +500,176 @@ def createNewTest(request): return test, None -def getMachine(machineid, user, osname, threads): +def get_machine(machineid, user, info): - # Create a new Machine if needed + # Create a new machine if we don't have an id if machineid == 'None': - return Machine(user=user, osname=osname, threads=threads) + return Machine(user=user, info=info) - # Fetch and verify the requested Machine + # Fetch the requested machine, which hopefully exists 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' + except: return None + + # Workload requests should always contain a MAC + if 'mac_address' not in machine.info: + return None + + # Soft-verify by checking if the MAC addresses match + if machine.info['mac_address'] != info['mac_address']: + return None - # 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 - machine.workload = test; machine.save(); result.save() - return str(workload_to_dictionary(test, result, machine)) + # Update the Machine's status and save everything + machine.workload = test.id; machine.save(); result.save() + 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 finished tests - tests = Test.objects.filter(finished=False) - tests = tests.filter(deleted=False).filter(approved=True) + # 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(): - 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) + if engine not in machine.info['supported']: + tests = tests.exclude(dev_engine=engine) + tests = tests.exclude(base_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 - options = [x for x in tests if test_maps_onto_thread_count(machine, x)] + 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): +def test_maps_onto_thread_count(test, threads, ncutechess, hyperthreads): - # Only assign a workload to a machine if the machine actually has - # enough Threads for the test. Furthermore, ensure that there are - # no left over threads when assigned. An exception is made for the - # case where thread counts differ -- a bad idea to run in general + dev_threads = int(extract_option(test.dev_options, 'Threads')) + base_threads = int(extract_option(test.base_options, 'Threads')) - 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) > (threads / ncutechess): + return False - if max(dev_threads, base_threads) > machine.threads: return False - return dev_threads != base_threads or machine.threads % 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): # Determine how many threads are assigned to each workload - table = { test : 0 for test in tests } + table = { test.id : { 'cores' : 0, 'throughput' : test.throughput } for test in tests } for m in getRecentMachines(): - if m.workload in tests and m != machine: - table[m.workload] = table[m.workload] + m.threads + if m.workload in table and m != machine: + table[m.workload]['cores'] += m.info['concurrency'] # Find the tests most deserving of resources currently - ratios = [table[test] / test.throughput for test in tests] + ratios = [table[x]['cores'] / table[x]['throughput'] for x in table] lowest_idxs = [i for i, r in enumerate(ratios) if r == min(ratios)] # Machine is out of date; or there is an unassigned test - if machine.workload not in tests or min(ratios) == 0: + if machine.workload not in table or min(ratios) == 0: return tests[random.choice(lowest_idxs)] # No test has less than (1-variance)% of its deserved resources, and # therefore we may have this machine repeat its existing workload again - ideal_ratio = sum(table.values()) / sum([x.throughput for x in tests]) + ideal_ratio = sum([x['cores'] for x in table.values()]) / sum([x['throughput'] for x in table.values()]) if min(ratios) / ideal_ratio > 1 - variance: - return machine.workload + return OpenBench.models.Test.objects.get(id=machine.workload) # 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({ + 'result' : { + 'id' : result.id + }, - 'machine' : { 'id' : machine.id }, + 'test' : { + 'id' : test.id, + '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, + 'book' : OPENBENCH_CONFIG['books'][test.book_name], - 'result' : { 'id' : result.id }, - - 'test' : { - - 'throughput' : 1000, # HACK: Updated Client's no longer need this value - - 'id' : test.id, - 'engine' : test.engine, - 'timecontrol' : test.timecontrol, - 'syzygy_adj' : test.syzygy_adj, - 'syzygy_wdl' : test.syzygy_wdl, - - 'nps' : OPENBENCH_CONFIG['engines'][test.engine]['nps'], - 'build' : OPENBENCH_CONFIG['engines'][test.engine]['build'], - 'book' : OPENBENCH_CONFIG['books'][test.bookname], - - 'dev' : { - 'id' : test.dev.id, 'name' : test.dev.name, - 'source' : test.dev.source, 'sha' : test.dev.sha, - 'bench' : test.dev.bench, 'options' : test.devoptions, - 'network' : test.devnetwork, + 'dev' : { + 'id' : test.dev.id, + 'name' : test.dev.name, + 'source' : test.dev.source, + 'sha' : test.dev.sha, + 'bench' : test.dev.bench, + 'engine' : test.dev_engine, + 'options' : test.dev_options, + 'network' : test.dev_network, + 'time_control' : test.dev_time_control, + 'nps' : OPENBENCH_CONFIG['engines'][test.dev_engine]['nps'], + 'build' : OPENBENCH_CONFIG['engines'][test.dev_engine]['build'], }, - 'base' : { - 'id' : test.base.id, 'name' : test.base.name, - 'source' : test.base.source, 'sha' : test.base.sha, - 'bench' : test.base.bench, 'options' : test.baseoptions, - 'network' : test.basenetwork, + 'base' : { + 'id' : test.base.id, + 'name' : test.base.name, + 'source' : test.base.source, + 'sha' : test.base.sha, + 'bench' : test.base.bench, + 'engine' : test.base_engine, + 'options' : test.base_options, + 'network' : test.base_network, + 'time_control' : test.base_time_control, + 'nps' : OPENBENCH_CONFIG['engines'][test.base_engine]['nps'], + 'build' : OPENBENCH_CONFIG['engines'][test.base_engine]['build'], }, }, - }) + } -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 @@ -505,11 +697,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( @@ -528,4 +720,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 c558b24..28d1285 100644 --- a/OpenBench/views.py +++ b/OpenBench/views.py @@ -18,7 +18,7 @@ # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # -import os, hashlib, mimetypes, datetime, json, random +import os, hashlib, datetime, json, secrets, re import django.http import django.shortcuts @@ -27,18 +27,18 @@ import django.contrib.auth import OpenBench.config import OpenBench.utils +from OpenBench.config import OPENBENCH_CONFIG + 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 +from django.http import HttpResponse, FileResponse, JsonResponse from django.views.decorators.csrf import csrf_exempt from django.core.files.storage import FileSystemStorage from django.core.files.base import ContentFile -from htmlmin.decorators import not_minified_response # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # GENERAL UTILITIES # @@ -47,10 +47,14 @@ from htmlmin.decorators import not_minified_response class UnableToAuthenticate(Exception): pass -def render(request, template, content={}): +def render(request, template, content={}, always_allow=False): data = content.copy() - data.update({'config' : OpenBench.config.OPENBENCH_CONFIG}) + data.update({ 'config' : OPENBENCH_CONFIG }) + + if OpenBench.config.REQUIRE_LOGIN_TO_VIEW: + if not request.user.is_authenticated and not always_allow: + return redirect(request, '/login/', error=data['config']['error']['requires_login']) if request.user.is_authenticated: @@ -58,12 +62,27 @@ def render(request, template, content={}): data.update({'profile' : profile.first()}) if profile.first() and not profile.first().enabled: - data.update({'error' : data['config']['error']['disabled']}) + request.session['error_message'] = data['config']['error']['disabled'] - if request.user.is_authenticated and not profile.first(): - data.update({'error' : data['config']['error']['fakeuser']}) + elif request.user.is_authenticated and not profile.first(): + request.session['error_message'] = data['config']['error']['fakeuser'] - return django.shortcuts.render(request, 'OpenBench/{0}'.format(template), data) + response = django.shortcuts.render(request, 'OpenBench/{0}'.format(template), data) + + for key in ['status_message', 'error_message']: + if key in request.session: del request.session[key] + + return response + +def redirect(request, destination, error=None, status=None): + + if error: + request.session['error_message'] = error + + if status: + request.session['status_message'] = status + + return django.http.HttpResponseRedirect(destination) def authenticate(request, requireEnabled=False): @@ -84,55 +103,25 @@ 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 # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # def register(request): - # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # - # # - # GET : Return the HTML template used for registering a new User # - # # - # POST : Enforce matching alpha-numeric passwords, and then attempt to # - # generate a new User and Profile. Return to the homepage after # - # after logging the User in. Share any errors with the viewer # - # # - # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # - if request.method == 'GET': - return render(request, 'register.html') + if not OpenBench.config.REQUIRE_MANUAL_REGISTRATION: + return render(request, 'register.html', always_allow=True) + return redirect(request, '/login/', error=OPENBENCH_CONFIG['error']['manual_registration']) if request.POST['password1'] != request.POST['password2']: - return index(request, error='Passwords Do Not Match') + return redirect(request, '/register/', error='Passwords do not match') if not request.POST['username'].isalnum(): - return index(request, error='Alpha Numeric Usernames Only') + return redirect(request, '/register/', error='Alpha-numeric usernames Only') if User.objects.filter(username=request.POST['username']): - return index(request, error='That Username is taken') + return redirect(request, '/register/', error='That username is already taken') email = request.POST['email'] username = request.POST['username'] @@ -142,134 +131,148 @@ def register(request): django.contrib.auth.login(request, user) Profile.objects.create(user=user) - return django.http.HttpResponseRedirect('/index/') + return redirect(request, '/index/') def login(request): - # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # - # # - # GET : Return the HTML template used for logging in a User # - # # - # 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') + return render(request, 'login.html', always_allow=True) try: - user = authenticate(request) - django.contrib.auth.login(request, user) - return django.http.HttpResponseRedirect('/index/') + django.contrib.auth.login(request, authenticate(request)) + return redirect(request, '/index/') except UnableToAuthenticate: - return index(request, error='Unable to Authenticate User') + return redirect(request, '/login/', error='Unable to authenticate user') def logout(request): - # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # - # # - # GET : Logout the User if they are logged in. Return to the main page # - # # - # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # - django.contrib.auth.logout(request) - return django.http.HttpResponseRedirect('/index/') + return redirect(request, '/index/', status='Logged out') def profile(request): - # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # - # # - # GET : If the User is logged in, return the HTML template which shows # - # all of the information about the User, and a form to change the # - # email address, password, and default engine of the User. If the # - # User is not logged in, return them to the main page # - # # - # POST : Modify the User's email address and selected Engine, if the # - # User has requested this. Update the password for the User if # - # they have requested a change and provided a new set of matching # - # passwords. Return the User to the main page # - # # - # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # - if not request.user.is_authenticated: - return django.http.HttpResponseRedirect('/login/') + return redirect(request, '/login/') + + if not Profile.objects.filter(user=request.user).first(): + return redirect(request, '/index/') if request.method == 'GET': return render(request, 'profile.html') - profile = Profile.objects.filter(user=request.user) - profile.update(engine=request.POST['engine'], repo=request.POST['repo']) - - request.user.email = request.POST['email'] - request.user.save() - - if request.POST['password1'] != request.POST['password2']: - return index(request, error='Passwords Do Not Match') - - if request.POST['password1'] != '': - request.user.set_password(request.POST['password1']) - django.contrib.auth.login(request, request.user) + changes_message = '' + if request.user.email != request.POST['email']: + changes_message += 'Updated email address to %s' % (request.POST['email']) + request.user.email = request.POST['email'] request.user.save() - return django.http.HttpResponseRedirect('/index/') + if request.POST['password1'] != request.POST['password2']: + return redirect(request, '/profile/', status=changes_message, error='Passwords do not match') + if request.POST['password1']: + request.user.set_password(request.POST['password1']) + request.user.save() + django.contrib.auth.login(request, request.user) + changes_message += '\nUpdated password' + + return redirect(request, '/profile/', status=changes_message.removeprefix('\n')) + +def profile_config(request): + + if not request.user.is_authenticated: + return redirect(request, '/login/') + + if not (profile := Profile.objects.filter(user=request.user).first()): + return redirect(request, 'index') + + if request.method == 'GET': + return render(request, 'profile.html') + + changes = '' + + if (engine := request.POST.get('default-status', profile.engine)) != profile.engine: + changes += 'Set %s as the default, replacing %s\n' % (engine, profile.engine) + profile.engine = engine + + for engine in json.loads(request.POST.get('deleted-repos', '[]')): + profile.repos.pop(engine, False) + changes += 'Deleted Engine: %s\n' % (engine) + + if changes: + profile.save() + + engine_name = request.POST.get('new-engine-name', 'None') + engine_repo = request.POST.get('new-engine-repo', '').removesuffix('/') + + if engine_name != 'None' and engine_repo: + + if not engine_repo.startswith('https://github.com/'): + return redirect(request, '/profile/', error='Repositories must be on Github') + + if not profile.engine: + profile.engine = engine_name + + changes += 'Added Engine: %s at %s' % (engine_name, engine_repo) + profile.repos[engine_name] = engine_repo + profile.save() + + return redirect(request, '/profile/', status=changes) # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # TEST LIST VIEWS # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # -def index(request, page=1, error=''): +def index(request, page=1): - # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # - # # - # GET : Return all pending, active, and completed tests. Limit the # - # display of tests by the requested page number. Also display the # - # status for connected machines. # - # # - # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # - - pending = OpenBench.utils.getPendingTests() - active = OpenBench.utils.getActiveTests() - completed = OpenBench.utils.getCompletedTests() + pending = OpenBench.utils.get_pending_tests() + active = OpenBench.utils.get_active_tests() + completed = OpenBench.utils.get_completed_tests() + awaiting = OpenBench.utils.get_awaiting_tests() start, end, paging = OpenBench.utils.getPaging(completed, page, 'index') data = { - 'error' : error, 'pending' : pending, - 'active' : active, 'completed' : completed[start:end], - 'paging' : paging, 'status' : OpenBench.utils.getMachineStatus(), + 'pending' : pending, + 'active' : active, + 'completed' : completed[start:end], + 'awaiting' : awaiting, + 'paging' : paging, + 'status' : OpenBench.utils.getMachineStatus(), + } + + return render(request, 'index.html', data) + +def user(request, username, page=1): + + pending = OpenBench.utils.get_pending_tests().filter(author=username) + active = OpenBench.utils.get_active_tests().filter(author=username) + completed = OpenBench.utils.get_completed_tests().filter(author=username) + awaiting = OpenBench.utils.get_awaiting_tests().filter(author=username) + + start, end, paging = OpenBench.utils.getPaging(completed, page, 'user/%s' % (username)) + + data = { + 'pending' : pending, + 'active' : active, + 'completed' : completed[start:end], + 'awaiting' : awaiting, + 'paging' : paging, + 'status' : OpenBench.utils.getMachineStatus(username), } return render(request, 'index.html', data) def greens(request, page=1): - # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # - # # - # GET : Return all tests both passed and completed. Limit the display # - # of tests by the requested page number. # - # # - # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # - - completed = OpenBench.utils.getCompletedTests().filter(passed=True) + completed = OpenBench.utils.get_completed_tests().filter(passed=True) start, end, paging = OpenBench.utils.getPaging(completed, page, 'greens') - data = {'completed' : completed[start:end], 'paging' : paging} + data = { 'completed' : completed[start:end], 'paging' : paging } return render(request, 'index.html', data) def search(request): - # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # - # # - # GET : Return the HTML template for searching tests on the framework. # - # # - # POST : Filter the tests by the provided criteria, and return a display # - # with the filtered results. Keywords are case insensitive # - # # - # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # - if request.method == 'GET': return render(request, 'search.html', {}) @@ -305,30 +308,14 @@ def search(request): return render(request, 'search.html', {'tests' : filtered}) -def user(request, username, page=1): +# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # +# GENERAL DATA TABLE VIEWS # +# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # - # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # - # # - # GET : Return all pending, active, and completed tests for the User # - # that has been requested. Limit the display of completed tests # - # by the requested page number. Also display the User's machines # - # # - # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # +def users(request): - pending = OpenBench.utils.getPendingTests().filter(author=username) - active = OpenBench.utils.getActiveTests().filter(author=username) - completed = OpenBench.utils.getCompletedTests().filter(author=username) - - url = 'user/{0}'.format(username) - start, end, paging = OpenBench.utils.getPaging(completed, page, url) - - data = { - 'pending' : pending, 'active' : active, - 'completed' : completed[start:end], 'paging' : paging, - 'status' : OpenBench.utils.getMachineStatus(username), - } - - return render(request, 'index.html', data) + data = { 'profiles' : Profile.objects.order_by('-games', '-tests') } + return render(request, 'users.html', data) def event(request, id): @@ -336,51 +323,36 @@ def event(request, id): with open(os.path.join(MEDIA_ROOT, LogEvent.objects.get(id=id).log_file)) as fin: return render(request, 'event.html', { 'content' : fin.read() }) except: - return HttpResponseRedirect('/index/') + return redirect(request, '/index/', error='No logs for event exist') -# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # -# GENERAL DATA TABLE VIEWS # -# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # +def events_actions(request, page=1): -def users(request): - - # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # - # # - # GET : Return information about all users on the Framework. Sort the # - # Users by games completed, tests created. The HTML template will # - # filter out disabled users later. # - # # - # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # - - data = {'profiles' : Profile.objects.order_by('-games', '-tests')} - return render(request, 'users.html', data) - -def events(request, page=1): - - # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # - # # - # GET : Return information about the events taken on the Framework. # - # Only show those events for the requested page. # - # # - # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # - - events = LogEvent.objects.all().order_by('-id') + events = LogEvent.objects.all().filter(machine_id=0).order_by('-id') start, end, paging = OpenBench.utils.getPaging(events, page, 'events') - data = {'events' : events[start:end], 'paging' : paging}; + data = { 'events' : events[start:end], 'paging' : paging }; return render(request, 'events.html', data) -def machines(request): +def events_errors(request, page=1): - # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # - # # - # GET : Return information about all of the machines that have been # - # active on the Framework within the last fifteen minutes # - # # - # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # + events = LogEvent.objects.all().exclude(machine_id=0).order_by('-id') + start, end, paging = OpenBench.utils.getPaging(events, page, 'errors') - data = {'machines' : OpenBench.utils.getRecentMachines()} - return render(request, 'machines.html', data) + data = { 'events' : events[start:end], 'paging' : paging }; + return render(request, 'errors.html', data) + +def machines(request, machineid=None): + + if machineid == None: + data = { 'machines' : OpenBench.utils.getRecentMachines() } + return render(request, 'machines.html', data) + + try: + data = { 'machine' : OpenBench.models.Machine.objects.get(id=machineid) } + return render(request, 'machine.html', data) + + except: + return redirect(request, '/machines/', error='Machine does not exist') # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # @@ -389,44 +361,22 @@ def machines(request): def test(request, id, action=None): - # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # - # # - # GET : The User is either trying to view the status of the selected # - # test, or adjust the running state of the test in some way. When # - # viewing a test, collect the results and return an HTML template # - # using that data. Otherwise, look to adjust the running state of # - # the test. We throw out any invalid requests. Create a LogEvent # - # if the we attempt to modify the test's state in any way # - # # - # POST : The only valid POST request is for the action MODIFY. Requests # - # to modify contain an updated Priority and Throughput parameter # - # for the selected test. Bound the updated values, and log the # - # modification of the test with the creation of a new LogEvent # - # # - # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # - - if not Test.objects.filter(id=id): + if not (test := Test.objects.filter(id=id).first()): return django.http.HttpResponseRedirect('/index/') if action not in ['APPROVE', 'RESTART', 'STOP', 'DELETE', 'MODIFY']: - test = Test.objects.get(id=id) - results = Result.objects.filter(test=test).order_by('machine_id') - data = {'test' : test, 'results': results} - return render(request, 'test.html', data) + return render(request, 'test.html', OpenBench.utils.get_test_context(test)) if not request.user.is_authenticated: - return django.http.HttpResponseRedirect('/login/') + return redirect(request, '/login/', error='Only users may interact with tests') - user = request.user - test = Test.objects.get(id=id) - profile = Profile.objects.get(user=user) - - if not profile.approver and test.author != profile.user.username: - return django.http.HttpResponseRedirect('/index/') + profile = Profile.objects.get(user=request.user) + if not profile.approver and test.author != request.user.username: + return redirect(request, '/index/', error='You cannot interact with another user\'s test') if action == 'APPROVE': - if test.author == user.username and not user.is_superuser: - return django.http.HttpResponseRedirect('/index/') + if test.author == request.user.username and not user.is_superuser: + return redirect(request, '/index/', error='You cannot approve your own test') if action == 'APPROVE': test.approved = True; test.save() if action == 'RESTART': test.finished = False; test.save() @@ -434,47 +384,34 @@ def test(request, id, action=None): if action == 'DELETE' : test.deleted = True; test.save() if action == 'MODIFY': - test.priority = int(request.POST['priority']) - test.throughput = max(1, int(request.POST['throughput'])) + test.priority = int(request.POST['priority']) + test.throughput = max(1, int(request.POST['throughput'])) + test.report_rate = max(1, int(request.POST['report_rate'])) + test.workload_size = max(1, int(request.POST['workload_size'])) test.save() - action += " P={0} TP={1}".format(test.priority, test.throughput) - LogEvent.objects.create(author=user.username, summary=action, log_file='', test_id=test.id) + action += " P=%d TP=%d RR=%d WS=%d" % (test.priority, test.throughput, test.report_rate, test.workload_size) + LogEvent.objects.create(author=request.user.username, summary=action, log_file='', test_id=test.id) return django.http.HttpResponseRedirect('/index/') def newTest(request): - # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # - # # - # GET : Return the HTML template for creating a new test when the User # - # is both logged in, and enabled. Otherwise, we redirect those # - # requests to either login, or the index where they are told that # - # their account has not yet been enabled # - # # - # POST : Enabled Users may create new tests. Fields are error checked. # - # If an error is found, the creation is aborted and the list of # - # errors is prestented back to the User on the homepage. If both # - # versions of the Engine in the Test have been seen, then we will # - # automatically approve the Test # - # # - # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # - if not request.user.is_authenticated: - return django.http.HttpResponseRedirect('/login/') + return redirect(request, '/login/', error='Only enabled users can create tests') if not Profile.objects.get(user=request.user).enabled: - return django.http.HttpResponseRedirect('/index/') + return redirect(request, '/login/', error='Only enabled users can create tests') if request.method == 'GET': - data = { 'networks' : Network.objects.all() } + data = { 'networks' : list(Network.objects.all().values()) } return render(request, 'newTest.html', data) - test, errors = OpenBench.utils.createNewTest(request) + test, errors = OpenBench.utils.create_new_test(request) if errors != [] and errors != None: errors = ["[{0}]: {1}".format(i, e) for i, e in enumerate(errors)] longest = max([len(e) for e in errors]) errors = ["{0}{1}".format(e, ' ' * (longest-len(e))) for e in errors] - return index(request, error='\n'.join(errors)) + return render(request, 'newTest.html', {'error_message': '\n'.join(errors)}) username = request.user.username profile = Profile.objects.get(user=request.user) @@ -503,7 +440,7 @@ def newTest(request): # NETWORK MANAGEMENT VIEWS # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # -def networks(request, action=None, sha256=None, client=False): +def networks(request, target=None, sha256=None, client=False): # *** GET Requests: # [1] Fetch a view of all the Networks on the framework (/networks/) @@ -519,9 +456,9 @@ def networks(request, action=None, sha256=None, client=False): # Any user may look at the list of Networks, for all or some engines # Only authenticated and approved Users may interact in the remaining ways - if not action or action.upper() not in ['UPLOAD', 'DEFAULT', 'DELETE', 'DOWNLOAD']: + if not target or target.upper() not in ['UPLOAD', 'DEFAULT', 'DELETE', 'DOWNLOAD']: networks = Network.objects.all() - if action: networks = networks.filter(engine=action) + if target: networks = networks.filter(engine=target) return render(request, 'networks.html', { 'networks' : networks.order_by('-id') }) if not request.user.is_authenticated: @@ -530,54 +467,65 @@ def networks(request, action=None, sha256=None, client=False): if not client and not Profile.objects.get(user=request.user).approver: return django.http.HttpResponseRedirect('/index/') - if action.upper() == 'UPLOAD': + if target.upper() == 'UPLOAD': if request.method == 'GET': return render(request, 'uploadnet.html', {}) + name = request.POST['name'] engine = request.POST['engine'] netfile = request.FILES['netfile'] sha256 = hashlib.sha256(netfile.file.read()).hexdigest()[:8].upper() - if Network.objects.filter(sha256=sha256): - return index(request, error='Network with that hash already exists') + if not re.match(r'^[a-zA-Z0-9_.-]+$', name): + return redirect(request, '/uploadnet/', error='Valid characters are [a-zA-Z0-9_.-]') - if engine not in OpenBench.utils.OPENBENCH_CONFIG['engines'].keys(): - return index(request, error='No Engine found with matching name') + if Network.objects.filter(sha256=sha256): + return redirect(request, '/uploadnet/', error='Network with that hash already exists') + + if Network.objects.filter(engine=engine, name=name): + return redirect(request, '/uploadnet/', error='Network with that name already exists for that engine') + + if engine not in OPENBENCH_CONFIG['engines'].keys(): + return redirect(request, '/uploadnet/', error='No Engine found with matching name') FileSystemStorage().save(sha256, netfile) Network.objects.create( - sha256=sha256, name=request.POST['name'], + sha256=sha256, name=name, engine=engine, author=request.user.username) - return index(request) + return redirect(request, '/networks/', status='Uploaded %s for %s' % (engine, name)) - if action.upper() == 'DEFAULT': + if target.upper() == 'DEFAULT': if not Network.objects.filter(sha256=sha256): - return index(request, error='No Network found with matching SHA256') + return redirect(request, '/networks/', error='No network found with matching Sha') network = Network.objects.get(sha256=sha256) Network.objects.filter(engine=network.engine).update(default=False) network.default = True; network.save() - return django.http.HttpResponseRedirect('/networks/') + status = 'Set %s as default for %s' % (network.name, network.engine) + return redirect(request, '/networks/', status=status) - if action.upper() == 'DELETE': + if target.upper() == 'DELETE': if not Network.objects.filter(sha256=sha256): - return index(request, error='No Network found with matching SHA256') + return redirect(request, '/networks/', error='No network found with matching Sha') - Network.objects.get(sha256=sha256).delete() + network = Network.objects.get(sha256=sha256) + status = 'Deleted %s for %s' % (network.name, network.engine) + + network.delete() FileSystemStorage().delete(sha256) - return django.http.HttpResponseRedirect('/networks/') + return redirect(request, '/networks/', status=status) - if action.upper() == 'DOWNLOAD': + if target.upper() == 'DOWNLOAD': if not Network.objects.filter(sha256=sha256): - return index(request, error='No Network found with matching SHA256') + return redirect(request, '/networks/', error='No network found with matching Sha') netfile = os.path.join(MEDIA_ROOT, sha256) fwrapper = FileWrapper(open(netfile, 'rb'), 8192) @@ -608,177 +556,196 @@ def scripts(request): # CLIENT HOOK VIEWS # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # -@not_minified_response -def clientGetFiles(request): +def client_verify_worker(request): - # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # - # # - # GET : Return a URL to the location of Cutechess for Windows and Linux # - # # - # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # + ## Returns the machine, or None. Returns a JsonResponse or None. + ## Presence of a JsonResponse indicates a failure to verify - return HttpResponse(OpenBench.config.OPENBENCH_CONFIG['corefiles']) + # 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' }) -@not_minified_response -def clientGetBuildInfo(request): + # Ensure the Client is using the same version as the Server + if machine.info['client_ver'] != OPENBENCH_CONFIG['client_version']: + expected_ver = OPENBENCH_CONFIG['client_version'] + return machine, JsonResponse({ 'error' : 'Bad Client Version: Expected %s' % (expected_ver)}) - # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # - # # - # GET : Return a Dictionary of all of the Engines that are present in # - # config.py, as well as the required compilation tools for them # - # # - # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # + # Use the secret token as our soft verification + if machine.secret != request.POST['secret']: + return machine, JsonResponse({ 'error' : 'Invalid Secret Token' }) - data = {} - for engine, config in OpenBench.config.OPENBENCH_CONFIG['engines'].items(): - data[engine] = config['build'] - return HttpResponse(json.dumps(data)) + return machine, None @csrf_exempt -@not_minified_response -def clientGetWorkload(request): +def client_get_files(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. # - # # - # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # + ## Location of static compile of Cutechess for Windows and Linux. + ## OpenBench does not serve these files, but points to a repo ideally. + + return JsonResponse( {'location' : OPENBENCH_CONFIG['corefiles'] }) + +@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. + + data = {} + for engine, config in OPENBENCH_CONFIG['engines'].items(): + data[engine] = config['build'] + return JsonResponse(data) + +@csrf_exempt +def client_worker_info(request): # Verify the User's credentials try: user = authenticate(request, True) - except UnableToAuthenticate: return HttpResponse('Bad Credentials') + except UnableToAuthenticate: + return JsonResponse({ 'error' : 'Bad Credentials' }) - # Make sure the Client passed its version number - if 'version' not in request.POST: - return HttpResponse('Bad Client Version') + # Attempt to fetch the Machine, or create a new one + info = json.loads(request.POST['system_info']) + machine = OpenBench.utils.get_machine(info['machine_id'], user, info) - # Make sure the Client & Server version numbers match - if request.POST['version'] != OpenBench.config.OPENBENCH_CONFIG['client_version']: - return HttpResponse('Bad Client Version') + # Indicate invalid request + if not machine: + return JsonResponse({ 'error' : 'Bad Machine Id' }) - # getWorkload() will verify the integrity of the request - return HttpResponse(OpenBench.utils.getWorkload(user, request)) + # 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['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'].keys(): + 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 clientGetNetwork(request, sha256): +def client_get_workload(request): + + # Pass along any error messages if they appear + machine, response = client_verify_worker(request) + if response != None: return response + + # Contains keys 'workload', otherwise none + return JsonResponse(OpenBench.utils.get_workload(machine)) + +@csrf_exempt +def client_get_network(request, identifier, engine=None): # Verify the User's credentials try: django.contrib.auth.login(request, authenticate(request, True)) except UnableToAuthenticate: return HttpResponse('Bad Credentials') + # Return the requested Neural Network, after resolving the Network name + if engine is not None: + try: identifier = Network.objects.get(name=identifier, engine=engine).sha256 + except: return HttpResponse('Unable to find associated Network') + # Return the requested Neural Network file for the Client - return networks(request, action='DOWNLOAD', sha256=sha256, client=True) + return networks(request, action='DOWNLOAD', sha256=identifier, client=True) @csrf_exempt -@not_minified_response -def clientWrongBench(request): +def client_wrong_bench(request): - # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # - # # - # POST : Inform the server that an Engine reported an incorrect Bench # - # value during the init process for a Test. We stop the Test and # - # log an Error into the Events table to indicate what happened # - # # - # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # - - # 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/OpenSite/settings.py b/OpenSite/settings.py index 115c7fe..5812f95 100644 --- a/OpenSite/settings.py +++ b/OpenSite/settings.py @@ -23,7 +23,11 @@ SECRET_KEY = '@!zw2l8til1(0eb_nk+1w!(n78gqm&u)s)_v7#k6iseia@g9q0' DEBUG = True ALLOWED_HOSTS = ['*'] -HTML_MINIFY = True + +HTML_MINIFY = True +APPEND_SLASH = True + +DEFAULT_AUTO_FIELD = 'django.db.models.AutoField' # Application definition @@ -36,14 +40,14 @@ MEDIA_URL = '/Media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'Media') INSTALLED_APPS = [ + 'OpenBench', + 'OpenBench.templatetags', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', - 'OpenBench', - 'OpenBench.templatetags', ] MIDDLEWARE = [ diff --git a/OpenSite/urls.py b/OpenSite/urls.py index 1ca45e2..7b8961c 100644 --- a/OpenSite/urls.py +++ b/OpenSite/urls.py @@ -1,5 +1,6 @@ from django.contrib import admin from django.urls import path, include +from django.contrib.staticfiles.urls import staticfiles_urlpatterns import OpenBench.urls @@ -7,3 +8,5 @@ urlpatterns = [ path(r'admin/', admin.site.urls), path(r'', include(OpenBench.urls.urlpatterns)), ] + +urlpatterns += staticfiles_urlpatterns() \ No newline at end of file diff --git a/Scripts/bench_all.py b/Scripts/bench_all.py index 58fc8d3..b0cf49d 100755 --- a/Scripts/bench_all.py +++ b/Scripts/bench_all.py @@ -100,7 +100,6 @@ def build_all_engines(): os.mkdir('Binaries') for engine, config in OPENBENCH_CONFIG['engines'].items(): - if USE_OLD_BINARIES and os.path.isfile('Binaries/' + engine): continue diff --git a/Scripts/bench_engine.py b/Scripts/bench_engine.py index fc57472..ae3d49f 100755 --- a/Scripts/bench_engine.py +++ b/Scripts/bench_engine.py @@ -9,34 +9,35 @@ def parse_stream_output(stream): nps = bench = None # Search through output Stream for line in stream.decode('ascii').strip().split('\n')[::-1]: - # Try to match a wide array of patterns + # Convert non alpha-numerics to spaces line = re.sub(r'[^a-zA-Z0-9 ]+', ' ', line) - nps_pattern = r'([0-9]+ NPS)|(NPS[ ]+[0-9]+)' - bench_pattern = r'([0-9]+ NODES)|(NODES[ ]+[0-9]+)' - re_nps = re.search(nps_pattern, line.upper()) - re_bench = re.search(bench_pattern, line.upper()) - # Replace only if not already found earlier - if not nps and re_nps: nps = re_nps.group() - if not bench and re_bench: bench = re_bench.group() + # Multiple methods, including Ethereal and Stockfish + nps_pattern = r'(\d+\s+nps)|(nps\s+\d+)|(nodes second\s+\d+)' + bench_pattern = r'(\d+\s+nodes)|(nodes\s+\d+)|(nodes searched\s+\d+)' + + # Search for and set only once the NPS value + if (re_nps := re.search(nps_pattern, line, re.IGNORECASE)): + nps = nps if nps else re_nps.group() + + # Search for and set only once the Bench value + if (re_bench := re.search(bench_pattern, line, re.IGNORECASE)): + bench = bench if bench else re_bench.group() # Parse out the integer portion from our matches - nps = int(re.search(r'[0-9]+', nps).group()) if nps else None - bench = int(re.search(r'[0-9]+', bench).group()) if bench else None + nps = int(re.search(r'\d+', nps ).group()) if nps else None + bench = int(re.search(r'\d+', bench).group()) if bench else None + return (bench, nps) def single_core_bench(engine, outqueue): # Launch the bench and wait for results stdout, stderr = subprocess.Popen( - "./{0} bench".format(engine).split(), + './{0} bench'.format(engine).split(), stdout=subprocess.PIPE, stderr=subprocess.STDOUT).communicate() - # Parse output streams for the benchmark data - bench, speed = parse_stream_output(stdout) - if bench is None or speed is None: - bench, speed = parse_stream_output(stderr) - outqueue.put((int(bench), int(speed))) + outqueue.put(parse_stream_output(stdout)) def multi_core_bench(engine, threads): diff --git a/Templates/OpenBench/Blocks/pagebrowser.html b/Templates/OpenBench/Blocks/pagebrowser.html index a9ffa73..6a292ff 100644 --- a/Templates/OpenBench/Blocks/pagebrowser.html +++ b/Templates/OpenBench/Blocks/pagebrowser.html @@ -1,13 +1,15 @@ -
+
{% if paging.prev != paging.next %} - <-- - {% for page in paging.pages %} - {% if page != "..." %} - {{page}} - {% else %} - {{page}} - {% endif %} - {% endfor %} - --> + {% endif %} -
\ No newline at end of file +
diff --git a/Templates/OpenBench/Blocks/testsummary.html b/Templates/OpenBench/Blocks/testsummary.html index 2bdbe44..ee7dcc8 100644 --- a/Templates/OpenBench/Blocks/testsummary.html +++ b/Templates/OpenBench/Blocks/testsummary.html @@ -1,11 +1,16 @@ {% load mytags %} {{test.author|capfirst|slice:":6"}} - {{test.engine}} - {% if test.error %} [x] {{test|prettyDevName}} - {% elif test|testIsFRC %} {{test|prettyDevName}}[FRC] - {% else %} {{test|prettyDevName}} {% endif %} + {{test.dev_engine}} + + {{test|prettyDevName}} + {% if test.error %} * {% endif %} + {% if test|testIsFRC %} * {% endif %} + diff - {{test.timecontrol}} - {{test|shortStatBlock|linebreaksbr}} + + {{test.dev_time_control}} + {% if test.dev_time_control != test.base_time_control %} * {% endif %} + + {{test|shortStatBlock|linebreaksbr}} diff --git a/Templates/OpenBench/base.html b/Templates/OpenBench/base.html index fde75e6..69be0c8 100644 --- a/Templates/OpenBench/base.html +++ b/Templates/OpenBench/base.html @@ -5,18 +5,22 @@ {% load static %} - + + + + - + OpenBench - + {% endblock %} {% block content %}
{% csrf_token %} -
-

Engine

-
-
+
+
-

Dev Settings

-
-
-
-
+

Engines

-

Base Settings

-
-
-
-
+
+ + +
+
+ +
+
+ + +
+
+ +
+

Dev Settings

+ +
+ +
+
+ +
+
+ +
+
+ +
+
+ +
+ +

Base Settings

+ +
+ +
+
+ +
+
+ +
+
+ +
+
+ +
+ +
+ +
+ +

Test Settings

+ +
+ +
+ +
+ + +
+
+ +
+
+ +
+
+ +
+ +

General Settings

+
+ +
+
+ +
+ +
+ +
+ +

Workload Settings

+
+ +
+
+ +
+ +

Adjudication Settings

+
+ + +
+
+ +
+
+ +
+
-
- -

Game Settings

-
-
- -

Test Settings

-
-
-
-
- -

General Settings

-
-
- -
- -
- -
- -
- + -
- +
+
+
+ +
+
{% endblock %} diff --git a/Templates/OpenBench/profile.html b/Templates/OpenBench/profile.html index 2793983..f58abfe 100644 --- a/Templates/OpenBench/profile.html +++ b/Templates/OpenBench/profile.html @@ -1,33 +1,124 @@ {% extends "OpenBench/base.html" %} +{% load static %} +{% load mytags %} + {% block content %}
{% csrf_token %} +
+
+
+ +
+
+ +
- -
-
-
-
-
- - -
- - - +
+ +
+
+ +
+ +
+
-{% endblock %} +
+ +
+ {% csrf_token %} +
+
+ + + {% for engine, repo in profile.repos.items %} +
+ + + + + + + + + + +
+ {% endfor %} + +
+ + + +
+ + + +
+
+
+ + + + +{% endblock %} \ No newline at end of file diff --git a/Templates/OpenBench/register.html b/Templates/OpenBench/register.html index f5c5bdc..a705cf8 100644 --- a/Templates/OpenBench/register.html +++ b/Templates/OpenBench/register.html @@ -4,11 +4,23 @@
{% csrf_token %} -
-
-
-
- +
+
+
+ +
+
+ +
+
+ +
+
+ +
+ +
+
{% endblock %} diff --git a/Templates/OpenBench/search.html b/Templates/OpenBench/search.html index db26d4f..5d2be87 100644 --- a/Templates/OpenBench/search.html +++ b/Templates/OpenBench/search.html @@ -23,54 +23,66 @@
{% csrf_token %} -
-
- - -
- - -
- - -
- - -
- - -
- - -
- - - +
+
+
+
+
+
+
+
+
+ +
+
+
+ +
+
+
+ +
+
+
+ +
+
+
+ +
+
+
+ +
+
+ +
+
{% endif %} - +
{% for test in tests %} {% include "OpenBench/Blocks/testsummary.html" %} {% endfor %} diff --git a/Templates/OpenBench/test.html b/Templates/OpenBench/test.html index 391fe89..eeb4cf0 100644 --- a/Templates/OpenBench/test.html +++ b/Templates/OpenBench/test.html @@ -3,45 +3,85 @@ {% load mytags %} {% block style %} -{% load static %} +{% endblock %} + +{% block scripts %} + + + {% endblock %} {% block content %} -
-
- - - - - - - - {% if test.devnetwork %} - - - - - {% endif %} - - - - - {% if test.basenetwork %} - - - - - {% endif %} - - +
+
Author{{test.author|capfirst}}
Creation{{test.creation|date:'U'}}
Engine{{test.engine}}
Dev Branch{{test.dev.name|prettyName}}
Dev Bench{{test.dev.bench}}
Dev Options{{test.devoptions}}
Dev Sha{{test.dev.sha}}
Dev Network{{test.devnetname}}
Base Branch{{test.base.name|prettyName}}
Base Bench{{test.base.bench}}
Base Options{{test.baseoptions}}
Base Sha{{test.base.sha}}
Base Network{{test.basenetname}}
Source Repo{{test.source}}
Opening Book{{test.bookname}}
+ + - - + + + + + + {% if test.dev_network %} + + + + {% endif %} + + + + + + + + {% if test.base_network %} + + + + {% endif %} + + + + + + + +
Author{{test.author|capfirst}}
Creation{{test.creation|date:'U'}}
Syzygy ADJ{{test.syzygy_adj}}
Syzygy WDL{{test.syzygy_wdl}}
Dev Engine{{test.dev_engine}}
Dev Source{{test.dev_repo}}
Dev Sha{{test.dev.sha}}
Dev Branch{{test.dev.name|prettyName}}
Dev Bench{{test.dev.bench}}
Dev Network{{test.dev_netname}}
Dev Options{{test.dev_options}}
Dev Time{{test.dev_time_control}}
Base Engine{{test.base_engine}}
Base Source{{test.base_repo}}
Base Sha{{test.base.sha}}
Base Bench{{test.base.bench}}
Base Network{{test.base_netname}}
Base Options{{test.base_options}}
Base Time{{test.base_time_control}}
Opening Book{{test.book_name}}
Syzygy WDL{{test.syzygy_wdl}}
Syzygy ADJ.{{test.syzygy_adj}}
Win ADJ.{{test.win_adj}}
Draw ADJ.{{test.draw_adj}}
-
+

@@ -50,70 +90,78 @@ {% if not test.approved and profile.approver and profile.user.username != test.author %} - Approve + Approve {% elif not test.approved and request.user.is_superuser %} - Approve + Approve {% else %} - Approve + Approve {% endif %} {% if test.finished and profile.approver %} - Restart + Restart {% elif test.finished and profile.user.username == test.author %} - Restart + Restart {% elif test.finished %} - Restart + Restart {% endif %} {% if not test.finished and profile.approver %} - Stop + Stop {% elif not test.finished and profile.user.username == test.author %} - Stop + Stop {% elif not test.finished %} - Stop + Stop {% endif %} {% if profile.approver or profile.user.username == test.author %} - Delete + Delete {% else %} - Delete + Delete {% endif %} + + + + -
{{test|longStatBlock|linebreaksbr}}
+
{{test|longStatBlock|linebreaksbr}}
- {% csrf_token %} - -
-
- - - {% if profile.approver or profile.user.username == test.author %} - - {% else %} - - {% endif %} - +
+
+
+ +
+
+ +
+
+ +
+
+ +
+ + {% if profile.approver or profile.user.username == test.author %} + + {% else %} + + {% endif %} +
+
-

-
- -
- - - - +
+
+ - @@ -123,11 +171,10 @@ - {% for result in results %} + {% for id, result in results.items %} - - - + + diff --git a/Templates/OpenBench/uploadnet.html b/Templates/OpenBench/uploadnet.html index a3f6d55..3291df3 100644 --- a/Templates/OpenBench/uploadnet.html +++ b/Templates/OpenBench/uploadnet.html @@ -3,22 +3,37 @@ {% block content %} - {% csrf_token %} + {% csrf_token %} + +
+
+
+ +
+
+ +
+
+ + +
+ + + +
+
+ -
-
-
- {% endblock %} diff --git a/Templates/OpenBench/users.html b/Templates/OpenBench/users.html index 9cbd4b8..59e794b 100644 --- a/Templates/OpenBench/users.html +++ b/Templates/OpenBench/users.html @@ -4,35 +4,37 @@ {% block content %} -
# UserOS Updated Games WonCrash
{{result.machine.id}}{{result.machine.user.username|capfirst|slice:"6"}}{{result.machine.osname|truncatewords:1|slice:":-2"}}{{result.machine_id}}{{result.username|capfirst|slice:"6"}} {{result.updated|date:'U'}} {{result.games}} {{result.wins}}
+
- - + + - + + {% for profile in profiles %} - {% if profile.enabled %} - {% if profile.games or profile.tests %} - - - - - - - + {% if profile.enabled %} + {% if profile.games or profile.tests or profile.approver %} + + + + + + + + {% endif %} {% endif %} - {% endif %} {% endfor %}
Username
Username Games TestsEngineEngine Default Repository
{{profile.user.username|capfirst}}{{profile.games|insertCommas}}{{profile.tests|insertCommas}}{{profile.engine}}{{profile.repo}}
{{profile.user.username|capfirst}}{{profile.games|insertCommas}}{{profile.tests|insertCommas}}{{profile.engine}}{{profile.repo}}
diff --git a/cleanup.sh b/cleanup.sh deleted file mode 100755 index 111b7f6..0000000 --- a/cleanup.sh +++ /dev/null @@ -1,12 +0,0 @@ -#!/bin/sh - -rm -i db.sqlite3 -rm -r OpenBench/migrations/* -rm -r OpenBench/__pycache__/* -rm -r OpenSite/__pycache__/* - -python3 manage.py makemigrations -python3 manage.py migrate -python3 manage.py migrate --run-syncdb - -python3 manage.py createsuperuser \ No newline at end of file