From 392cb001c782f68a41b5e95730ea374e78a09a48 Mon Sep 17 00:00:00 2001 From: Andrew Grant Date: Fri, 1 May 2020 15:05:12 -0400 Subject: [PATCH] Add clientGetFiles(), clientGetBuildInfo(), clientGetWorkload() --- Client/Client.py | 83 +++++++++++----------- OpenBench/urls.py | 8 ++- OpenBench/utils.py | 170 +++++++++++++++++++++++++-------------------- OpenBench/views.py | 51 ++++++-------- 4 files changed, 164 insertions(+), 148 deletions(-) diff --git a/Client/Client.py b/Client/Client.py index f699d3e..5b3afd9 100644 --- a/Client/Client.py +++ b/Client/Client.py @@ -49,6 +49,7 @@ IS_LINUX = platform.system() != 'Windows' COMPILERS = {} # Mapping of Engines to Compilers + def addExtension(name): return name + ["", ".exe"][IS_WINDOWS] @@ -79,11 +80,35 @@ def killCutechess(cutechess): except Exception as error: pass +def getCutechess(server): + + # Ask the server where the core files are saved + source = requests.get( + pathjoin(server, 'clientGetFiles'), + timeout=HTTP_TIMEOUT).content.decode('utf-8') + + # Windows workers need the cutechess.exe and the Qt5Core dll. + # Linux workers need cutechess and the libcutechess SO. + # Make sure Linux binaries are set to be executable. + + if IS_WINDOWS and not os.path.isfile('cutechess.exe'): + getFile(pathjoin(source, 'cutechess-windows.exe'), 'cutechess.exe') + + if IS_WINDOWS and not os.path.isfile('Qt5Core.dll'): + getFile(pathjoin(source, 'cutechess-qt5core.dll'), 'Qt5Core.dll') + + if IS_LINUX and not os.path.isfile('cutechess'): + getFile(pathjoin(source, 'cutechess-linux'), 'cutechess') + os.system('chmod 777 cutechess') + + if IS_LINUX and not os.path.isfile('libcutechess.so.1'): + getFile(pathjoin(source, 'libcutechess.so.1'), 'libcutechess.so.1') + def getCompilationSettings(server): # Get a dictionary of engine -> compilers data = requests.get( - pathjoin(server, 'getCompilers'), + pathjoin(server, 'clientGetBuildInfo'), timeout=HTTP_TIMEOUT).content.decode('utf-8') data = ast.literal_eval(data) @@ -127,6 +152,7 @@ def getCompilationSettings(server): for engine in [engine for engine in data.keys() if engine not in COMPILERS]: print("Unable to find compiler for {0}".format(engine)) + def getFile(source, output): # Download the source file @@ -149,29 +175,6 @@ def getAndUnzipFile(source, name, output): # Cleanup by deleting the .zip os.remove(name) -def getCutechess(server): - - # Ask the server where the core files are saved - source = requests.get( - pathjoin(server, 'getFiles'), - timeout=HTTP_TIMEOUT).content.decode('utf-8') - - # Windows workers need the cutechess.exe and the Qt5Core dll. - # Linux workers need cutechess and the libcutechess SO. - # Make sure Linux binaries are set to be executable. - - if IS_WINDOWS and not os.path.isfile('cutechess.exe'): - getFile(pathjoin(source, 'cutechess-windows.exe'), 'cutechess.exe') - - if IS_WINDOWS and not os.path.isfile('Qt5Core.dll'): - getFile(pathjoin(source, 'cutechess-qt5core.dll'), 'Qt5Core.dll') - - if IS_LINUX and not os.path.isfile('cutechess'): - getFile(pathjoin(source, 'cutechess-linux'), 'cutechess') - os.system('chmod 777 cutechess') - - if IS_LINUX and not os.path.isfile('libcutechess.so.1'): - getFile(pathjoin(source, 'libcutechess.so.1'), 'libcutechess.so.1') def getMachineID(): @@ -564,24 +567,24 @@ def completeWorkload(workRequestData, arguments): # Get the next workload data = requests.post( - pathjoin(arguments.server, 'getWorkload'), + pathjoin(arguments.server, 'clientGetWorkload'), data=workRequestData, timeout=HTTP_TIMEOUT).content.decode('utf-8') # Check for an empty workload if data == 'None': - print('[NOTE] Server Has No Work') + print('\n[NOTE] Server Has No Work') time.sleep(WORKLOAD_TIMEOUT) return # Kill process if unable to login if data == 'Bad Credentials': - print('[ERROR] Invalid Login Credentials') + print('\n[ERROR] Invalid Login Credentials') sys.exit() # Bad machines will be registered again if data == 'Bad Machine': workRequestData['machineid'] = 'None' - print('[NOTE] Invalid Machine ID') + print('\n[NOTE] Invalid Machine ID') return # Convert response into a dictionary @@ -610,17 +613,6 @@ def main(): p.add_argument('-T', '--threads', help='Number of Threads', required=True) arguments = p.parse_args() - # All workload requests must be tied to a user and a machine. - # We also pass a thread count to inform the server what tests this - # machine can handle. We pass the osname in order to register machines - workRequestData = { - 'machineid' : getMachineID(), - 'username' : arguments.username, - 'password' : arguments.password, - 'threads' : arguments.threads, - 'osname' : '{0} {1}'.format(platform.system(), platform.release()) - }; - # Make sure we have cutechess installed getCutechess(arguments.server) @@ -632,6 +624,19 @@ def main(): if not os.path.isdir('Engines'): os.mkdir('Engines') + # All workload requests must be tied to a user and a machine. + # We also pass a thread count to inform the server what tests this + # machine can handle. We pass the osname in order to register machines. + # We pass a space seperated string of the engines we are able to compile. + workRequestData = { + 'machineid' : getMachineID(), + 'username' : arguments.username, + 'password' : arguments.password, + 'threads' : arguments.threads, + 'osname' : '{0} {1}'.format(platform.system(), platform.release()), + 'supported' : ' '.join(COMPILERS.keys()), + }; + # Continually pull down and complete workloads while True: try: completeWorkload(workRequestData, arguments) diff --git a/OpenBench/urls.py b/OpenBench/urls.py index 2fe7897..3089a5c 100644 --- a/OpenBench/urls.py +++ b/OpenBench/urls.py @@ -50,9 +50,11 @@ urlpatterns = [ django.urls.path(r'newTest/', OpenBench.views.newTest), # Links for the Client to work with the Server - django.urls.path(r'getFiles/', OpenBench.views.getFiles), - django.urls.path(r'getCompilers/', OpenBench.views.getCompilers), - django.urls.path(r'getWorkload/', OpenBench.views.getWorkload), + django.urls.path(r'clientGetFiles/', OpenBench.views.clientGetFiles), + django.urls.path(r'clientGetBuildInfo/', OpenBench.views.clientGetBuildInfo), + django.urls.path(r'clientGetWorkload/', OpenBench.views.clientGetWorkload), + + # Links for the Client to work with the Server (DEAD) django.urls.path(r'wrongBench/', OpenBench.views.wrongBench), django.urls.path(r'submitNPS/', OpenBench.views.submitNPS), django.urls.path(r'submitResults/', OpenBench.views.submitResults), diff --git a/OpenBench/utils.py b/OpenBench/utils.py index 0627d48..dee2832 100644 --- a/OpenBench/utils.py +++ b/OpenBench/utils.py @@ -251,110 +251,125 @@ def createNewTest(request): return test, None -def getMachine(machineid, username, osname, threads): +def getMachine(machineid, owner, osname, threads): - # Client has no saved machine ID, make a new machine - if machineid == 'None': - machine = Machine() - machine.owner = username - machine.osname = osname - machine.threads = int(threads) - return machine + try: # Create a new or fetch an existing Machine + if machineid == 'None': machine = Machine() + else: machine = Machine.objects.get(id=int(machineid)) + except: return 'Bad Machine' - # Fetch and verify the claimed machine ID - machine = Machine.objects.get(id=machineid) - assert machine.owner == username - assert machine.osname == osname + # Verify that the fetched Machine matches + if machineid != 'None': + if machine.owner != owner: return 'Bad Machine' + if machine.osname != osname: return 'Bad Machine' - # Update to reflect new worload - machine.threads = int(threads) - machine.mnps = 0.00 - machine.save() + # Update the Machine's running status + machine.owner = owner ; machine.osname = osname + machine.threads = int(threads) ; machine.mnps = 0.00 return machine -def getWorkload(machine): +def getResult(test, machine): - # Get a list of all active tests - tests = Test.objects.filter(finished=False) - tests = tests.filter(deleted=False) - tests = list(tests.filter(approved=True)) - - # No tests, error out and let views handle it - if len(tests) == 0: raise Exception('None') - - options = [] # Highest priority with acceptable threads - - # Find our options for workloads - for test in tests: - - # Find Threads for the Dev Engine - tokens = test.devoptions.split(' ') - devthreads = int(tokens[0].split('=')[1]) - - # Find Threads for the Base Engine - tokens = test.baseoptions.split(' ') - basethreads = int(tokens[0].split('=')[1]) - - # Minimum threads to support Dev & Base - threadcnt = max(devthreads, basethreads) - - # Empty list or higher priority found for workable test - if (options == [] or test.priority > highest) and threadcnt <= machine.threads: - highest = test.priority - options = [test] - - # New workable test with the same priority - elif options != [] and test.priority == highest and threadcnt <= machine.threads: - options.append(test) - - # Sum of throughputs, for weighted randomness - total = sum([test.throughput for test in options]) - target = random.randrange(0, total) - - # Finally, select our test with the weighted target - while True: - - # Found test within the target throughput - if target < options[0].throughput: - return options[0] - - # Drop the test from selection - target -= options[0].throughput - options = options[1:] - -def getResult(machine, test): - - # Can find an existing result by test and 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] - # Must make a new one for the machine - machine.save() + # Create a new Result if none is found return Result.objects.create(test=test, machine=machine) -def workloadDictionary(machine, result, test): +def getWorkload(user, request): + + # Extract worker information + machineid = request.POST['machineid'] + owner = request.POST['username' ] + osname = request.POST['osname' ] + threads = request.POST['threads' ] + + # If we don't get a Machine back, there was an error + machine = getMachine(machineid, owner, osname, threads) + if type(machine) == str: return machine + machine.save() + + # Compare supported Machines vs Existing + supported = request.POST['supported'].split() + existing = OPENBENCH_CONFIG['engines'].keys() + + # Filter only to active tests + tests = Test.objects.filter(finished=False).filter(deleted=False) + tests = tests.filter(deleted=False).filter(approved=True) + + # Remove tests that this Machine cannot complete + for engine in existing: + if engine not in supported: + tests = tests.exclude(engine=engine) + + # If we don't get a Test back, there was an error + test = selectWorkload(tests, machine) + if type(test) == str: return test + + # If we don't get a Result back, there was an error + result = getResult(test, machine) + if type(result) == str: return result + + # Success. Update the Machine's status + machine.workload = test; machine.save() + return str(workloadDictionary(test, result, machine)) + +def selectWorkload(tests, machine): + + options = [] # Tests which this Machine may complete + + for test in tests: + + # Skip tests which the Machine lacks the threads to complete + devthreads = int(extractOption(test.devoptions, 'Threads')) + basethreads = int(extractOption(test.baseoptions, 'Threads')) + if max(devthreads, basethreads) > machine.threads: continue + + # First Test or a higher priority Test + if options == [] or test.priority > highest: + highest = test.priority; options = [test] + + # Another Test with an equal priority + elif options != [] and test.priority == highest: + options.append(test) + + if options == []: return 'None' + + target = random.randrange(sum([t.throughput for t in options])) + while True: # Select a random test used weighted randomness + if target < options[0].throughput: return options[0] + target -= options[0].throughput; options = options[1:] + +def workloadDictionary(test, result, machine): + + # 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 - # Worker will send back the id of each model for ease of - # updating. Worker needs test information, as well as the - # specification for both engines. Group the dev and base - # options with the coressponding engine, for easy usage return { - 'machine' : { 'id' : machine.id, }, - 'result' : { 'id' : result.id, }, + + 'machine' : { 'id' : machine.id }, + + 'result' : { 'id' : result.id }, + 'test' : { + 'id' : test.id, 'nps' : OPENBENCH_CONFIG['engines'][test.engine]['nps'], 'build' : OPENBENCH_CONFIG['engines'][test.engine]['build'], 'book' : OPENBENCH_CONFIG['books'][test.bookname], 'timecontrol' : test.timecontrol, 'engine' : test.engine, + 'dev' : { 'id' : test.dev.id, 'name' : test.dev.name, 'source' : test.dev.source, 'protocol' : test.dev.protocol, 'sha' : test.dev.sha, 'bench' : test.dev.bench, 'options' : test.devoptions, }, + 'base' : { 'id' : test.base.id, 'name' : test.base.name, 'source' : test.base.source, 'protocol' : test.base.protocol, @@ -364,6 +379,7 @@ def workloadDictionary(machine, result, test): }, } + def update(request, user): # Parse the data from the worker diff --git a/OpenBench/views.py b/OpenBench/views.py index f1cd167..7b8134b 100644 --- a/OpenBench/views.py +++ b/OpenBench/views.py @@ -420,16 +420,28 @@ def newTest(request): # CLIENT HOOK VIEWS # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # -@csrf_exempt @not_minified_response -def getFiles(request): +def clientGetFiles(request): - # Core Files should be sitting in framework's repo - return HttpResponse(OpenBench.config.OPENBENCH_CONFIG['corefiles']) + # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # + # # + # GET : Return a URL pointing to the location of Cutechess-cli, as well # + # as any DLLs or Shared Object files needed for Cutechess-cli # + # # + # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # + + data = OpenBench.config.OPENBENCH_CONFIG['corefiles'] + return HttpResponse(str(data)) -@csrf_exempt @not_minified_response -def getCompilers(request): +def clientGetBuildInfo(request): + + # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # + # # + # GET : Return a Dictionary of all of the Engines that are present in # + # config.py, as well as the required compilation tools for them # + # # + # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # data = {} # Return all engine-compiler information for engine, config in OpenBench.config.OPENBENCH_CONFIG['engines'].items(): @@ -438,36 +450,17 @@ def getCompilers(request): @csrf_exempt @not_minified_response -def getWorkload(request): +def clientGetWorkload(request): - # Verify that we got a valid login + # Verify the User's credentials user = django.contrib.auth.authenticate( username=request.POST['username'], password=request.POST['password']) if user == None: return HttpResponse('Bad Credentials') - # Create or fetch the Machine - try: machine = OpenBench.utils.getMachine( - request.POST['machineid'], - request.POST['username'], - request.POST['osname'], - request.POST['threads']) - except: return HttpResponse('Bad Machine') + # getWorkload() will verify the integrity of the request + return HttpResponse(OpenBench.utils.getWorkload(user, request)) - # Find an active Test to work on - try: - test = OpenBench.utils.getWorkload(machine) - machine.workload = test - machine.save() - except: - return HttpResponse('None') - - # Create or fetch the Results - try: result = OpenBench.utils.getResult(machine, test) - except: return HttpResponse('None') - - # Send ID's and test information as a string dictionary - return HttpResponse(str(OpenBench.utils.workloadDictionary(machine, result, test))) @csrf_exempt @not_minified_response