Files
OpenBench/OpenBench/pipeline_views.py
T

591 lines
22 KiB
Python

# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
# #
# OpenBench is a chess engine testing framework authored by Andrew Grant. #
# <https://github.com/AndyGrant/OpenBench> <andrew@grantnet.us> #
# #
# OpenBench is free software: you can redistribute it and/or modify #
# it under the terms of the GNU General Public License as published by #
# the Free Software Foundation, either version 3 of the License, or #
# (at your option) any later version. #
# #
# OpenBench is distributed in the hope that it will be useful, #
# but WITHOUT ANY WARRANTY; without even the implied warranty of #
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the #
# GNU General Public License for more details. #
# #
# You should have received a copy of the GNU General Public License #
# along with this program. If not, see <http://www.gnu.org/licenses/>. #
# #
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
# The Pipeline pages: a list, the page of one Pipeline, and the page of one run.
#
# Who may do what, decided in one place ( can_manage ) and nowhere else:
# - Anybody with an enabled account may look at Pipelines and their runs
# - Only the author of a Pipeline, or an Approver, may start, pause, resume,
# or delete it, or cancel one of its runs
#
# Everything that changes something is a POST, which Django checks the CSRF token
# of, and takes no input from the request at all except which object it is for.
# Every decision, allowed or refused, leaves an event behind.
import OpenBench.pipeline_graph as graphs
import OpenBench.pipeline_layout as drawing
import OpenBench.pipelines
import OpenBench.views
import copy
import json
from django.http import JsonResponse
from django.views.decorators.http import require_POST
from OpenBench.models import LogEvent, Pipeline, PipelineRun, Profile, StepRun, Test
STATUS_LABELS = {
'QUEUED' : 'Waiting', 'LAUNCHING' : 'Starting', 'RUNNING' : 'Running',
'PASSED' : 'Passed', 'FAILED' : 'Failed', 'STOPPED' : 'Stopped',
'ERROR' : 'Could not start', 'COMPLETED' : 'Finished', 'CANCELLED' : 'Cancelled',
}
STATUS_BADGES = {
'QUEUED' : 'badge-muted', 'LAUNCHING' : 'badge-muted', 'RUNNING' : 'badge-info',
'PASSED' : 'badge-ok', 'FAILED' : 'badge-bad', 'STOPPED' : 'badge-warn',
'ERROR' : 'badge-bad', 'COMPLETED' : 'badge-ok', 'CANCELLED' : 'badge-warn',
}
WORKLOAD_PATHS = { 'TEST' : 'test', 'TUNE' : 'tune', 'DATAGEN' : 'datagen' }
WHEN = {
'passed' : 'it passes', 'failed' : 'it fails',
'stopped' : 'it is stopped', 'any' : 'it ends',
}
KIND_LABELS = { 'TEST' : 'Test', 'TUNE' : 'Tune', 'DATAGEN' : 'Datagen' }
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
# PERMISSIONS #
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
def viewer(request):
""" The Profile of whoever is asking, if they are logged in and enabled """
if not request.user.is_authenticated:
return None
profile = Profile.objects.select_related('user').filter(user=request.user).first()
return profile if profile and profile.enabled else None
def can_manage(profile, pipeline):
""" The one rule for changing a Pipeline or its runs. Closed by default """
if profile is None or not profile.enabled:
return False
return bool(profile.approver) or profile.user.username == pipeline.author
def _audit(username, summary):
LogEvent.objects.create(author=username, summary=summary[:128], log_file='', test_id=0)
def _turn_away(request, profile, pipeline_id=None, action=''):
""" Anonymous visitors go to log in. People who are logged in, but not
allowed, are told so, and it is written down. """
if not request.user.is_authenticated:
return OpenBench.views.redirect(request, '/login/', error=OpenBench.views.ERROR_MESSAGES['requires_login'])
if profile is None:
return OpenBench.views.redirect(request, '/index/', error=OpenBench.views.ERROR_MESSAGES['disabled'])
if pipeline_id is not None:
_audit(profile.user.username, 'PIPELINE #%d %s REFUSED' % (pipeline_id, action.upper()))
return OpenBench.views.redirect(request, '/pipelines/', error='Only the author of a pipeline, or an approver, can do that')
def _missing(request):
return OpenBench.views.redirect(request, '/pipelines/', error='That pipeline does not exist, or was deleted')
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
# PRESENTING #
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
def _status(status):
return { 'code' : status, 'label' : STATUS_LABELS.get(status, status.title()), 'badge' : STATUS_BADGES.get(status, 'badge-muted') }
def _step_name(graph, step_key):
return (graph.get('steps', {}).get(step_key) or {}).get('name') or step_key
def _leads(graph, step_key):
""" What a step leads to, in plain sentences """
sentences = []
for edge in graph.get('edges', []):
if edge['from'] != step_key:
continue
if edge['to'] is None:
what = 'the pipeline ends'
else:
what = 'start %s' % (_step_name(graph, edge['to']))
changes = len(edge.get('set') or {})
if changes:
what += ' with %d setting%s changed' % (changes, '' if changes == 1 else 's')
sentences.append('If %s, %s' % (WHEN.get(edge['on'], 'it ends'), what))
return sentences
def _describe_steps(graph):
rows = []
for step_key, step in graph['steps'].items():
what, speed = drawing.step_summary(step)
rows.append({
'key' : step_key, 'name' : step.get('name') or step_key,
'kind' : KIND_LABELS.get(step.get('kind'), step.get('kind')),
'what' : what, 'speed' : speed,
'leads' : _leads(graph, step_key),
'start' : step_key == graph.get('start'),
})
return rows
def _last_runs(pipelines):
latest = {}
for run in PipelineRun.objects.filter(pipeline__in=pipelines).order_by('-id'):
latest.setdefault(run.pipeline_id, run)
return latest
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
# PAGES #
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
def pipelines(request):
profile = viewer(request)
if profile is None:
return _turn_away(request, profile)
listed = list(Pipeline.objects.filter(deleted=False).order_by('-updated'))
latest = _last_runs(listed)
rows = []
for pipeline in listed:
run = latest.get(pipeline.id)
if not pipeline.enabled:
state = { 'code' : 'PAUSED', 'label' : 'Paused', 'badge' : 'badge-warn' }
elif run is not None:
state = _status(run.status)
else:
state = { 'code' : 'NEW', 'label' : 'Never run', 'badge' : 'badge-muted' }
rows.append({
'pipeline' : pipeline, 'run' : run, 'state' : state,
'steps' : len((pipeline.graph or {}).get('steps', {})),
})
data = {
'rows' : rows,
'running' : PipelineRun.objects.filter(status='RUNNING', pipeline__deleted=False).count(),
'paused' : sum(1 for row in rows if not row['pipeline'].enabled),
'total' : len(rows),
}
return OpenBench.views.render(request, 'pipelines.html', data)
def pipeline(request, id):
profile = viewer(request)
if profile is None:
return _turn_away(request, profile)
found = Pipeline.objects.filter(id=id, deleted=False).first()
if found is None:
return _missing(request)
issues = graphs.validate_graph(found.graph)
usable = not graphs.has_errors(issues) # A graph damaged behind our back is shown as damaged, not drawn
graph = found.graph if usable else None
names = { key : (step.get('name') or key) for key, step in graph['steps'].items() } if usable else {}
runs = list(PipelineRun.objects.filter(pipeline=found).order_by('-id')[:20])
for run in runs:
run.state = _status(run.status)
data = {
'pipeline' : found,
'can_manage' : can_manage(profile, found),
'svg' : drawing.render_svg(graph) if usable else '',
'steps' : _describe_steps(graph) if usable else [],
'usable' : usable,
'issues' : [dict(i, name=names.get(i['step'], i['step'])) for i in issues],
'runs' : runs,
'running' : next((run for run in runs if run.status == 'RUNNING'), None),
}
return OpenBench.views.render(request, 'pipeline.html', data)
def pipeline_run(request, run_id):
profile = viewer(request)
if profile is None:
return _turn_away(request, profile)
run = PipelineRun.objects.select_related('pipeline').filter(id=run_id).first()
if run is None:
return _missing(request)
graph = run.graph
steps = list(StepRun.objects.filter(run=run).order_by('id'))
approved = {
row['id'] : row['approved']
for row in Test.objects.filter(id__in=[s.test_id for s in steps if s.test_id]).values('id', 'approved')
}
states, hops, rows, keys = {}, [], [], {}
for step in steps:
keys[step.id] = step.step_key
state = states.setdefault(step.step_key, { 'runs' : 0 })
state['runs'] += 1
state['status'] = step.status
state['url'] = ('/%s/%d/' % (WORKLOAD_PATHS.get(step.kind, 'test'), step.test_id)) if step.test_id else None
if step.parent_id in keys:
hops.append((keys[step.parent_id], step.step_key, step.via))
rows.append({
'step' : step, 'name' : _step_name(graph, step.step_key), 'state' : _status(step.status),
'url' : state['url'],
'after' : ('After %s %s' % (_step_name(graph, keys[step.parent_id]), step.via)) if step.parent_id in keys else 'First step',
'waiting' : step.status == 'RUNNING' and approved.get(step.test_id) is False,
})
taken = graphs.followed_edges(graph, hops)
data = {
'run' : run,
'pipeline' : run.pipeline,
'state' : _status(run.status),
'can_manage' : can_manage(profile, run.pipeline),
'svg' : drawing.render_svg(graph, states=states, taken=taken),
'rows' : rows,
'signature' : '%s:%s' % (run.status, ','.join('%d=%s' % (s.id, s.status) for s in steps)),
'live' : run.status == 'RUNNING',
}
return OpenBench.views.render(request, 'pipeline_run.html', data)
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
# ACTIONS #
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
def _managed(request, id, action):
""" ( pipeline, None ) when this person may change it, ( None, response ) when not """
profile = viewer(request)
if profile is None:
return None, _turn_away(request, profile)
found = Pipeline.objects.filter(id=id, deleted=False).first()
if found is None:
return None, _missing(request)
if not can_manage(profile, found):
return None, _turn_away(request, profile, id, action)
return (found, profile), None
@require_POST
def pipeline_start(request, id):
managed, refusal = _managed(request, id, 'start')
if refusal: return refusal
found, profile = managed
# One at a time, so that a double click can not start every test twice
running = PipelineRun.objects.filter(pipeline=found, status='RUNNING').first()
if running:
return OpenBench.views.redirect(request, '/pipelines/run/%d/' % (running.id),
error='This pipeline is already running. Cancel that run if you want to start over')
run, issues = OpenBench.pipelines.start_pipeline(found, starter=profile.user.username)
if run is None:
problems = '\n'.join(i['message'] for i in issues if i['level'] == 'error')
return OpenBench.views.redirect(request, '/pipelines/%d/' % (found.id), error='Could not start the pipeline:\n' + problems)
first = StepRun.objects.filter(run=run).order_by('id').first()
if run.status == 'ERROR' and first:
return OpenBench.views.redirect(request, '/pipelines/run/%d/' % (run.id), error='The first test could not be created:\n' + first.message)
return OpenBench.views.redirect(request, '/pipelines/run/%d/' % (run.id), status='Run started')
@require_POST
def pipeline_toggle(request, id):
managed, refusal = _managed(request, id, 'toggle')
if refusal: return refusal
found, profile = managed
found.enabled = not found.enabled
found.save()
_audit(profile.user.username, 'PIPELINE #%d %s' % (found.id, 'RESUMED' if found.enabled else 'PAUSED'))
return OpenBench.views.redirect(request, '/pipelines/%d/' % (found.id), status='Pipeline resumed' if found.enabled else 'Pipeline paused')
@require_POST
def pipeline_delete(request, id):
managed, refusal = _managed(request, id, 'delete')
if refusal: return refusal
found, profile = managed
found.deleted = True
found.save()
for run in PipelineRun.objects.filter(pipeline=found, status='RUNNING'):
OpenBench.pipelines.cancel_run(run.id, profile.user.username)
_audit(profile.user.username, 'PIPELINE #%d DELETED' % (found.id))
return OpenBench.views.redirect(request, '/pipelines/', status='Pipeline deleted')
@require_POST
def pipeline_run_cancel(request, run_id):
profile = viewer(request)
if profile is None:
return _turn_away(request, profile)
run = PipelineRun.objects.select_related('pipeline').filter(id=run_id).first()
if run is None:
return _missing(request)
if not can_manage(profile, run.pipeline):
return _turn_away(request, profile, run.pipeline_id, 'cancel')
if not OpenBench.pipelines.cancel_run(run.id, profile.user.username):
return OpenBench.views.redirect(request, '/pipelines/run/%d/' % (run.id), error='This run is already over')
return OpenBench.views.redirect(request, '/pipelines/run/%d/' % (run.id), status='Run cancelled')
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
# EDITING #
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
# Anybody with an enabled account may make a Pipeline, just like they may make a
# Test. Changing one later is the same can_manage() rule as everything else.
# The editor page builds the graph in the browser. Whatever it sends is never
# trusted: it is validated here by exactly the code that validates a run.
MAX_GRAPH_BYTES = 262144
_GENERAL_DEFAULTS = {
'upload_pgns' : 'FALSE', 'priority' : '0', 'throughput' : '1000',
'syzygy_wdl' : 'OPTIONAL', 'syzygy_adj' : 'OPTIONAL',
'win_adj' : 'movecount=3 score=400',
'draw_adj' : 'movenumber=40 movecount=8 score=10',
}
PAYLOAD_DEFAULTS = {
'TEST' : dict(_GENERAL_DEFAULTS, workload_size='32', test_mode='SPRT', test_bounds='[0.00, 3.00]', test_confidence='[0.05, 0.05]'),
'TUNE' : dict(_GENERAL_DEFAULTS),
'DATAGEN' : dict(_GENERAL_DEFAULTS, workload_size='32'),
}
def _blank_graph():
return {
'version' : graphs.SCHEMA_VERSION,
'start' : 'step1',
'max_visits' : graphs.DEFAULT_MAX_VISITS,
'max_steps' : graphs.DEFAULT_MAX_STEPS,
'steps' : { 'step1' : { 'name' : 'Step 1', 'kind' : 'TEST', 'payload' : dict(PAYLOAD_DEFAULTS['TEST']) } },
'edges' : [],
}
def _parse_graph(raw):
if not isinstance(raw, str) or len(raw) > MAX_GRAPH_BYTES:
return None
try: graph = json.loads(raw)
except ValueError: return None
return graph if isinstance(graph, dict) else None
def _tidy(graph):
keys = ('version', 'start', 'max_visits', 'max_steps', 'steps', 'edges')
return { key : graph[key] for key in keys if key in graph }
def _check(graph):
# validate_graph() is built for garbage, but a page that talks to the browser
# should never answer with a 500 because of what the browser sent
try: return graphs.validate_graph(graph)
except Exception: return [graphs.issue('error', 'graph.invalid', 'The pipeline is not valid')]
def _named(issues, graph):
steps = graph.get('steps') if isinstance(graph, dict) else None
steps = steps if isinstance(steps, dict) else {}
named = []
for entry in issues:
step = steps.get(entry['step']) if isinstance(entry['step'], str) else None
name = step.get('name') if isinstance(step, dict) else None
named.append(dict(entry, name=name or entry['step']))
return named
def _editor(request, pipeline, name, graph, issues=None, error=None):
data = {
'pipeline' : pipeline,
'name' : name,
'graph' : graph,
'issues' : _named(issues or [], graph),
'meta' : {
'kinds' : list(graphs.KINDS),
'outcomes' : list(graphs.EDGE_CONDITIONS),
'required' : graphs.REQUIRED_FIELDS,
'conditional' : graphs.CONDITIONAL_FIELDS,
'allowed' : sorted(graphs.ALLOWED_FIELDS),
'defaults' : PAYLOAD_DEFAULTS,
'limits' : { 'steps' : graphs.LIMIT_STEPS, 'visits' : graphs.LIMIT_MAX_VISITS, 'total' : graphs.LIMIT_MAX_STEPS },
},
}
return OpenBench.views.render(request, 'pipeline_edit.html', data, error=error)
def _submit(request, profile, found):
""" Shared by creating and editing. Saves, or shows the editor again with what was wrong """
name = (request.POST.get('name') or '').strip()
graph = _parse_graph(request.POST.get('graph'))
errors = []
if not (1 <= len(name) <= 128):
errors.append('Give the pipeline a name of up to 128 characters')
if graph is None:
errors.append('The pipeline could not be read. Reload the page and try again')
return _editor(request, found, name, _blank_graph(), error='\n'.join(errors))
issues = _check(graph)
if graphs.has_errors(issues):
errors.append('The pipeline has problems, see the checks below')
if errors:
return _editor(request, found, name, graph, issues, error='\n'.join(errors))
graph = _tidy(graph)
if found is None:
found = Pipeline.objects.create(name=name, author=profile.user.username, graph=graph)
action = 'CREATED'
else:
found.name = name
found.graph = graph
found.save()
action = 'EDITED'
_audit(profile.user.username, 'PIPELINE #%d %s' % (found.id, action))
return OpenBench.views.redirect(request, '/pipelines/%d/' % (found.id), status='Pipeline saved')
def pipeline_new(request):
profile = viewer(request)
if profile is None:
return _turn_away(request, profile)
if request.method != 'POST':
return _editor(request, None, '', _blank_graph())
return _submit(request, profile, None)
def pipeline_edit(request, id):
profile = viewer(request)
if profile is None:
return _turn_away(request, profile)
found = Pipeline.objects.filter(id=id, deleted=False).first()
if found is None:
return _missing(request)
if not can_manage(profile, found):
return _turn_away(request, profile, id, 'edit')
# Runs that are going work from a snapshot of the graph, so this is safe at any time
if request.method != 'POST':
return _editor(request, found, found.name, copy.deepcopy(found.graph))
return _submit(request, profile, found)
@require_POST
def pipeline_check(request):
""" Validates a graph without saving it, for the Check button of the editor """
if viewer(request) is None:
return JsonResponse({ 'error' : 'Not allowed' }, status=403)
graph = _parse_graph(request.POST.get('graph'))
if graph is None:
return JsonResponse({ 'issues' : [graphs.issue('error', 'graph.invalid', 'The pipeline could not be read')] })
return JsonResponse({ 'issues' : _check(graph) })
def pipeline_test_fields(request, test_id):
""" The settings of an existing SPRT or Games test, as the settings of a step """
if viewer(request) is None:
return JsonResponse({ 'error' : 'Not allowed' }, status=403)
test = Test.objects.select_related('dev', 'base').filter(id=test_id).first()
if test is None or test.test_mode not in ('SPRT', 'GAMES'):
return JsonResponse({ 'error' : 'There is no SPRT or Games test with that number' }, status=404)
fields = {
'dev_engine' : test.dev_engine, 'base_engine' : test.base_engine,
'dev_repo' : test.dev_repo, 'base_repo' : test.base_repo,
'dev_branch' : test.dev.name, 'base_branch' : test.base.name,
'dev_network' : test.dev_network, 'base_network' : test.base_network,
'dev_options' : test.dev_options, 'base_options' : test.base_options,
'dev_time_control' : test.dev_time_control, 'base_time_control' : test.base_time_control,
'book_name' : test.book_name, 'upload_pgns' : test.upload_pgns,
'priority' : test.priority, 'throughput' : test.throughput,
'workload_size' : test.workload_size, 'test_mode' : test.test_mode,
'syzygy_wdl' : test.syzygy_wdl, 'syzygy_adj' : test.syzygy_adj,
'win_adj' : test.win_adj, 'draw_adj' : test.draw_adj,
}
if test.test_mode == 'SPRT':
fields['test_bounds'] = '[%.2f, %.2f]' % (test.elolower, test.eloupper)
fields['test_confidence'] = '[%.2f, %.2f]' % (test.beta, test.alpha)
else:
fields['test_max_games'] = test.max_games
return JsonResponse({ 'payload' : { key : str(value) for key, value in fields.items() } })