Finalize?

This commit is contained in:
andrew committed 2023-05-17 02:05:53 -04:00
1 parent dd0f2ca29f
commit 27e6017bfb
9 files changed
+268 -369

No files matched your search

+1 -1
View File
@@ -38,7 +38,7 @@ REQUIRE_MANUAL_REGISTRATION = True # Disable the public facing registration pag
OPENBENCH_CONFIG = {
# Server Client version control
'client_version' : '7',
'client_version' : '8',
# Generic Error Messages useful to those setting up their own instance
'error' : {
+9 -9
View File
@@ -60,15 +60,15 @@ urlpatterns = [
django.urls.path(r'scripts/', OpenBench.views.scripts),
# Links for the Client to work with the Server
django.urls.path(r'clientGetFiles/', OpenBench.views.clientGetFiles),
django.urls.path(r'clientGetBuildInfo/', OpenBench.views.clientGetBuildInfo),
django.urls.path(r'clientWorkerInfo/', OpenBench.views.clientWorkerInfo),
django.urls.path(r'clientGetWorkload/', OpenBench.views.clientGetWorkload),
django.urls.path(r'clientGetNetwork/<str:sha256>/', 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/<str:sha256>/', 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),
+40 -94
View File
@@ -424,101 +424,61 @@ def get_machine(machineid, user, info):
return machine
def getMachine(machineid, user, osname, threads):
# Create a new Machine if needed
if machineid == 'None':
return Machine(user=user, osname=osname, threads=threads)
# Fetch and verify the requested Machine
try: machine = Machine.objects.get(id=int(machineid))
except: return 'Bad Machine'
if machine.user != user: return 'Bad Machine'
if machine.osname != osname: return 'Bad Machine'
# Update the Machine's running status
machine.threads = threads
machine.mnps = 0.00
return machine
def getResult(test, machine):
# Try to find an already existing Result
results = Result.objects.filter(test=test)
results = list(results.filter(machine=machine))
if results != []: return results[0]
# Create a new Result if none is found
return Result(test=test, machine=machine)
def getWorkload(user, request):
# Extract worker information
machineid = request.POST['machineid']
osname = request.POST['osname' ]
threads = request.POST['threads' ]
# If we don't get a Machine back, there was an error
machine = getMachine(machineid, user, osname, int(threads))
if type(machine) == str: return machine
def get_workload(machine):
# Check to make sure we have a potential workload
tests = get_valid_workloads(machine, request)
if not tests: return 'None'
if not (tests := get_valid_workloads(machine)):
return {}
# Select from valid workloads and create a Result object
test = select_workload(machine, tests)
result = getResult(test, machine)
test = select_workload(machine, tests)
result = Result(test=test, machine=machine)
# Success. Update the Machine's status and save everything
# Update the Machine's status and save everything
machine.workload = test; machine.save(); result.save()
return str(workload_to_dictionary(test, result, machine))
return { 'workload' : workload_to_dictionary(test, result) }
# Purely Helper functions for getWorkload()
# Purely Helper functions for get_workload()
def get_valid_workloads(machine, request):
def get_valid_workloads(machine):
# Skip anything that is not running
tests = get_active_tests()
# Skip engines that the Machine cannot build
# Skip engines that the Machine cannot handle
for engine in OPENBENCH_CONFIG['engines'].keys():
if engine not in request.POST['supported'].split():
if engine not in machine.info['supported']:
tests = tests.exclude(engine=engine)
# Skip engines that the Machine cannot run
for engine, data in OPENBENCH_CONFIG['engines'].items():
for flag in data['build']['cpuflags']:
if flag not in request.POST['cpuflags'].split():
tests = tests.exclude(engine=engine)
# Skip tests with unmet Syzygy requirments
if request.POST['syzygy_wdl'] == 'False':
if not machine.info['syzygy_wdl']:
tests = tests.exclude(syzygy_adj='REQUIRED')
tests = tests.exclude(syzygy_wdl='REQUIRED')
# Skip tests that would waste available Threads or exceed them
ncutechess = int(request.POST['ncutechess'])
options = [x for x in tests if test_maps_onto_thread_count(machine, x, ncutechess)]
threads = machine.info['concurrency']
ncutechess = machine.info['ncutechesses']
hyperthreads = machine.info['physical_cores'] < threads
options = [x for x in tests if
test_maps_onto_thread_count(x, threads, ncutechess, hyperthreads)]
# Finally refine for tests of the highest priority
if not options: return []
highest_prio = max(options, key=lambda x: x.priority).priority
return [test for test in options if test.priority == highest_prio]
def test_maps_onto_thread_count(machine, test, ncutechess):
def test_maps_onto_thread_count(test, threads, ncutechess, hyperthreads):
dev_threads = int(extractOption(test.devoptions, 'Threads'))
base_threads = int(extractOption(test.baseoptions, 'Threads'))
# Each individual cutechess copy must have access to sufficient Threads
if max(dev_threads, base_threads) > (machine.threads / ncutechess):
if max(dev_threads, base_threads) > (threads / ncutechess):
return False
# Intentional Thread Imbalance, or evenly distributed Threads
return dev_threads != base_threads or (machine.threads / ncutechess) % dev_threads == 0
# Intentional Thread Imbalance, or real cores, or evenly distributed
return dev_threads != base_threads or not hyperthreads or (threads / ncutechess) % dev_threads == 0
def select_workload(machine, tests, variance=0.25):
@@ -526,7 +486,7 @@ def select_workload(machine, tests, variance=0.25):
table = { test : 0 for test in tests }
for m in getRecentMachines():
if m.workload in tests and m != machine:
table[m.workload] = table[m.workload] + m.threads
table[m.workload] = table[m.workload] + m.info['concurrency']
# Find the tests most deserving of resources currently
ratios = [table[test] / test.throughput for test in tests]
@@ -545,36 +505,22 @@ def select_workload(machine, tests, variance=0.25):
# Fallback to simply doing the least attention given test
return tests[random.choice(lowest_idxs)]
def workload_to_dictionary(test, result, machine):
def workload_to_dictionary(test, result):
# Convert the workload into a Dictionary to be used by the Client.
# The Client must know his Machine ID, his Result ID, and his Test
# ID. Also, all information about the Test and the associated engines
return {
return json.dumps({
'machine' : { 'id' : machine.id },
'result' : { 'id' : result.id },
'engine' : {
'private' : OPENBENCH_CONFIG['engines'][test.engine]['private']
},
'test' : {
'result' : { 'id' : result.id },
'test' : {
'id' : test.id,
'engine' : test.engine,
'timecontrol' : test.timecontrol,
'syzygy_wdl' : test.syzygy_wdl,
'syzygy_adj' : test.syzygy_adj,
'win_adj' : test.win_adj,
'draw_adj' : test.draw_adj,
'report_rate' : test.report_rate,
'workload_size' : test.workload_size,
'nps' : OPENBENCH_CONFIG['engines'][test.engine]['nps'],
'build' : OPENBENCH_CONFIG['engines'][test.engine]['build'],
'book' : OPENBENCH_CONFIG['books'][test.bookname],
@@ -593,28 +539,28 @@ def workload_to_dictionary(test, result, machine):
'network' : test.basenetwork,
},
},
})
}
def updateTest(request, user):
def update_test(request, machine):
# New results from the Worker
wins = int(request.POST['wins'])
losses = int(request.POST['losses'])
draws = int(request.POST['draws'])
crashes = int(request.POST['crashes'])
wins = int(request.POST['wins' ])
losses = int(request.POST['losses' ])
draws = int(request.POST['draws' ])
crashes = int(request.POST['crashes' ])
timeloss = int(request.POST['timeloss'])
games = wins + losses + draws
# Worker knows where to save the results
machineid = int(request.POST['machineid'])
resultid = int(request.POST['resultid'])
testid = int(request.POST['testid'])
machineid = int(request.POST['machine_id'])
resultid = int(request.POST['result_id' ])
testid = int(request.POST['test_id' ])
# Prevent updating a finished test
test = Test.objects.get(id=testid)
if test.finished or test.deleted:
return 'Stop'
return { 'stop' : True }
# Tally up the updated WLD stats
swins = test.wins + wins
@@ -642,11 +588,11 @@ def updateTest(request, user):
sprt = 0.0 # Hack to "update" the currentllr
# Update total games played by the Player
Profile.objects.filter(user=user).update(games=F('games') + games)
Profile.objects.get(user=user).save()
Profile.objects.filter(user=machine.user).update(games=F('games') + games)
Profile.objects.get(user=machine.user).save()
# Update the datetime in the Machine
Machine.objects.get(id=machineid).save()
machine.save()
# Update individual Result entry for the Player
Result.objects.filter(id=resultid).update(
@@ -665,4 +611,4 @@ def updateTest(request, user):
# Force a refresh of the updated field when finished
if finished: Test.objects.get(id=testid).save()
return ['None', 'Stop'][finished]
return [{}, {'stop' : True}][finished]
+95 -114
View File
@@ -31,7 +31,6 @@ from OpenBench.models import *
from django.contrib.auth.models import User
from OpenSite.settings import MEDIA_ROOT
from ipware import get_client_ip
from wsgiref.util import FileWrapper
from django.db.models import F
from django.http import HttpResponse, FileResponse, JsonResponse
@@ -88,28 +87,6 @@ def authenticate(request, requireEnabled=False):
return user
def authenticate_client(request):
# Fetch the Machine associated with the Client Request
try: machine = Machine.objects.get(id=int(request.POST['machineid']))
except: raise Exception('Bad Machine')
# Try to compare the saved IP address of the machine
client_ip, _ = get_client_ip(request)
# Authenticate via comparing current to recent IP addresses ( Fast )
if client_ip and machine.lastaddr == str(client_ip):
return User.objects.get(username=request.POST['username']), machine
# Authenticate the User associated with the Client Request ( Slow )
try: user = authenticate(request, True)
except: raise Exception('Bad Credentials')
# After Authentication, we may save the Client's IP Address for later
if client_ip: machine.lastaddr = str(client_ip); machine.save()
return user, machine
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
# ADMINISTRATIVE VIEWS #
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
@@ -626,16 +603,36 @@ def scripts(request):
# CLIENT HOOK VIEWS #
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
@not_minified_response
def clientGetFiles(request):
def client_verify_worker(request):
## Returns the machine, or None. Returns a JsonResponse or None.
## Presence of a JsonResponse indicates a failure to verify
# Get the machine, assuming it exists
try: machine = Machine.objects.get(id=int(request.POST['machine_id']))
except: return None, JsonResponse({ 'error' : 'Bad Machine Id' })
# Ensure the Client is using the same version as the Server
if machine.info['client_ver'] != OpenBench.config.OPENBENCH_CONFIG['client_version']:
expected_ver = OpenBench.config.OPENBENCH_CONFIG['client_version']
return machine, JsonResponse({ 'error' : 'Bad Client Version: Expected %s' % (expected_ver)})
# Use the secret token as our soft verification
if machine.secret != request.POST['secret']:
return machine, JsonResponse({ 'error' : 'Invalid Secret Token' })
return machine, None
@csrf_exempt
def client_get_files(request):
## Location of static compile of Cutechess for Windows and Linux.
## OpenBench does not serve these files, but points to a repo ideally.
return HttpResponse(OpenBench.config.OPENBENCH_CONFIG['corefiles'])
return JsonResponse( {'location' : OpenBench.config.OPENBENCH_CONFIG['corefiles'] })
@not_minified_response
def clientGetBuildInfo(request):
@csrf_exempt
def client_get_build_info(request):
## Information pulled from the config about how to build each engine.
## Toss in a private flag as well to indicate the need for Github Tokens.
@@ -643,12 +640,10 @@ def clientGetBuildInfo(request):
data = {}
for engine, config in OpenBench.config.OPENBENCH_CONFIG['engines'].items():
data[engine] = config['build']
data[engine]['private'] = config['private']
return JsonResponse(data)
@csrf_exempt
@not_minified_response
def clientWorkerInfo(request):
def client_worker_info(request):
# Verify the User's credentials
try: user = authenticate(request, True)
@@ -663,45 +658,47 @@ def clientWorkerInfo(request):
if not machine:
return JsonResponse({ 'error' : 'Bad Machine Id' })
# Save the machine's latest information
# Save the machine's latest information and Secret Token for this session
machine.info = info
machine.secret = secrets.token_hex(32)
# Tag engines that the Machine can build and/or run with binaries
machine.info['supported'] = []
for engine, data in OpenBench.config.OPENBENCH_CONFIG['engines'].items():
# Must have all CPU flags, for both Public and Private engines
if any([flag not in machine.info['cpu_flags'] for flag in data['build']['cpuflags']]):
continue
# Private engines must have, or think they have, a Git Token
if data['private'] and engine not in machine.info['tokens']:
continue
# Public engines must have a compiler of a sufficient version
if not data['private'] and engine not in machine.info['compilers'].keys():
continue
# All requirements are met, and this Machine can play with the given engine
machine.info['supported'].append(engine)
# Finish up
machine.save()
# Pass back the Machine Id, and Secret Token for this session
return JsonResponse({ 'machine_id' : machine.id, 'secret' : machine.secret })
@csrf_exempt
@not_minified_response
def clientGetWorkload(request):
def client_get_workload(request):
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
# #
# POST : Return a Dictionary of data in order to complete a workload. If #
# there are no tests for the User, 'None' will be returned. If we #
# cannot authenticate the User, 'Bad Credentials' is returned. If #
# the posted Machine does not belong the the User, 'Bad Machine' #
# is returned. #
# #
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
# Pass along any error messages if they appear
machine, response = client_verify_worker(request)
if response != None: return response
# Verify the User's credentials
try: user = authenticate(request, True)
except UnableToAuthenticate: return HttpResponse('Bad Credentials')
# Make sure the Client passed its version number
if 'version' not in request.POST:
return HttpResponse('Bad Client Version')
# Make sure the Client & Server version numbers match
if request.POST['version'] != OpenBench.config.OPENBENCH_CONFIG['client_version']:
return HttpResponse('Bad Client Version')
# getWorkload() will verify the integrity of the request
return HttpResponse(OpenBench.utils.getWorkload(user, request))
# Contains keys 'workload', otherwise none
return JsonResponse(OpenBench.utils.get_workload(machine))
@csrf_exempt
@not_minified_response
def clientGetNetwork(request, sha256):
def client_get_network(request, sha256):
# Verify the User's credentials
try: django.contrib.auth.login(request, authenticate(request, True))
@@ -711,8 +708,7 @@ def clientGetNetwork(request, sha256):
return networks(request, action='DOWNLOAD', sha256=sha256, client=True)
@csrf_exempt
@not_minified_response
def clientWrongBench(request):
def client_wrong_bench(request):
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
# #
@@ -722,99 +718,84 @@ def clientWrongBench(request):
# #
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
# Authenticate the User/Machine combination
try: user, machine = authenticate_client(request)
except Exception as error: return HttpResponse(str(error))
# Pass along any error messages if they appear
machine, response = client_verify_worker(request)
if response != None: return response
# Find and stop the test with the bad bench
if int(request.POST['wrong']) != 0:
test = Test.objects.get(id=int(request.POST['testid']))
test = Test.objects.get(id=int(request.POST['test_id']))
test.finished = True; test.save()
# Collect information on the Error
wrong = request.POST['wrong']
correct = request.POST['correct']
wrong = int(request.POST['wrong'])
correct = int(request.POST['correct'])
name = request.POST['engine']
# Format a nice Error message
message = 'Got {0} Expected {1} for {2}'
message = message.format(wrong, correct, name)
# Log the error into the Events table
LogEvent.objects.create(
author = user.username,
summary = message,
author = machine.user.username,
summary = 'Got %d Expected %d for %s' % (wrong, correct, name),
log_file = '',
machine_id = int(request.POST['machineid']),
test_id = int(request.POST['testid']))
machine_id = int(request.POST['machine_id']),
test_id = int(request.POST['test_id']))
return HttpResponse('None')
return JsonResponse({})
@csrf_exempt
@not_minified_response
def clientSubmitNPS(request):
def client_submit_nps(request):
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
# #
# POST : Report the speed of the engines in the currently running Test #
# for the User and his Machine. We save this value to display #
# #
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
# Pass along any error messages if they appear
machine, response = client_verify_worker(request)
if response != None: return response
# Authenticate the User/Machine combination
try: user, machine = authenticate_client(request)
except Exception as error: return HttpResponse(str(error))
# Update the NPS and return 'None' to signal no errors
# Update the NPS counter for the GUI views
machine.mnps = float(request.POST['nps']) / 1e6; machine.save()
return HttpResponse('None')
# Pass back an empty JSON response
return JsonResponse({})
@csrf_exempt
@not_minified_response
def clientSubmitError(request):
def client_submit_error(request):
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
# #
# POST : Report en Engine error to the server. This could be a crash, a #
# timeloss, a disconnect, or an illegal move. Log the Error into #
# the Events table. #
# #
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
## Report an error when working on test. This could be one three kinds.
## 1. Error building the engine. Does not compile, for whatever reason.
## 2. Error getting the artifacts. Does not exist, lacks credentials.
## 3. Error during actual gameplay. Timeloss, Disconnect, Crash, etc.
# Authenticate the User/Machine combination
try: user, machine = authenticate_client(request)
except Exception as error: return HttpResponse(str(error))
# Pass along any error messages if they appear
machine, response = client_verify_worker(request)
if response != None: return response
# Flag the Test as having an error except for time losses
test = Test.objects.get(id=int(request.POST['testid']))
test = Test.objects.get(id=int(request.POST['test_id']))
if 'loses on time' not in request.POST['error']:
test.error = True; test.save()
# Log the Error into the Events table
event = LogEvent.objects.create(
author = user.username,
author = machine.user.username,
summary = request.POST['error'],
log_file = '',
machine_id = int(request.POST['machineid']),
test_id = int(request.POST['testid']))
machine_id = int(request.POST['machine_id']),
test_id = int(request.POST['test_id']))
# Save the Logs to /Media/ to be viewed later
logfile = ContentFile(request.POST['logs'])
FileSystemStorage().save('event%d.log' % (event.id), logfile)
event.log_file = 'event%d.log' % (event.id); event.save()
return HttpResponse('None')
return JsonResponse({})
@csrf_exempt
@not_minified_response
def clientSubmitResults(request):
def client_submit_results(request):
# Authenticate the User/Machine combination
try: user, machine = authenticate_client(request)
except Exception as error: return HttpResponse(str(error))
# Pass along any error messages if they appear
machine, response = client_verify_worker(request)
if response != None: return response
# updateTest() will return 'None' or 'Stop'
return HttpResponse(OpenBench.utils.updateTest(request, user))
# Returns {}, or { 'stop' : True }
return JsonResponse(OpenBench.utils.update_test(request, machine))
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
# BUSINESS VIEWS #