396 lines
15 KiB
Python
396 lines
15 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 scheduler: starts workloads, and decides what to start next once
|
|
# a workload ends. All of the decision making lives in OpenBench/pipeline_graph.py
|
|
# and is free of Django. This module only does the bookkeeping around it.
|
|
#
|
|
# How a run moves along:
|
|
#
|
|
# start_pipeline() queues the starting step, then launches it
|
|
# workload_finished() is called whenever a workload is over ( passed,
|
|
# failed, stopped, deleted ). Resolves its step,
|
|
# queues whatever the graph says comes next
|
|
# launch_step() creates the actual workload for a queued step,
|
|
# through the same code that the web forms use
|
|
# catch_up() safety net for anything the above missed
|
|
#
|
|
# Deciding happens inside a short transaction. Creating a workload talks to the
|
|
# Github API, so that always happens outside of any transaction, in order to not
|
|
# hold the database ( SQLite locks all of it ) while waiting on the network.
|
|
|
|
import copy
|
|
import sys
|
|
import threading
|
|
import traceback
|
|
|
|
from collections import Counter
|
|
from datetime import timedelta
|
|
|
|
from django.contrib.auth.models import User
|
|
from django.db import connections, transaction
|
|
from django.utils import timezone
|
|
|
|
import OpenBench.pipeline_graph as graphs
|
|
|
|
from OpenBench.models import LogEvent, Pipeline, PipelineRun, Profile, StepRun, Test
|
|
|
|
STALE_LAUNCH_SECONDS = 300 # A LAUNCHING step older than this was abandoned
|
|
QUEUED_GRACE_SECONDS = 30 # Give the hook this long, before catch_up() steps in
|
|
MAX_NOTES = 50
|
|
|
|
class PipelineRequest(object):
|
|
|
|
""" Stands in for a Django request, so that workloads made by a Pipeline are
|
|
verified and created by exactly the code that the web forms use """
|
|
|
|
def __init__(self, user, post):
|
|
self.user = user
|
|
self.POST = post
|
|
self.FILES = {}
|
|
self.method = 'POST'
|
|
|
|
def _log(author, summary, test_id=0):
|
|
LogEvent.objects.create(author=author, summary=summary[:128], log_file='', test_id=test_id)
|
|
|
|
def _add_notes(run, notes):
|
|
run.notes = (list(run.notes or []) + list(notes))[-MAX_NOTES:]
|
|
|
|
def _queue(run, fire, parent):
|
|
|
|
# Caller holds the lock on run, and saves it
|
|
run.fired += 1
|
|
|
|
return StepRun.objects.create(
|
|
run=run, parent=parent, step_key=fire.step_key,
|
|
via=fire.via, kind=fire.kind, payload=fire.payload)
|
|
|
|
def _refresh_run(run, halted=False):
|
|
|
|
# Caller holds the lock on run
|
|
status = graphs.run_status(list(run.steps.values_list('status', flat=True)))
|
|
|
|
if (halted and status == 'COMPLETED') or run.status == 'CANCELLED':
|
|
status = 'CANCELLED' # Cancelled by hand, or by disabling the Pipeline: it stays that way
|
|
|
|
run.status = status
|
|
run.save()
|
|
|
|
|
|
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
|
|
# STARTING #
|
|
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
|
|
|
|
def start_pipeline(pipeline, starter=None):
|
|
|
|
""" Returns ( run, issues ). The run is None if the Pipeline cannot run """
|
|
|
|
issues = graphs.validate_graph(pipeline.graph)
|
|
|
|
if not pipeline.enabled or pipeline.deleted:
|
|
issues.append(graphs.issue('error', 'pipeline.disabled', 'The pipeline is disabled'))
|
|
|
|
if graphs.has_errors(issues):
|
|
return None, issues
|
|
|
|
with transaction.atomic():
|
|
run = PipelineRun.objects.create(
|
|
pipeline=pipeline, graph=copy.deepcopy(pipeline.graph),
|
|
starter=starter or pipeline.author)
|
|
_queue(run, graphs.initial_fire(run.graph), None)
|
|
run.save()
|
|
|
|
_log(run.starter, 'PIPELINE #%d RUN #%d STARTED' % (pipeline.id, run.id)) # By whoever pressed the button
|
|
|
|
launch_queued(run.id)
|
|
return PipelineRun.objects.get(id=run.id), issues
|
|
|
|
|
|
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
|
|
# LAUNCHING #
|
|
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
|
|
|
|
def launch_queued(run_id):
|
|
for step_id in StepRun.objects.filter(run_id=run_id, status='QUEUED').order_by('id').values_list('id', flat=True):
|
|
launch_step(step_id)
|
|
|
|
def launch_step(step_id):
|
|
|
|
# Claim the step, so that the hook and catch_up() can never both create it
|
|
claimed = StepRun.objects.filter(id=step_id, status='QUEUED').update(status='LAUNCHING', updated=timezone.now())
|
|
if claimed != 1:
|
|
return
|
|
|
|
step = StepRun.objects.get(id=step_id)
|
|
pipeline = Pipeline.objects.get(id=step.run.pipeline_id)
|
|
|
|
try:
|
|
workload, errors = _create_workload(step, pipeline)
|
|
except Exception:
|
|
traceback.print_exc(); sys.stdout.flush()
|
|
workload, errors = None, ['Unexpected error while creating the workload']
|
|
|
|
failed = False
|
|
|
|
with transaction.atomic():
|
|
|
|
run = PipelineRun.objects.select_for_update().get(id=step.run_id)
|
|
step = StepRun.objects.select_for_update().get(id=step_id)
|
|
|
|
if step.status != 'LAUNCHING':
|
|
# The run was cancelled while this was being created. The step stays as
|
|
# cancelling left it, but a workload that did get made is not forgotten
|
|
if workload is not None:
|
|
step.test_id = workload.id
|
|
step.message = (step.message + '. Its workload was already being created')[:512]
|
|
step.save()
|
|
|
|
elif errors:
|
|
failed = True
|
|
step.status = 'ERROR'
|
|
step.message = ' / '.join(errors)[:512]
|
|
step.resolved = timezone.now()
|
|
step.save()
|
|
_add_notes(run, ['Could not create "%s": %s' % (step.step_key, step.message)])
|
|
|
|
else:
|
|
step.status = 'RUNNING'
|
|
step.test_id = workload.id
|
|
step.save()
|
|
|
|
_refresh_run(run, halted=not pipeline.enabled or pipeline.deleted)
|
|
|
|
if failed:
|
|
_log(pipeline.author, 'PIPELINE #%d %s ERROR' % (pipeline.id, step.step_key))
|
|
|
|
def _create_workload(step, pipeline):
|
|
|
|
# Imported late: the workload modules depend on OpenBench.utils, which in
|
|
# turn calls into this module when a workload ends. They must be entered by
|
|
# way of OpenBench.views, like the web server does, or they import in circles
|
|
import OpenBench.views
|
|
|
|
from OpenBench.config import OPENBENCH_CONFIG
|
|
from OpenBench.workloads import create_workload as creation
|
|
|
|
user = User.objects.filter(username=pipeline.author).first()
|
|
profile = Profile.objects.filter(user=user).first() if user else None
|
|
|
|
if not profile or not profile.enabled:
|
|
return None, ['"%s" is not an enabled user' % (pipeline.author)]
|
|
|
|
creators = {
|
|
'TEST' : creation.create_new_test,
|
|
'TUNE' : creation.create_new_tune,
|
|
'DATAGEN' : creation.create_new_datagen,
|
|
}
|
|
|
|
workload, errors = creators[step.kind](PipelineRequest(user, dict(step.payload)))
|
|
|
|
if errors:
|
|
return None, errors
|
|
|
|
# The same bookkeeping that create_workload() does after creating a workload
|
|
summary = 'CREATE P=%d TP=%d' % (workload.priority, workload.throughput)
|
|
_log(user.username, summary, workload.id)
|
|
|
|
if not OPENBENCH_CONFIG['use_cross_approval'] and profile.approver:
|
|
workload.approved = True
|
|
workload.save()
|
|
|
|
return workload, None
|
|
|
|
|
|
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
|
|
# LOOKING UP #
|
|
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
|
|
|
|
def step_of(test_id):
|
|
|
|
""" Which step of which run made a workload, for showing on the page of that
|
|
workload. None for the great majority of workloads, that no Pipeline made. """
|
|
|
|
step = StepRun.objects.select_related('run__pipeline', 'parent').filter(test_id=test_id).first()
|
|
|
|
if step is None:
|
|
return None
|
|
|
|
names = (step.run.graph or {}).get('steps', {})
|
|
name = lambda key: (names.get(key) or {}).get('name') or key
|
|
|
|
return {
|
|
'name' : name(step.step_key),
|
|
'pipeline' : step.run.pipeline.name,
|
|
'run_id' : step.run_id,
|
|
'after' : 'After %s %s' % (name(step.parent.step_key), step.via) if step.parent_id else '',
|
|
}
|
|
|
|
|
|
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
|
|
# CANCELLING #
|
|
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
|
|
|
|
def cancel_run(run_id, by):
|
|
|
|
""" Ends a run for good, so that nothing more starts from it. Whatever has not
|
|
started yet is stopped. Workloads that are already running are left alone,
|
|
since stopping a test is a decision for the page of that test. Returns
|
|
whether there was a running run to cancel. """
|
|
|
|
with transaction.atomic():
|
|
|
|
run = PipelineRun.objects.select_for_update().filter(id=run_id).first()
|
|
if run is None or run.status != 'RUNNING':
|
|
return False
|
|
|
|
now = timezone.now()
|
|
for step in StepRun.objects.select_for_update().filter(run=run, status__in=('QUEUED', 'LAUNCHING')):
|
|
step.status = 'STOPPED'
|
|
step.message = 'Run cancelled by %s' % (by)
|
|
step.resolved = now
|
|
step.save()
|
|
|
|
run.status = 'CANCELLED'
|
|
_add_notes(run, ['Cancelled by %s' % (by)])
|
|
run.save()
|
|
|
|
_log(by, 'PIPELINE #%d RUN #%d CANCELLED' % (run.pipeline_id, run.id))
|
|
return True
|
|
|
|
|
|
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
|
|
# ADVANCING #
|
|
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
|
|
|
|
def workload_finished(test_id, background=True):
|
|
|
|
""" Hook for everything that can end a workload. Safe to call for any
|
|
workload, at any time, as many times as you like, and never raises.
|
|
|
|
Cheap for workloads that no Pipeline cares about, which is nearly all
|
|
of them. Otherwise carries on in a thread, since creating the next
|
|
workload needs the Github API, and the caller is often a Worker who
|
|
should not be kept waiting for that. """
|
|
|
|
try:
|
|
if not StepRun.objects.filter(test_id=test_id, status='RUNNING').exists():
|
|
return
|
|
except Exception:
|
|
traceback.print_exc(); sys.stdout.flush()
|
|
return
|
|
|
|
if not background:
|
|
return _advance(test_id, guarded=True)
|
|
|
|
threading.Thread(target=_advance_in_thread, args=(test_id,), daemon=True).start()
|
|
|
|
def _advance_in_thread(test_id):
|
|
try: _advance(test_id, guarded=True)
|
|
finally: connections.close_all() # Threads own their database connections
|
|
|
|
def _advance(test_id, guarded=False):
|
|
|
|
if guarded:
|
|
try: return _advance(test_id)
|
|
except Exception:
|
|
traceback.print_exc(); sys.stdout.flush()
|
|
return
|
|
|
|
to_launch = []
|
|
|
|
with transaction.atomic():
|
|
|
|
step = StepRun.objects.select_for_update().filter(test_id=test_id, status='RUNNING').first()
|
|
test = Test.objects.filter(id=test_id).first()
|
|
|
|
if step is None or test is None:
|
|
return # Already handled, or nothing that we know of
|
|
|
|
outcome = graphs.classify_outcome(
|
|
test.finished, test.deleted, test.passed, test.failed,
|
|
test.test_mode, test.games, getattr(test, 'spsa', None))
|
|
|
|
if outcome is None:
|
|
return # Still going
|
|
|
|
run = PipelineRun.objects.select_for_update().get(id=step.run_id)
|
|
pipeline = Pipeline.objects.get(id=run.pipeline_id)
|
|
halted = not pipeline.enabled or pipeline.deleted
|
|
|
|
step.status = outcome.upper()
|
|
step.resolved = timezone.now()
|
|
step.save()
|
|
|
|
_log(pipeline.author, 'PIPELINE #%d %s %s' % (pipeline.id, step.step_key, outcome.upper()), test_id)
|
|
|
|
if run.status != 'RUNNING':
|
|
pass # Nothing may start from a run that is already over
|
|
|
|
elif halted:
|
|
_add_notes(run, ['Pipeline is disabled, not carrying on after "%s"' % (step.step_key)])
|
|
|
|
else:
|
|
visits = Counter(run.steps.values_list('step_key', flat=True))
|
|
plan = graphs.plan_next(run.graph, step.step_key, outcome, visits, run.fired)
|
|
|
|
_add_notes(run, plan.notes)
|
|
to_launch = [_queue(run, fire, step) for fire in plan.fires]
|
|
|
|
_refresh_run(run, halted)
|
|
|
|
for queued in to_launch:
|
|
launch_step(queued.id)
|
|
|
|
|
|
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
|
|
# SAFETY NET #
|
|
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
|
|
|
|
def catch_up():
|
|
|
|
""" Picks up whatever the hooks could not: the server was down when a
|
|
workload ended, a thread died halfway, a launch was interrupted. Safe
|
|
to run at any time, and as often as you like. Returns what it found. """
|
|
|
|
now = timezone.now()
|
|
found = { 'relaunched' : 0, 'resolved' : 0 }
|
|
|
|
# A launch that started, but never reported back. Whether or not the
|
|
# workload got created, there is no way to know here. A duplicate is much
|
|
# better than a pipeline that silently stalls, so it gets queued again.
|
|
stale = now - timedelta(seconds=STALE_LAUNCH_SECONDS)
|
|
StepRun.objects.filter(status='LAUNCHING', test_id=0, updated__lt=stale).update(status='QUEUED')
|
|
|
|
waiting = now - timedelta(seconds=QUEUED_GRACE_SECONDS)
|
|
for step_id in StepRun.objects.filter(status='QUEUED', updated__lt=waiting).order_by('id').values_list('id', flat=True):
|
|
launch_step(step_id)
|
|
found['relaunched'] += 1
|
|
|
|
# Workloads that are over, but whose Step was never told so
|
|
running = StepRun.objects.filter(status='RUNNING', test_id__gt=0)
|
|
for test_id in list(running.values_list('test_id', flat=True)):
|
|
before = StepRun.objects.filter(test_id=test_id, status='RUNNING').exists()
|
|
_advance(test_id, guarded=True)
|
|
after = StepRun.objects.filter(test_id=test_id, status='RUNNING').exists()
|
|
found['resolved'] += int(before and not after)
|
|
|
|
return found
|