diff --git a/OpenBench/static/style.css b/OpenBench/static/style.css index c9b416c..866cec5 100644 --- a/OpenBench/static/style.css +++ b/OpenBench/static/style.css @@ -237,11 +237,9 @@ a:link, a:visited, a:hover, a:active { } #error { - background-color: #ED7676; + background-color: #EE7676; padding: 8px; text-align: center; - font-weight: bold; - font-size: 20px; } #content form h3 { diff --git a/OpenBench/urls.py b/OpenBench/urls.py index ea83fd4..e2e490a 100644 --- a/OpenBench/urls.py +++ b/OpenBench/urls.py @@ -39,9 +39,9 @@ urlpatterns = [ # 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'machines/', OpenBench.views.machines), - django.urls.path(r'eventLog/', OpenBench.views.eventLog), - django.urls.path(r'eventLog//', OpenBench.views.eventLog), # Links for viewing and managing tests (maintain Legacy) django.urls.path(r'test//', OpenBench.views.test), diff --git a/OpenBench/utils.py b/OpenBench/utils.py index 3406a3d..d4c9a02 100644 --- a/OpenBench/utils.py +++ b/OpenBench/utils.py @@ -18,19 +18,35 @@ # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # -import math, requests, random, datetime +import math, re, requests, random, datetime import OpenBench.models +import django.utils.timezone + from django.utils import timezone from django.db.models import F from django.contrib.auth import authenticate -from django.utils.timezone import utc from OpenBench.config import * from OpenBench.models import Engine, Profile, Machine, Result, Test +def pathjoin(*args): + return "/".join([f.lstrip("/").rstrip("/") for f in args]) + "/" + +def extractOption(options, option): + + match = re.search('(?<={0}=")[^"]*'.format(option), options) + if match: return match.group() + + match = re.search('(?<={0}=\')[^\']*'.format(option), options) + if match: return match.group() + + match = re.search('(?<={0}=)[^ ]*'.format(option), options) + if match: return match.group() + + def getPendingTests(): pending = OpenBench.models.Test.objects.filter(approved=False) pending = pending.exclude(finished=True) @@ -48,22 +64,24 @@ def getCompletedTests(): completed = completed.exclude(deleted=True) return completed.order_by('-updated') +def getRecentMachines(minutes=15): + target = datetime.datetime.utcnow() + target = target.replace(tzinfo=django.utils.timezone.utc) + target = target - datetime.timedelta(minutes=minutes) + return Machine.objects.filter(updated__gte=target) + def getMachineStatus(username=None): - # Filter for machines used in the last 10 minutes - target = datetime.datetime.utcnow().replace(tzinfo=utc) \ - - datetime.timedelta(minutes=10) - machines = Machine.objects.filter(updated__gte=target) + machines = getRecentMachines() - # Filter for user specific views - if username != None: machines = machines.filter(owner=username) + if username != None: + machines = machines.filter(owner=username) - # Extract stat information from workers 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)) -def getPagedContent(content, page, pagelen, url): +def getPaging(content, page, url, pagelen=25): start = max(0, pagelen * (page - 1)) end = min(len(content), pagelen * page) @@ -92,68 +110,113 @@ def getPagedContent(content, page, pagelen, url): return content[start:end], context -def pagingContext(page, pageLength, items, url): - # Tests within the given page - start = page * pageLength - end = min(start + pageLength, items) +def getEngine(name, source, proto, sha, bench): - # Get page numbers near the current page - pagenum = 1 + math.ceil(items / pageLength) - temp = list(range(1, min(4, pagenum))) - temp.extend(range(pagenum-1, pagenum-4, -1)) - temp.extend(range(max(0, page-2), min(pagenum-1, page+3))) - temp = list(set(temp)) - temp.sort() + engine = Engine.objects.filter( + name=name, source=source, + protocol=proto, sha=sha, bench=bench) - # Fill in gaps with an ellipsis, throw out negatives - pages = [] - for f in range(len(temp)): - if temp[f] < 1: continue - pages.append(temp[f]) - if f < len(temp) - 1 and temp[f] != temp[f+1] - 1: - pages.append("...") + if engine.first() != None: + return engine.first() - # Create context dictionary for paging setup - return { - "url" : url, - "page" : page, - "pages" : pages, - "prev" : max(1, page - 1), - "next" : max(1, min(page + 1, pagenum - 1)), - } + return Engine.objects.create( + name=name, source=source, + protocol=proto, sha=sha, bench=bench) -def getSourceLocation(branch, repo): +def verifyNewTest(request): + + errors = [] + + def verifyInteger(field, fieldName): + if not request.POST[field].isnumeric(): + errors.append('{0} is not an Integer'.format(fieldName)) + + def verifyFloating(field, fieldName): + if not request.POST[field].replace('.','').isnumeric(): + errors.append('{0} is not a Float'.format(fieldName)) + elif request.POST[field].count('.') > 1: + errors.append('{0} is not a Float'.format(fieldName)) + + def verifyLessThan(field, fieldName, value, valueName): + if not float(request.POST[field]) < value: + errors.append('{0} is not less than {1}'.format(fieldName, valueName)) + + 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 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 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)) + + verifications = [ + (verifyInteger, 'devbench', 'Dev Bench'), + (verifyInteger, 'basebench', 'Base Bench'), + (verifyInteger, 'priority', 'Priority'), + (verifyInteger, 'throughput', 'Throughput'), + (verifyFloating, 'elolower', 'Elo Lower'), + (verifyFloating, 'eloupper', 'Elo Upper'), + (verifyFloating, 'alpha', 'Alpha'), + (verifyFloating, 'beta', 'Beta'), + (verifyLessThan, 'alpha', 'Alpha', 1.00, '1'), + (verifyLessThan, 'beta', 'Beta', 1.00, '1'), + (verifyGreaterThan, 'alpha', 'Alpha', 0.00, '0'), + (verifyGreaterThan, 'beta', 'beta', 0.00, '0'), + (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'), + ] + + for verification in verifications: + try: verification[0](*verification[1:]) + except: pass + + return errors + +def getBranchInformation(repo, branch, errors): + + target = repo.replace('github.com', 'api.github.com/repos') + target = pathjoin(target, 'branches', branch) try: - target = repo.replace('github.com', 'api.github.com/repos') - target = target + 'branches/' + branch - data = requests.get(target).json() - source = repo + 'archive/' + data['commit']['commit']['tree']['sha'] + '.zip' - sha = data['commit']['sha'] - return (sha, source) + data = requests.get(target.rstrip('/')).json() + treesha = data['commit']['commit']['tree']['sha'] + return (data['commit']['sha'], pathjoin(repo, 'archive', treesha, '.zip')) except: - raise Exception('Unable to find branch ({0})'.format(branch)) + errors.append("Branch {0} could not be found".format(branch)) + return (None, None) -def newTest(request): +def createNewTest(request): + + errors = verifyNewTest(request) + if errors != []: return None, errors + + devname = request.POST['devbranch'] + basename = request.POST['basebranch'] + devbench = int(request.POST['devbench']) + basebench = int(request.POST['basebench']) + protocol = OPENBENCH_CONFIG['engines'][request.POST['enginename']]['proto'] + + errors = [] + devsha, devsource = getBranchInformation(request.POST['source'], devname, errors) + basesha, basesource = getBranchInformation(request.POST['source'], basename, errors) + if errors != []: return None, errors - # New Test saved after parsing test = Test() - test.author = request.user.username - test.engine = request.POST['enginename'] - - # Extract Development Fields - devname = request.POST['devbranch'] - devbench = int(request.POST['devbench']) - devprotocol = OPENBENCH_CONFIG['engines'][test.engine]['proto'] - - # Extract Base Fields - basename = request.POST['basebranch'] - basebench = int(request.POST['basebench']) - baseprotocol = OPENBENCH_CONFIG['engines'][test.engine]['proto'] - - # Extract test configuration + test.author = request.user.username + test.engine = request.POST['enginename'] test.source = request.POST['source'] test.devoptions = request.POST['devoptions'] test.baseoptions = request.POST['baseoptions'] @@ -165,38 +228,20 @@ def newTest(request): test.eloupper = float(request.POST['eloupper']) test.alpha = float(request.POST['alpha']) test.beta = float(request.POST['beta']) + test.lowerllr = math.log(test.beta / (1.0 - test.alpha)) + test.upperllr = math.log((1.0 - test.beta) / test.alpha) + test.dev = getEngine(devname, devsource, protocol, devsha, devbench) + test.base = getEngine(basename, basesource, protocol, basesha, basebench) + test.save() - # Compute LLR cutoffs - test.lowerllr = math.log(test.beta / (1.0 - test.alpha)) - test.upperllr = math.log((1.0 - test.beta) / test.alpha) - - # Build or fetch the Development version - devsha, devsource = getSourceLocation(devname, test.source) - test.dev = getEngine(devname, devsource, devprotocol, devsha, devbench) - - # Build or fetch the Base version - basesha, basesource = getSourceLocation(basename, test.source) - test.base = getEngine(basename, basesource, baseprotocol, basesha, basebench) - - # Track number of tests by this user profile = Profile.objects.get(user=request.user) profile.tests += 1 profile.save() - # Nothing seems to have gone wrong - test.save() - return test + return test, None -def getEngine(name, source, protocol, sha, bench): - # Engine may already exist, which is okay - try: return Engine.objects.get(name=name, source=source, protocol=protocol, sha=sha, bench=bench) - except: pass - # Build new Engine - return Engine.objects.create( - name=name, source=source, - protocol=protocol, sha=sha, bench=bench) def getMachine(machineid, username, osname, threads): diff --git a/OpenBench/views.py b/OpenBench/views.py index 084d607..01112f0 100644 --- a/OpenBench/views.py +++ b/OpenBench/views.py @@ -18,52 +18,43 @@ # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # -#from django.shortcuts import render as djangoRender - import django.http import django.shortcuts import django.contrib.auth -from django.db.models import F -from django.http import HttpResponse, HttpResponseRedirect +import OpenBench.config +import OpenBench.utils + +from OpenBench.models import * from django.contrib.auth.models import User -from django.contrib.auth.decorators import login_required + +from django.db.models import F +from django.http import HttpResponse from django.views.decorators.csrf import csrf_exempt -from django.utils.timezone import utc from htmlmin.decorators import not_minified_response -from OpenBench.config import * -from OpenBench.models import LogEvent, Engine, Profile -from OpenBench.models import Machine, Result, Test -from OpenBench.utils import pagingContext - -import OpenBench.utils, datetime - def render(request, template, data={}): - # Always provide the basic configuration - data.update({'config' : OPENBENCH_CONFIG}) + template = 'OpenBench/{0}'.format(template) + + data.update({'config' : OpenBench.config.OPENBENCH_CONFIG}) if request.user.is_authenticated: - # Provide user information when possible - profile = Profile.objects.filter(user=request.user).first() - data.update({'config' : OPENBENCH_CONFIG, 'profile' : profile}) + profile = Profile.objects.filter(user=request.user) + data.update({'profile' : profile.first()}) - # Warn Users that they need to be enabled - if profile and not profile.enabled: - data.update({'error' : OPENBENCH_CONFIG['error']['disabled']}) + if profile.first() and not profile.first().enabled: + data.update({'error' : data['config']['error']['disabled']}) - # Warn any non-OpenBench users made by some means - if request.user.is_authenticated and not profile: - data.update({'error' : OPENBENCH_CONFIG['error']['fakeuser']}) + if request.user.is_authenticated and not profile.first(): + data.update({'error' : data['config']['error']['fakeuser']}) - # Wrapper to simplify django's rendering function - return django.shortcuts.render(request, 'OpenBench/{0}'.format(template), data) + return django.shortcuts.render(request, template, data) # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # -# Administrative Views # +# ADMINISTRATIVE VIEWS # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # def register(request): @@ -155,10 +146,10 @@ def profile(request): # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # if not request.user.is_authenticated: - return django.http.HttpResponseRedirect('/index/') + return django.http.HttpResponseRedirect('/login/') if request.method == 'GET': - return render(request, 'profile.html', {}) + return render(request, 'profile.html') profile = Profile.objects.filter(user=request.user) profile.update(engine=request.POST['engine'], repo=request.POST['repo']) @@ -178,7 +169,7 @@ def profile(request): # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # -# Test List Views # +# TEST LIST VIEWS # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # def index(request, page=1, error=''): @@ -199,8 +190,7 @@ def index(request, page=1, error=''): active = OpenBench.utils.getActiveTests() completed = OpenBench.utils.getCompletedTests() - completed, paging = OpenBench.utils.getPagedContent( - completed, page, 25, 'index'.format()) + completed, paging = OpenBench.utils.getPaging(completed, page, 'index') data = { 'error' : error, 'pending' : pending, @@ -223,8 +213,7 @@ def greens(request, page=1): # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # completed = OpenBench.utils.getCompletedTests().filter(passed=True) - completed, paging = OpenBench.utils.getPagedContent( - completed, page, 25, 'greens'.format()) + completed, paging = OpenBench.utils.getPaging(completed, page, 'greens') data = {'completed' : completed, 'paging' : paging} return render(request, 'index.html', data) @@ -243,7 +232,7 @@ def search(request): if request.method == 'GET': return render(request, 'search.html', {}) - tests = Test.objects.all() + tests = Test.objects.all().order_by('-updated') if request.POST['engine'] != '': tests = tests.filter(engine=request.POST['engine']) @@ -268,7 +257,7 @@ def search(request): keywords = ['(?i)' + f.upper() for f in request.POST['keywords'].split()] tests = tests.filter(dev__name__regex=r'{0}'.format('|'.join(keywords))) - return render(request, 'search.html', {'tests' : tests.order_by('-updated')}) + return render(request, 'search.html', {'tests' : tests}) def user(request, username, page=1): @@ -288,8 +277,8 @@ def user(request, username, page=1): active = OpenBench.utils.getActiveTests().filter(author=username) completed = OpenBench.utils.getCompletedTests().filter(author=username) - completed, paging = OpenBench.utils.getPagedContent( - completed, page, 25, 'user/{0}'.format(username)) + url = 'user/{0}'.format(username) + completed, paging = OpenBench.utils.getPaging(completed, page, url) data = { 'pending' : pending, 'active' : active, @@ -299,68 +288,65 @@ def user(request, username, page=1): return render(request, 'index.html', data) + # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # -# # +# GENERAL DATA TABLE VIEWS # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # def users(request): - # Build context dictionary for template - data = {'profiles' : Profile.objects.order_by('-games', '-tests', '-enabled')} + # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # + # # + # 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. # + # # + # POST : 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. # + # # + # POST : 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, paging = OpenBench.utils.getPaging(events, page, 'events') + + data = {'events' : events, 'paging' : paging}; + return render(request, 'events.html', data) + def machines(request): - # Build context dictionary for machine template with machines updated recently - target = datetime.datetime.utcnow().replace(tzinfo=utc) - datetime.timedelta(minutes=10) - data = {'machines' : Machine.objects.filter(updated__gte=target)} + # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # + # # + # GET : Return information about all of the machines that have been # + # active on the Framework within the last fifteen minutes # + # # + # POST : Return information about all of the machines that have been # + # active on the Framework within the last fifteen minutes # + # # + # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # + + data = {'machines' : OpenBench.utils.getRecentMachines()} return render(request, 'machines.html', data) -def eventLog(request, page=1, pageLength=24): - # Choose events within the given page, if any - events = LogEvent.objects.all().order_by('-id') - items = len(events) - start = (page - 1) * pageLength - end = page * pageLength - start = max(0, min(start, items)) - end = max(0, min(end, items)) - paging = pagingContext(page, pageLength, items, 'eventLog') - - # Build context dictionary for event log template - data = { - 'events': events[start:end], - 'paging': paging - } - - return render(request, 'eventLog.html', data) - -@login_required(login_url='/login/') -def newTest(request): - - # User trying to view the new test page - if request.method == 'GET': - return render(request, 'newTest.html', {}) - - try: - # Throw out non-approved / disabled users - if not Profile.objects.get(user=request.user).enabled: - raise Exception('Account not Enabled') - - # Create test and verify fields - test = OpenBench.utils.newTest(request) - - # Log the test creation - LogEvent.objects.create( - data='Created Test', - author=request.user.username, - test=test) - - return HttpResponseRedirect('/index/') - - # Bad data, kick back to index with error - except Exception as error: - return index(request, error=str(error)) +# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # +# TEST MANAGEMENT VIEWS # +# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # def test(request, id, action=None): @@ -386,7 +372,11 @@ def test(request, id, action=None): 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') - return render(request, 'test.html', {'test' : test, 'results': results}) + data = {'test' : test, 'results': results} + return render(request, 'test.html', data) + + if not request.user.is_authenticated: + return django.http.HttpResponseRedirect('/login/') user = request.user test = Test.objects.get(id=id) @@ -395,8 +385,9 @@ def test(request, id, action=None): if not profile.approver and test.author != profile.user.username: return django.http.HttpResponseRedirect('/index/') - if action == 'APPROVE' and test.author == user.username and not user.is_superuser: - return django.http.HttpResponseRedirect('/index/') + if action == 'APPROVE': + if test.author == user.username and not user.is_superuser: + return django.http.HttpResponseRedirect('/index/') if action == 'APPROVE': test.approved = True; test.save() if action == 'RESTART': test.finished = False; test.save() @@ -412,12 +403,52 @@ def test(request, id, action=None): LogEvent.objects.create(data=action, author=user.username, test=test) 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 not request.user.is_authenticated: + return django.http.HttpResponseRedirect('/login/') + + if not Profile.objects.get(user=request.user).enabled: + return django.http.HttpResponseRedirect('/index/') + + if request.method == 'GET': + return render(request, 'newTest.html') + + test, errors = OpenBench.utils.createNewTest(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)) + + username = request.user.username + LogEvent.objects.create(data="CREATE", author=username, test=test) + return django.http.HttpResponseRedirect('/index/') + + +# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # +# CLIENT HOOK VIEWS # +# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # + @csrf_exempt @not_minified_response def getFiles(request): # Core Files should be sitting in framework's repo - return HttpResponse(OPENBENCH_CONFIG['corefiles']) + return HttpResponse(OpenBench.config.OPENBENCH_CONFIG['corefiles']) @csrf_exempt @not_minified_response diff --git a/Templates/OpenBench/base.html b/Templates/OpenBench/base.html index 1fe6997..028a90a 100644 --- a/Templates/OpenBench/base.html +++ b/Templates/OpenBench/base.html @@ -18,7 +18,7 @@ {% if error %}
- {{error}} +
{{error}}
{% endif %} @@ -46,8 +46,8 @@ diff --git a/Templates/OpenBench/eventLog.html b/Templates/OpenBench/events.html similarity index 100% rename from Templates/OpenBench/eventLog.html rename to Templates/OpenBench/events.html