Add a build-times web endpoint

This endpoint runs an optimized query for returning information
suitable for displaying a graph of build times.

This includes a schema migration to add some indexes to aid
the query.

Change-Id: I56e8422a599c1ee51216f26fcae5a39013066e6b
This commit is contained in:
James E. Blair committed 2024-01-03 13:06:07 -08:00
1 parent e916f151ff
commit 50f068ee6d
5 files changed
+190 -2

No files matched your search

+2 -2
View File
@@ -115,9 +115,9 @@ class TestSQLConnectionMysql(ZuulTestCase):
indexes_build_event = insp.get_indexes(build_event_table)
self.assertEqual(8, len(indexes_ref))
self.assertEqual(1, len(indexes_buildset))
self.assertEqual(2, len(indexes_buildset))
self.assertEqual(2, len(indexes_buildset_ref))
self.assertEqual(4, len(indexes_build))
self.assertEqual(5, len(indexes_build))
self.assertEqual(1, len(indexes_artifact))
self.assertEqual(1, len(indexes_provides))
self.assertEqual(1, len(indexes_build_event))
+10
View File
@@ -2000,6 +2000,16 @@ class TestBuildInfo(BaseTestWeb):
"idx_min=%i" % idx_max).json()
self.assertEqual(len(buildsets_query), 1, buildsets_query)
def test_web_list_build_times(self):
# Generate some build records in the db.
self.add_base_changes()
self.executor_server.hold_jobs_in_build = False
self.executor_server.release()
self.waitUntilSettled()
builds = self.get_url("api/tenant/tenant-one/build-times").json()
self.assertEqual(len(builds), 6)
@simple_layout('layouts/empty-check.yaml')
def test_build_error(self):
conf = textwrap.dedent(
@@ -0,0 +1,46 @@
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
"""build_times
Revision ID: ac1dad8c9434
Revises: 3c1488fb137e
Create Date: 2023-10-31 15:27:40.014371
"""
# revision identifiers, used by Alembic.
revision = 'ac1dad8c9434'
down_revision = '3c1488fb137e'
branch_labels = None
depends_on = None
from alembic import op
BUILD_TABLE = 'zuul_build'
BUILDSET_TABLE = 'zuul_buildset'
def upgrade(table_prefix=''):
prefixed_build = table_prefix + BUILD_TABLE
prefixed_buildset = table_prefix + BUILDSET_TABLE
op.create_index(
f'{prefixed_build}_end_time_idx',
prefixed_build, ['end_time'])
op.create_index(
f'{prefixed_buildset}_tenant_idx',
prefixed_buildset, ['tenant'])
def downgrade():
raise Exception("Downgrades not supported")
+69
View File
@@ -255,6 +255,66 @@ class DatabaseSession(object):
except sqlalchemy.orm.exc.MultipleResultsFound:
raise Exception("Multiple builds found with uuid %s", uuid)
def getBuildTimes(self, tenant=None, project=None, pipeline=None,
branch=None,
ref=None,
start_time=None,
end_time=None,
job_name=None,
final=None,
sort_by_buildset=False,
limit=50,
offset=0,
exclude_result=None,
query_timeout=None):
ref_table = self.connection.zuul_ref_table
build_table = self.connection.zuul_build_table
buildset_table = self.connection.zuul_buildset_table
# contains_eager allows us to perform eager loading on the
# buildset *and* use that table in filters (unlike
# joinedload).
q = self.session().query(self.connection.buildModel).\
join(self.connection.buildSetModel).\
join(self.connection.refModel).\
options(orm.contains_eager(self.connection.buildModel.buildset),
orm.contains_eager(self.connection.buildModel.ref))
if query_timeout:
# For MySQL, we can add a query hint directly.
q = q.prefix_with(
f'/*+ MAX_EXECUTION_TIME({query_timeout}) */',
dialect='mysql')
# For Postgres, we add a comment that we parse in our
# event handler.
q = q.with_statement_hint(
f'/* statement_timeout={query_timeout} */',
dialect_name='postgresql')
q = self.listFilter(q, buildset_table.c.tenant, tenant)
q = self.listFilter(q, buildset_table.c.pipeline, pipeline)
q = self.listFilter(q, ref_table.c.project, project)
q = self.listFilter(q, ref_table.c.branch, branch)
q = self.listFilter(q, ref_table.c.ref, ref)
q = self.listFilter(q, build_table.c.job_name, job_name)
q = self.exListFilter(q, build_table.c.result, exclude_result)
q = self.listFilter(q, build_table.c.final, final)
if start_time:
# Intentionally using end_time here
q = q.filter(build_table.c.end_time >= start_time)
if end_time:
q = q.filter(build_table.c.end_time <= end_time)
# Only complete builds
q = q.filter(build_table.c.result != None) # noqa
q = q.order_by(build_table.c.end_time.desc())
q = q.limit(limit).offset(offset)
try:
return q.all()
except sqlalchemy.orm.exc.NoResultFound:
return []
def createBuildSet(self, *args, **kw):
bs = self.connection.buildSetModel(*args, **kw)
self.session().add(bs)
@@ -534,6 +594,7 @@ class SQLConnection(BaseConnection):
RefModel,
secondary=self.table_prefix + BUILDSET_REF_TABLE)
sa.Index(self.table_prefix + 'zuul_buildset_uuid_idx', uuid)
sa.Index(self.table_prefix + 'zuul_buildset_tenant_idx', tenant)
def createBuild(self, ref, *args, **kw):
session = orm.session.Session.object_session(self)
@@ -589,6 +650,7 @@ class SQLConnection(BaseConnection):
buildset = orm.relationship(BuildSetModel,
backref=orm.backref(
"builds",
order_by=id,
cascade="all, delete-orphan"))
ref = orm.relationship(RefModel)
@@ -600,6 +662,8 @@ class SQLConnection(BaseConnection):
buildset_id)
sa.Index(self.table_prefix + 'zuul_build_ref_id_idx',
ref_id)
sa.Index(self.table_prefix + 'zuul_build_end_time_idx',
end_time)
@property
def duration(self):
@@ -738,3 +802,8 @@ class SQLConnection(BaseConnection):
"""Delete buildsets"""
with self.getSession() as db:
return db.deleteBuildsets(*args, **kw)
def getBuildTimes(self, *args, **kw):
"""Return a list of Build objects"""
with self.getSession() as db:
return db.getBuildTimes(*args, **kw)
+63
View File
@@ -1575,6 +1575,67 @@ class ZuulWebAPI(object):
data = self.buildToDict(data[0], data[0].buildset)
return data
def buildTimeToDict(self, build):
start_time = self._datetimeToString(build.start_time)
end_time = self._datetimeToString(build.end_time)
if build.start_time and build.end_time:
duration = (build.end_time -
build.start_time).total_seconds()
else:
duration = None
ret = {
'_id': build.id,
'uuid': build.uuid,
'job_name': build.job_name,
'result': build.result,
'start_time': start_time,
'end_time': end_time,
'duration': duration,
'final': build.final,
'project': build.ref.project,
'branch': build.ref.branch,
'pipeline': build.buildset.pipeline,
'ref': build.ref.ref,
}
return ret
@cherrypy.expose
@cherrypy.tools.save_params()
@cherrypy.tools.json_out(content_type='application/json; charset=utf-8')
@cherrypy.tools.handle_options()
@cherrypy.tools.check_tenant_auth()
def build_times(self, tenant_name, tenant, auth, project=None,
pipeline=None, branch=None,
ref=None, job_name=None,
final=None,
start_time=None, end_time=None,
limit=50, skip=0,
exclude_result=None):
connection = self._get_connection()
if tenant_name not in self.zuulweb.abide.tenants.keys():
raise cherrypy.HTTPError(
404,
f'Tenant {tenant_name} does not exist.')
# If final is None, we return all builds, both final and non-final
if final is not None:
final = final.lower() == "true"
build_times = connection.getBuildTimes(
tenant=tenant_name, project=project, pipeline=pipeline,
branch=branch, ref=ref,
job_name=job_name,
final=final,
limit=limit, offset=skip,
exclude_result=exclude_result,
start_time=start_time,
end_time=end_time,
query_timeout=self.query_timeout)
return [self.buildTimeToDict(b) for b in build_times]
def buildsetToDict(self, buildset, builds=[]):
event_timestamp = self._datetimeToString(buildset.event_timestamp)
start = self._datetimeToString(buildset.first_build_start_time)
@@ -2163,6 +2224,8 @@ class ZuulWeb(object):
controller=api, action='buildsets')
route_map.connect('api', '/api/tenant/{tenant_name}/buildset/{uuid}',
controller=api, action='buildset')
route_map.connect('api', '/api/tenant/{tenant_name}/build-times',
controller=api, action='build_times')
route_map.connect('api', '/api/tenant/{tenant_name}/config-errors',
controller=api, action='config_errors')
route_map.connect('api', '/api/tenant/{tenant_name}/tenant-status',