From c02e0782b69a53d7ffc67e0448a584dde143b004 Mon Sep 17 00:00:00 2001 From: andrew Date: Tue, 7 Mar 2023 23:12:23 -0500 Subject: [PATCH] Add Support for Private source engines Private source engines must be located on Github. All test branches must come from the same repo as stated in the config. Repo must have an openbench.yml file that produces artifacts for the workers. Basic name scheme: windows-avx2-pext, linux-avx512-pext, ... Desired artifacts can be set in the engine config under ['build']['artifacts'] Server must have a private key, housed in credentials.enginename. Client must have a private key, housed in credentials.enginename. enginename is lowercase and with spaces removed. Private engines cannot build their NNUE files directly into them. They must therefore support being run from the CMD line, with additional options. Namely: ./engine "setoption name EvalFile value path/to/file" "bench" "quit". --- Client/Client.py | 206 ++++++++++++++++++++++--------- OpenBench/config.py | 38 +++--- OpenBench/templatetags/mytags.py | 10 +- OpenBench/utils.py | 153 ++++++++++++++++++----- OpenBench/views.py | 1 + 5 files changed, 296 insertions(+), 112 deletions(-) diff --git a/Client/Client.py b/Client/Client.py index 037108d..9e220ea 100644 --- a/Client/Client.py +++ b/Client/Client.py @@ -48,7 +48,7 @@ from itertools import combinations_with_replacement TIMEOUT_HTTP = 30 # Timeout in seconds for HTTP requests TIMEOUT_ERROR = 10 # Timeout in seconds when any errors are thrown TIMEOUT_WORKLOAD = 30 # Timeout in seconds between workload requests -CLIENT_VERSION = '5' # Client version to send to the Server +CLIENT_VERSION = '6' # 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 @@ -86,6 +86,7 @@ IS_WINDOWS = platform.system() == 'Windows' IS_LINUX = platform.system() != 'Windows' COMPILERS = {} # Compiler for each Engine, + CPU Flags +CPUINFO = '' # Result of ``echo | gcc -march=native -E -dM -`` OSNAME = '%s %s' % (platform.system(), platform.release()) DEBUG = True @@ -207,9 +208,9 @@ def try_until_success(mesg): 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 @@ -260,11 +261,15 @@ def parse_bench_output(stream): bench = int(re.search(r'[0-9]+', bench).group()) if bench else None return (nps, bench) -def run_bench(engine, outqueue): +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) + process = Popen(cmd, stdout=PIPE, stderr=PIPE) stdout, stderr = process.communicate() outqueue.put(parse_bench_output(stdout)) except Exception: outqueue.put((0, 0)) @@ -389,8 +394,6 @@ def server_download_cutechess(arguments): @try_until_success(mesg=ERRORS['configure']) def server_configure_worker(arguments): - print ('\nScanning for Compilers...') - # Fetch { Engine -> Compilers } from the server target = url_join(arguments.server, 'clientGetBuildInfo') data = requests.get(target, timeout=TIMEOUT_HTTP).json() @@ -410,8 +413,15 @@ def server_configure_worker(arguments): stdout = process.communicate()[0].decode('utf-8') return re.search(r'[0-9]+\.[0-9]+\.[0-9]+', stdout).group() + 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 build_info['private']: + continue + for compiler in build_info['compilers']: # Compilers may require a specific version @@ -425,33 +435,47 @@ def server_configure_worker(arguments): # Compiler version was sufficient if tuple(map(int, match.split('.'))) >= version: - print('%14s | %s (%s)' % (engine, compiler, match)) + print('%-20s | %-8s (%s)' % (engine, compiler, match)) COMPILERS[engine] = compiler break # Report missing engines in case the User is not expecting it - for engine in filter(lambda x: x not in COMPILERS, data): + for engine in filter(lambda x: x not in COMPILERS and not data[x]['private'], data): compiler = data[engine]['compilers'] - print('%14s | Missing %s' % (engine, compiler)) + print('%-20s | Missing %s' % (engine, compiler)) + + 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 build_info['private']: + continue + + # Private engines expect a credentials.engine file for the main repo + has_token = os.path.exists('credentials.%s' % (engine.replace(' ', '').lower())) + print('%-20s | %s' % (engine, ['Missing', 'Found'][has_token])) + if has_token: COMPILERS[engine] = True print('\nScanning for CPU Flags...') # Use GCC -march=native to find CPU info - stdout, stderr = Popen( + CPUINFO = str(Popen( 'echo | gcc -march=native -E -dM -', stdout=PIPE, shell=True - ).communicate() + ).communicate()[0]) # 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))) + actual = set(f for f in flags if '%s 1' % (f) in CPUINFO) COMPILERS['cpuflags'] = ' '.join(list(actual)) + # Print out the results of our search + for flag in sorted(flags): + print ('%-20s | %s' % (flag, ['Missing', 'Found'][flag in actual])) + @try_until_success(mesg=ERRORS['request']) def server_request_workload(arguments): @@ -478,6 +502,20 @@ def server_request_workload(arguments): target = url_join(arguments.server, 'clientGetWorkload') return requests.post(target, data=payload, timeout=TIMEOUT_HTTP) +def server_report_missing_artifact(arguments, workload, branch, artifact_name, artifact_json): + + payload = { + 'username' : arguments.username, + 'password' : arguments.password, + 'testid' : workload['test']['id'], + 'machineid' : workload['machine']['id'], + 'error' : 'Artifact %s missing' % (artifact_name), + 'logs' : json.dumps(artifact_json, indent=2), + } + + target = url_join(arguments.server, 'clientSubmitError') + requests.post(target, data=payload, timeout=TIMEOUT_HTTP) + def server_report_build_fail(arguments, workload, branch, compiler_output): payload = { @@ -602,17 +640,17 @@ def check_workload_response(arguments, response): 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) - 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 @@ -695,37 +733,71 @@ def download_engine(arguments, workload, branch, network): commit_sha = workload['test'][branch]['sha'] source = workload['test'][branch]['source'] build_path = workload['test']['build']['path'] + private = workload['engine']['private'] - 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) + # Construct the artifact string for the desired binary + old_ryzen = '__znver1' in str(CPUINFO) or '__znver2' in str(CPUINFO) + os_string = ['windows', 'linux' ][IS_LINUX] + avx_string = ['avx2' , 'avx512']['__AVX512VNNI__ 1' in str(CPUINFO)] + bit_string = ['popcnt' , 'pext' ]['__BMI2__ 1' in str(CPUINFO) and not old_ryzen] + 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) + + 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,21 +811,23 @@ 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 = int(arguments.threads) + queue = multiprocessing.Queue() + name = workload['test'][branch]['name'] + private = workload['engine']['private'] 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)])) if len(set(bench)) > 1: return (0, 0) # Flag an error @@ -767,7 +841,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): dev_options = workload['test']['dev' ]['options'] base_options = workload['test']['base']['options'] @@ -775,11 +849,29 @@ 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_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) + # Add EvalFile to the options for Private engines using Networks + if workload['engine']['private']: + + dev_network = workload['test']['dev' ]['network'] + if dev_network and dev_network != 'None': + dev_options += ' EvalFile=%s' % (os.path.join('../Networks', dev_network)) + dev_name += '-%s' % (dev_network) + + base_network = workload['test']['base']['network'] + if 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()) @@ -810,10 +902,10 @@ def build_cutechess_command(arguments, workload, dev_name, base_name, nps): args = ( win_adj, draw_adj, 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'), + dev_cmd, time_control, dev_options, dev_name, + base_cmd, time_control, base_options, base_name, book_name, book_name.split('.')[-1], - dev_name.rstrip('.exe'), base_name.rstrip('.exe') + dev_name, base_name, ) if IS_LINUX: diff --git a/OpenBench/config.py b/OpenBench/config.py index fb88594..6c2af11 100644 --- a/OpenBench/config.py +++ b/OpenBench/config.py @@ -25,7 +25,7 @@ REQUIRE_LOGIN_TO_VIEW = False OPENBENCH_CONFIG = { # Server Client version control - 'client_version' : '5', + 'client_version' : '6', # Generic Error Messages useful to those setting up their own instance 'error' : { @@ -114,7 +114,7 @@ OPENBENCH_CONFIG = { 'build' : { 'path' : 'src', 'compilers' : ['clang', 'gcc'], - 'cpuflags' : ['AVX2', 'AVX', 'FMA', 'POPCNT', 'SSE2', 'SSE'], + 'cpuflags' : ['__AVX2__', '__FMA__', '__POPCNT__'], }, 'testmodes' : [ @@ -140,7 +140,7 @@ OPENBENCH_CONFIG = { 'build' : { 'path' : 'src', 'compilers' : ['g++'], - 'cpuflags' : ['POPCNT'], + 'cpuflags' : ['__POPCNT__'], }, 'testmodes' : [ @@ -166,7 +166,7 @@ OPENBENCH_CONFIG = { 'build' : { 'path' : 'src', 'compilers' : ['gcc'], - 'cpuflags' : ['POPCNT'], + 'cpuflags' : ['__POPCNT__'], }, 'testmodes' : [ @@ -192,7 +192,7 @@ OPENBENCH_CONFIG = { 'build' : { 'path' : 'src', 'compilers' : ['clang', 'gcc'], - 'cpuflags' : ['POPCNT'], + 'cpuflags' : ['__POPCNT__'], }, 'testmodes' : [ @@ -218,7 +218,7 @@ OPENBENCH_CONFIG = { 'build' : { 'path' : 'src', 'compilers' : ['g++'], - 'cpuflags' : ['POPCNT'], + 'cpuflags' : ['__POPCNT__'], }, 'testmodes' : [ @@ -244,7 +244,7 @@ OPENBENCH_CONFIG = { 'build' : { 'path' : '', 'compilers' : ['cargo>=1.41.0'], - 'cpuflags' : ['POPCNT'], + 'cpuflags' : ['__POPCNT__'], }, 'testmodes' : [ @@ -270,7 +270,7 @@ OPENBENCH_CONFIG = { 'build' : { 'path' : 'src', 'compilers' : ['g++'], - 'cpuflags' : ['POPCNT'], + 'cpuflags' : ['__POPCNT__'], }, 'testmodes' : [ @@ -296,7 +296,7 @@ OPENBENCH_CONFIG = { 'build' : { 'path' : '', 'compilers' : ['clang++', 'g++'], - 'cpuflags' : ['POPCNT'], + 'cpuflags' : ['__POPCNT__'], }, 'testmodes' : [ @@ -322,7 +322,7 @@ OPENBENCH_CONFIG = { 'build' : { 'path' : 'src', 'compilers' : ['g++'], - 'cpuflags' : ['POPCNT'], + 'cpuflags' : ['__POPCNT__'], }, 'testmodes' : [ @@ -348,7 +348,7 @@ OPENBENCH_CONFIG = { 'build' : { 'path' : 'src', 'compilers' : ['gcc', 'clang'], - 'cpuflags' : ['POPCNT'], + 'cpuflags' : ['__POPCNT__'], }, 'testmodes' : [ @@ -374,7 +374,7 @@ OPENBENCH_CONFIG = { 'build' : { 'path' : 'build', 'compilers' : ['g++>=9.0.0'], - 'cpuflags' : ['AVX2', 'AVX', 'FMA', 'POPCNT', 'SSE2', 'SSE'], + 'cpuflags' : ['__AVX2__', '__FMA__', '__POPCNT__'], }, 'testmodes' : [ @@ -400,7 +400,7 @@ OPENBENCH_CONFIG = { 'build' : { 'path' : 'src_files', 'compilers' : ['g++'], - 'cpuflags' : ['AVX2', 'AVX', 'FMA', 'POPCNT', 'SSE2', 'SSE'], + 'cpuflags' : ['__AVX2__', '__FMA__', '__POPCNT__'], }, 'testmodes' : [ @@ -426,7 +426,7 @@ OPENBENCH_CONFIG = { 'build' : { 'path' : '', 'compilers' : ['g++'], - 'cpuflags' : ['POPCNT'], + 'cpuflags' : ['__POPCNT__'], }, 'testmodes' : [ @@ -452,7 +452,7 @@ OPENBENCH_CONFIG = { 'build' : { 'path' : 'src', 'compilers' : ['g++'], - 'cpuflags' : ['POPCNT'], + 'cpuflags' : ['__POPCNT__'], }, 'testmodes' : [ @@ -478,7 +478,7 @@ OPENBENCH_CONFIG = { 'build' : { 'path' : 'src', 'compilers' : ['gcc'], - 'cpuflags' : ['AVX2', 'AVX', 'FMA', 'POPCNT', 'SSE2', 'SSE'], + 'cpuflags' : ['__AVX2__', '__FMA__', '__POPCNT__'], }, 'testmodes' : [ @@ -504,7 +504,7 @@ OPENBENCH_CONFIG = { 'build' : { 'path' : '', 'compilers' : ['go'], - 'cpuflags' : ['AVX', 'POPCNT'], + 'cpuflags' : ['__AVX__', '__POPCNT__'], }, 'testmodes' : [ @@ -530,7 +530,7 @@ OPENBENCH_CONFIG = { 'build' : { 'path' : '', 'compilers': ['cargo>=1.57.0'], - 'cpuflags' : ['AVX2', 'AVX', 'FMA', 'POPCNT', 'SSE2', 'SSE'], + 'cpuflags' : ['__AVX2__', '__FMA__', '__POPCNT__'], }, 'testmodes' : [ @@ -556,7 +556,7 @@ OPENBENCH_CONFIG = { 'build' : { 'path' : '', 'compilers' : ['g++'], - 'cpuflags' : ['POPCNT'], + 'cpuflags' : ['__POPCNT__'], }, 'testmodes' : [ diff --git a/OpenBench/templatetags/mytags.py b/OpenBench/templatetags/mytags.py index cf059c5..e668d60 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,14 +51,20 @@ def gitDiffLink(test): base = test['base']['source'] devsha = test['dev']['sha'] basesha = test['base']['sha'] + engine = test['engine'] else: dev = test.dev.source base = test.base.source devsha = test.dev.sha basesha = test.base.sha + engine = test.engine + + if OpenBench.config.OPENBENCH_CONFIG['engines'][engine]['private']: + repo = OpenBench.config.OPENBENCH_CONFIG['engines'][engine]['source'] + else: + repo = OpenBench.utils.pathjoin(*dev.split('/')[:-2]) - repo = OpenBench.utils.pathjoin(*dev.split('/')[:-2]) return OpenBench.utils.pathjoin(repo, 'compare', '{0}...{1}'.format(basesha[:8], devsha[:8])) diff --git a/OpenBench/utils.py b/OpenBench/utils.py index face156..cfb3b05 100644 --- a/OpenBench/utils.py +++ b/OpenBench/utils.py @@ -148,55 +148,136 @@ 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(request): + + engine = request.POST['enginename'].replace(' ', '').lower() + fname = 'credentials.%s' % (engine) + + if os.path.exists(fname): + with open(fname) as fin: + return { 'Authorization' : 'token %s' % fin.readlines()[0].rstrip() } + +def requests_illegal_fork(request): + + # Strip trailing '/'s for sanity + engine = OPENBENCH_CONFIG['engines'][request.POST['enginename']] + eng_src = engine['source'].rstrip('/') + tar_src = request.POST['source'].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['source'].replace('github.com', 'api.github.com/repos') + private = OPENBENCH_CONFIG['engines'][request.POST['enginename']]['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 sit 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(request)): + errors.append('Server does not have access tokens for this engine') + return (None, None, None, None) + + # Do not allow private engines to use forked repos ( We don't have a token! ) + if requests_illegal_fork(request): + errors.append('Forked Repositories are not allowed for Private engines') + return (None, None, 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) - # 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 = pathjoin(base, path, branch).rstrip('/') + 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)) + path = 'Commit Sha' if bysha else 'Branch' + errors.append('{0} {1} could not be found'.format(path, branch)) return (None, None, None, None) - treeurl = data['commit']['tree']['sha'] + '.zip' - source = pathjoin(repo, 'archive', treeurl).rstrip('/') - - 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 - - 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) - - except: # Neither method found a viable Bench - errors.append('Unable to parse a Bench for {0}'.format(branch)) + # 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, None, None) + # Public Engines: Construct the .zip download and return everything + if not OPENBENCH_CONFIG['engines'][request.POST['enginename']]['private']: + treeurl = data['commit']['tree']['sha'] + '.zip' + source = pathjoin(request.POST['source'], 'archive', treeurl).rstrip('/') + 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 do not exist, we cannot create the test. + + try: # Fetch the run id for the openbench workflow for this comment + url = pathjoin(base, 'actions', 'workflows', 'openbench.yml', 'runs').rstrip('/') + url += '?head_sha=%s' % (data['sha']) + run_id = requests.get(url=url, headers=headers).json()['workflow_runs'][0]['id'] + + except: # Unable to determine this for whatever reason + errors.append('Failed to idenftify the run_id associated with the OpenBench workflow') + return (None, None, None, None) + + try: # Fetch the artifact list for the run_id we determined above + url = pathjoin(base, 'actions', 'runs', str(run_id), 'artifacts').rstrip('/') + artifacts = requests.get(url=url, headers=headers).json()['artifacts'] + + except: # Unable to fetch the list of artifacts for whatever reason + errors.append('Failed to get the Artifact List for run_id = %d' % (run_id)) + return (None, None, None, None) + + # 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'][request.POST['enginename']]['build']['artifacts'] + + # Flag any and all missing artifacts + for name in required: + if '%s-%s' % (data['sha'], name) not in available: + errors.append('Missing Artifact (%s)' % (name)) + + # Return the API endpoint for artifacts, along with the usual rest + return (url, branch, data['sha'], bench) + + def verifyNewTest(request): errors = [] @@ -259,8 +340,8 @@ def createNewTest(request): errors = verifyNewTest(request) if errors != []: return None, errors - devinfo = getBranch(request, errors, 'dev') - baseinfo = getBranch(request, errors, 'base') + devinfo = collect_github_info(request, errors, 'dev') + baseinfo = collect_github_info(request, errors, 'base') if errors != []: return None, errors test = Test() @@ -442,6 +523,10 @@ def workload_to_dictionary(test, result, machine): 'result' : { 'id' : result.id }, + 'engine' : { + 'private' : OPENBENCH_CONFIG['engines'][test.engine]['private'] + }, + 'test' : { 'id' : test.id, diff --git a/OpenBench/views.py b/OpenBench/views.py index b807541..a893532 100644 --- a/OpenBench/views.py +++ b/OpenBench/views.py @@ -639,6 +639,7 @@ def clientGetBuildInfo(request): data = {} for engine, config in OpenBench.config.OPENBENCH_CONFIG['engines'].items(): data[engine] = config['build'] + data[engine]['private'] = config['private'] return HttpResponse(json.dumps(data)) @csrf_exempt