Skip to contentSkip to conversation

toaster: changes with regards to read-only log viewer

PATCH New Patrick Vogelaar 1 participant 4 messages Nov 9

lore
Share & tools
lore
#0 lore raw

cover toaster: changes with regards to read-only log viewer

We use Toaster as a read-only build viewer for CI. Every CI build uploads its bitbake event log to a shared Toaster instance, which imports it with toaster-eventreplay and is started without build mode. This works today, but has three limitations that this series removes:

* All imported builds land in the "Command line builds" project, so builds of differeent branches or CI instances cannot be told appart.
* Whithuot the build mode. projects are hard to reach because the "All projects" tab is hidden and project links lead to the configuration page for builds.
* And IMHO there was a bug that the time of the import instead of the actual start time.

Patch 1 shows projects and their builds without build mode and hides the configuration pages and build actions there.

Patch 2 adds the TOASTER_PROJECT variable: if it is set, a command line build or replayed event log goes into the project of that name, which is created if needed. Without the variable nothing changes. It also decides whether a build is a command line build from the absence of a BuildRequest instead of from the default project, so command line builds in named projects get no Rebuild/Cancel actions.

Patch 3 takes the build start and end time from the log and task events, so a replayed log keeps the times of the original build. Live builds are unchanged apart from at most a few seconds.

---
Patrick Vogelaar (3):
toaster: show projects and builds without build mode
toaster: group command line builds by TOASTER_PROJECT
toaster: take build times from the events

 bin/toaster                                        |   2 +-
 .../bitbake-user-manual-ref-variables.rst          |  13 ++
 lib/bb/ui/buildinfohelper.py                       |  54 +++++++--
 lib/bb/ui/toasterui.py                             |   1 +
 lib/toaster/tests/browser/test_all_builds_page.py  |   2 +
 lib/toaster/tests/buildinfohelper/__init__.py      |   0
 .../tests/buildinfohelper/test_build_time.py       |  62 ++++++++++
 .../tests/buildinfohelper/test_cli_project.py      | 131 +++++++++++++++++++++
 lib/toaster/tests/views/test_nobuild.py            |  94 +++++++++++++++
 lib/toaster/toastergui/templates/base.html         |   2 -
 .../toastergui/templates/basebuildpage.html        |   4 +
 lib/toaster/toastergui/templates/mrb_section.html  |   4 +-
 .../toastergui/templates/projecttopbar.html        |   2 +-
 .../toastergui/templatetags/project_url_tag.py     |  11 +-
 lib/toaster/toastergui/views.py                    |  13 ++
 lib/toaster/toastergui/widgets.py                  |   2 +-
 lib/toaster/tox.ini                                |   3 +-
 17 files changed, 378 insertions(+), 22 deletions(-)

---
base-commit: 0f33b68cbabab26c9ed1585e3ee109689d206812
change-id: 20261104-toaster-projects-nobuild-b23f374c6f08

Best regards,

Signature · 1 line
Patrick Vogelaar <[email protected]>
#1 lore raw

PATCH 1/3 toaster: show projects and builds without build mode

Without build mode (TOASTER_BUILDSERVER unset, e.g. "toaster start nobuild" or a server that only imports event logs), Toaster cannot run builds, but it still groups builds into projects. Today the projects are hard to reach in this mode: the "All projects" tab is hidden, and a project link leads to its configuration page, which offers build and configuration actions that cannot work.

Without build mode, treat every project like the default command line builds project:

- always show the "All projects" tab
- link projects to their builds page
- hide the project top bar with its configuration tabs and build form
- redirect the project overview and main configuration page to builds
- hide the "New custom image" and "Edit custom image" build actions

Build mode is unchanged. Add tests/views/test_nobuild.py to cover the project links, redirects and hidden actions in both modes.

AI-Generated: Uses Kiro (claude-opus-5.5)

---
 lib/toaster/tests/views/test_nobuild.py            | 88 ++++++++++++++++++++++
 lib/toaster/toastergui/templates/base.html         |  2 -
 .../toastergui/templates/basebuildpage.html        |  3 +
 .../toastergui/templates/projecttopbar.html        |  2 +-
 .../toastergui/templatetags/project_url_tag.py     | 10 ++-
 lib/toaster/toastergui/views.py                    |  6 ++
 6 files changed, 105 insertions(+), 6 deletions(-)
lib/toaster/tests/views/test_nobuild.py new file +88 -0
new file mode 100644
index 000000000..a8ee82179
@@ -0,0 +1,88 @@
+#! /usr/bin/env python3
+#
+# BitBake Toaster Implementation
+#
+# SPDX-License-Identifier: GPL-2.0-only
+#
+
+"""Project pages with and without build mode (TOASTER_BUILDSERVER)."""
+
+import os
+from unittest import mock
+
+from django.test import TestCase
+from django.urls import reverse
+from django.utils import timezone
+
+from orm.models import Project, Build, Variable, Layer, Layer_Version, Recipe
+
+
+class ProjectPagesBase(TestCase):
+
+    def setUp(self):
+        self.project = Project.objects.create(name="test project")
+        self.builds_url = reverse('projectbuilds', args=(self.project.id,))
+        self.config_url = reverse('project', args=(self.project.id,))
+
+        # a started build of an image recipe
+        now = timezone.now()
+        self.build = Build.objects.create(project=self.project, started_on=now,
+                                          completed_on=now,
+                                          outcome=Build.SUCCEEDED)
+        Variable.objects.create(build=self.build, variable_name='MACHINE',
+                                variable_value='qemux86-64')
+        layer_version = Layer_Version.objects.create(
+            build=self.build, layer=Layer.objects.create(name='meta-test'))
+        Recipe.objects.create(name='core-image-test', is_image=True,
+                              layer_version=layer_version)
+        self.build_url = reverse('builddashboard', args=(self.build.id,))
+
+    def projects_table_names(self):
+        response = self.client.get(reverse('all-projects'), {'format': 'json'})
+        self.assertEqual(response.status_code, 200)
+        return [row['name'] for row in response.json()['rows']]
+
+
[email protected]('toastergui.views.project_enable', True)
[email protected](os.environ, {'TOASTER_BUILDSERVER': '1'})
+class BuildModeTests(ProjectPagesBase):
+
+    def test_projects_table_links_to_configuration(self):
+        names = self.projects_table_names()
+        self.assertTrue(any(self.config_url + '"' in n for n in names), names)
+
+    def test_build_page_offers_new_custom_image(self):
+        response = self.client.get(self.build_url)
+        self.assertContains(response, 'id="menu-new-custom-image"')
+
+
[email protected]('toastergui.views.project_enable', False)
[email protected](os.environ, {'TOASTER_BUILDSERVER': '0'})
+class NoBuildModeTests(ProjectPagesBase):
+
+    def test_projects_tab_shown(self):
+        response = self.client.get(reverse('all-builds'))
+        self.assertContains(response, 'id="navbar-all-projects"')
+
+    def test_projects_table_links_to_builds(self):
+        names = self.projects_table_names()
+        self.assertTrue(any(self.builds_url + '"' in n for n in names), names)
+        self.assertFalse(any(self.config_url + '"' in n for n in names), names)
+
+    def test_configuration_pages_redirect_to_builds(self):
+        for url in (self.config_url,
+                    reverse('projectconf', args=(self.project.id,))):
+            response = self.client.get(url)
+            self.assertRedirects(response, self.builds_url,
+                                 fetch_redirect_response=False)
+
+    def test_builds_page_has_no_project_topbar(self):
+        response = self.client.get(self.builds_url)
+        self.assertEqual(response.status_code, 200)
+        self.assertNotContains(response, 'id="project-topbar"')
+
+    def test_build_page_has_no_custom_image_actions(self):
+        response = self.client.get(self.build_url)
+        self.assertContains(response, 'id="menu-download-build-log"')
+        self.assertNotContains(response, 'id="menu-new-custom-image"')
+        self.assertNotContains(response, 'id="menu-edit-custom-image"')
lib/toaster/toastergui/templates/base.html +0 -2
index e90be6962..28af3a8ec 100644
@@ -110,7 +110,6 @@
                 All builds
               </a>
               </li>
-              {% if project_enable %}
               <li id="navbar-all-projects"
               {% if request.resolver_match.url_name == 'all-projects'  %}
               class="active"
@@ -120,7 +119,6 @@
                 All projects
               </a>
               </li>
-              {% endif %}
             {% endif %}
               <li id="navbar-docs">
               <a target="_blank" href="http://docs.yoctoproject.org/toaster-manual/index.html#toaster-user-manual">
lib/toaster/toastergui/templates/basebuildpage.html +3 -0
index a41911f52..b7982dd2c 100644
@@ -148,6 +148,8 @@
             </a>
           </li>
 
+          <!-- custom images can only be built in build mode -->
+          {% if project_enable %}
           {% with build.get_custom_image_recipes as custom_image_recipes %}
             {% if custom_image_recipes.count > 0 %}
               <!-- edit custom image built during this build -->
@@ -215,6 +217,7 @@
                 });
               </script>
             {% endif %}
+          {% endif %}
 
             <li  id="menu-delete-build">
             <a href="#delete-build-modal" id="delete-build" data-toggle="modal" data-target="#delete-build-modal" class="text-danger">
lib/toaster/toastergui/templates/projecttopbar.html +1 -1
index 768ca9455..5673f5c13 100644
@@ -41,7 +41,7 @@
     </form>
   </div>
 
-  {% if not project.is_default %}
+  {% if project_enable and not project.is_default %}
   <div id="project-topbar">
     <ul class="nav nav-tabs">
       <li id="topbar-configuration-tab">
lib/toaster/toastergui/templatetags/project_url_tag.py +7 -3
index 7b6f15b2c..7554f2a28 100644
@@ -2,6 +2,8 @@
 # SPDX-License-Identifier: GPL-2.0-only
 #
 
+import os
+
 from django import template
 from django.urls import reverse
 
@@ -10,8 +12,9 @@ register = template.Library()
 def project_url(parser, token):
     """
     Create a URL for a project's main page;
-    for non-default projects, this is the configuration page;
-    for the default project, this is the project builds page
+    for non-default projects in build mode, this is the configuration page;
+    for the default project, or without build mode, this is the project
+    builds page
     """
     try:
         tag_name, project = token.split_contents()
@@ -28,7 +31,8 @@ class ProjectUrlNode(template.Node):
     def render(self, context):
         try:
             project = self.project.resolve(context)
-            if project.is_default:
+            build_mode = os.environ.get('TOASTER_BUILDSERVER') == '1'
+            if project.is_default or not build_mode:
                 return reverse('projectbuilds', args=(project.id,))
             else:
                 return reverse('project', args=(project.id,))
lib/toaster/toastergui/views.py +6 -0
index 3192b7270..c43492af8 100644
@@ -1522,6 +1522,10 @@ if True:
 
     # Shows the edit project page
     def project(request, pid):
+        # without build mode there is nothing to configure
+        if not project_enable:
+            return redirect('projectbuilds', pid=pid)
+
         project = Project.objects.get(pk=pid)
 
         if '1' == os.environ.get('TOASTER_PROJECTSPECIFIC'):
@@ -1815,6 +1819,8 @@ if True:
         return(vars_managed,sorted(vars_fstypes),vars_disallowed)
 
     def projectconf(request, pid):
+        if not project_enable:
+            return redirect('projectbuilds', pid=pid)
 
         try:
             prj = Project.objects.get(id = pid)
Signature · 1 line
2.43.0
#2 lore raw

PATCH 2/3 toaster: group command line builds by TOASTER_PROJECT

In reply to Patrick Vogelaar

All command line builds, live ones and replayed event logs, end up in the default "Command line builds" project. When builds come from several branches or CI systems, e.g. a CI that uploads event logs to a shared Toaster instance, they cannot be told apart by project.

If TOASTER_PROJECT is set, put a command line build into the project of that name and create a normal project, including its default settings, if it does not exist yet. Empty values keep the existing default project behavior. The variable is read from the datastore so that it is recorded in event logs; bin/toaster adds it to BB_ENV_PASSTHROUGH_ADDITIONS like TOASTER_DIR.

Determine whether a build is a command line build from the absence of a BuildRequest, rather than from the default project. This keeps layers and recipes scoped correctly and avoids offering Rebuild or Cancel for command line builds in named projects. Projects created this way have no release, so in build mode they are shown like the default project, without configuration pages, build form or custom image actions. Managed builds are unchanged.

Document TOASTER_PROJECT in the BitBake variable reference. Add the tests/buildinfohelper test package and include it in tox, and give the project in tests/views/test_nobuild.py a release. Update the existing browser test to model a managed build with its BuildRequest.

AI-Generated: Uses Kiro (claude-opus-5.5)

---
 bin/toaster                                        |   2 +-
 .../bitbake-user-manual-ref-variables.rst          |  13 ++
 lib/bb/ui/buildinfohelper.py                       |  26 +++-
 lib/toaster/tests/browser/test_all_builds_page.py  |   2 +
 lib/toaster/tests/buildinfohelper/__init__.py      |   0
 .../tests/buildinfohelper/test_cli_project.py      | 131 +++++++++++++++++++++
 lib/toaster/tests/views/test_nobuild.py            |   8 +-
 .../toastergui/templates/basebuildpage.html        |   5 +-
 lib/toaster/toastergui/templates/mrb_section.html  |   4 +-
 .../toastergui/templates/projecttopbar.html        |   2 +-
 .../toastergui/templatetags/project_url_tag.py     |   7 +-
 lib/toaster/toastergui/views.py                    |   7 ++
 lib/toaster/toastergui/widgets.py                  |   2 +-
 lib/toaster/tox.ini                                |   3 +-
 14 files changed, 194 insertions(+), 18 deletions(-)
bin/toaster +1 -1
index 16a64bab6..79b3cdbda 100755
@@ -263,7 +263,7 @@ fi
 # 4) pid's we need to clean up on exit/shutdown
 # By default we move this all into the Toaster's parent build directory
 export TOASTER_DIR=$BUILDDIR
-export BB_ENV_PASSTHROUGH_ADDITIONS="$BB_ENV_PASSTHROUGH_ADDITIONS TOASTER_DIR"
+export BB_ENV_PASSTHROUGH_ADDITIONS="$BB_ENV_PASSTHROUGH_ADDITIONS TOASTER_DIR TOASTER_PROJECT"
 
 # Determine the action. If specified by arguments, fine, if not, toggle it
 if [ "$CMD" = "start" ] ; then
doc/bitbake-user-manual/bitbake-user-manual-ref-variables.rst +13 -0
index fd75275bb..41e8ec74d 100644
@@ -1922,6 +1922,19 @@ overview of their function and contents.
       consist mostly of task logs and scripts, when building a particular
       recipe.
 
+   :term:`TOASTER_PROJECT`
+      Specifies the name of the Toaster project in which to store a build
+      started from the command line. If the project does not exist, Toaster
+      creates it. If this variable is not set, Toaster stores the build in the
+      default "Command line builds" project. This variable has no effect on
+      builds started from the Toaster web interface.
+
+      Toaster reads this variable from the BitBake datastore, so it is also
+      recorded in event logs. You can set it in a configuration file such as
+      ``local.conf``. To set it from the environment, the variable must be
+      listed in :term:`BB_ENV_PASSTHROUGH_ADDITIONS`, which the ``toaster``
+      start script does for you.
+
    :term:`TOPDIR`
       Points to the build directory. BitBake automatically sets this
       variable.
lib/bb/ui/buildinfohelper.py +20 -6
index 4ee45d67a..787cab952 100644
@@ -143,7 +143,12 @@ class ORMWrapper(object):
     # pylint: disable=bad-continuation
     # we do not follow the python conventions for continuation indentation due to long lines here
 
-    def get_or_create_build_object(self, brbe):
+    def get_or_create_build_object(self, brbe, project_name=None):
+        """
+        project_name: for command line builds, the project to put the build
+        into (created if needed); None or empty for the default project
+        """
+        project_name = project_name.strip() if project_name else None
         prj = None
         buildrequest = None
         if brbe is not None:
@@ -152,6 +157,12 @@ class ORMWrapper(object):
             br, _ = brbe.split(":")
             buildrequest = BuildRequest.objects.get(pk=br)
             prj = buildrequest.project
+        elif project_name:
+            # CLI build with TOASTER_PROJECT set
+            prj = Project.objects.filter(name=project_name).first()
+            if prj is None:
+                prj = Project.objects.create_project(project_name, None)
+            logger.debug("buildinfohelper: project is %s" % prj)
         else:
             # CLI build
             prj = Project.objects.get_or_create_default_project()
@@ -348,8 +359,7 @@ class ORMWrapper(object):
         # and therefore we return the 'real' recipe rather than the build
         # history copy of the recipe.
         if  recipe_information['layer_version'].build is not None and \
-            recipe_information['layer_version'].build.project == \
-                Project.objects.get_or_create_default_project():
+            recipe_information['layer_version'].build.get_buildrequest() is None:
             return recipe
 
         if built_recipe is None:
@@ -394,7 +404,7 @@ class ORMWrapper(object):
         # If we're doing a command line build then associate this new layer with the
         # project to avoid it 'contaminating' toaster data
         project = None
-        if build_obj.project == Project.objects.get_or_create_default_project():
+        if build_obj.get_buildrequest() is None:
             project = build_obj.project
 
         layer_version_object, _ = Layer_Version.objects.get_or_create(
@@ -924,9 +934,13 @@ class BuildInfoHelper(object):
         data on the bitbake server
         """
         if not 'build' in self.internal_state or not self.internal_state['build']:
-            # create the Build object
+            # create the Build object; command line builds go into the
+            # project named by TOASTER_PROJECT, if set
+            project_name = None
+            if self.brbe is None:
+                project_name, _ = self.server.runCommand(["getVariable", "TOASTER_PROJECT"])
             self.internal_state['build'] = \
-                self.orm_wrapper.get_or_create_build_object(self.brbe)
+                self.orm_wrapper.get_or_create_build_object(self.brbe, project_name)
 
         build = self.internal_state['build']
 
lib/toaster/tests/browser/test_all_builds_page.py +2 -0
index 9ab81fb11..baf65ebc3 100644
@@ -192,6 +192,8 @@ class TestAllBuildsPage(SeleniumTestCase):
         but should be shown for other builds
         """
         build1 = Build.objects.create(**self.project1_build_success)
+        BuildRequest.objects.create(project=self.project1, build=build1,
+                                    state=BuildRequest.REQ_COMPLETED)
         default_build = Build.objects.create(
             **self.default_project_build_success)
 
lib/toaster/tests/buildinfohelper/__init__.py new file +0 -0
new file mode 100644
index 000000000..e69de29bb
lib/toaster/tests/buildinfohelper/test_cli_project.py new file +131 -0

131 lines not on this page · raw message

lib/toaster/tests/views/test_nobuild.py +7 -1
index a8ee82179..4bcb9853e 100644
@@ -15,12 +15,18 @@ from django.urls import reverse
 from django.utils import timezone
 
 from orm.models import Project, Build, Variable, Layer, Layer_Version, Recipe
+from orm.models import BitbakeVersion, Release
 
 
 class ProjectPagesBase(TestCase):
 
     def setUp(self):
-        self.project = Project.objects.create(name="test project")
+        bbv = BitbakeVersion.objects.create(name='bbv', giturl='/tmp/',
+                                            branch='master', dirpath='')
+        release = Release.objects.create(name='release',
+                                         bitbake_version=bbv)
+        self.project = Project.objects.create(name="test project",
+                                              release=release)
         self.builds_url = reverse('projectbuilds', args=(self.project.id,))
         self.config_url = reverse('project', args=(self.project.id,))
 
lib/toaster/toastergui/templates/basebuildpage.html +3 -2
index b7982dd2c..db3e3494a 100644
@@ -148,8 +148,9 @@
             </a>
           </li>
 
-          <!-- custom images can only be built in build mode -->
-          {% if project_enable %}
+          <!-- custom images can only be built in build mode, in a project
+               with a release -->
+          {% if project_enable and build.project.release %}
           {% with build.get_custom_image_recipes as custom_image_recipes %}
             {% if custom_image_recipes.count > 0 %}
               <!-- edit custom image built during this build -->
lib/toaster/toastergui/templates/mrb_section.html +2 -2
index 9fc7dfaee..91c3e6f5b 100644
@@ -255,7 +255,7 @@
 
 <!-- rebuild button or no rebuild icon -->
 <script id="rebuild-template" type="text/x-jsrender">
-  <%if is_default_project_build%>
+  <%if is_cli_build%>
     <!-- no rebuild info icon -->
     <span class="pull-right glyphicon glyphicon-question-sign get-help <%if state == 'Succeeded'%>get-help-green<%else state == 'Failed'%>get-help-red<%else%>get-help-blue<%/if%>"
     title="Builds in this project cannot be started from Toaster: they are started from the command line">
@@ -272,7 +272,7 @@
 
 <!-- cancel button or no cancel icon -->
 <script id="cancel-template" type="text/x-jsrender">
-  <%if is_default_project_build%>
+  <%if is_cli_build%>
     <!-- no cancel icon -->
     <span class="glyphicon glyphicon-question-sign get-help get-help-blue pull-right" title="Builds in this project cannot be cancelled from Toaster: they can only be cancelled from the command line"></span>
   <%else%>
lib/toaster/toastergui/templates/projecttopbar.html +1 -1
index 5673f5c13..e2055cb9b 100644
@@ -41,7 +41,7 @@
     </form>
   </div>
 
-  {% if project_enable and not project.is_default %}
+  {% if project_enable and not project.is_default and project.release %}
   <div id="project-topbar">
     <ul class="nav nav-tabs">
       <li id="topbar-configuration-tab">
lib/toaster/toastergui/templatetags/project_url_tag.py +4 -3
index 7554f2a28..d9cebda1f 100644
@@ -12,8 +12,9 @@ register = template.Library()
 def project_url(parser, token):
     """
     Create a URL for a project's main page;
-    for non-default projects in build mode, this is the configuration page;
-    for the default project, or without build mode, this is the project
+    for non-default projects with a release in build mode, this is the
+    configuration page; for the default project, projects without a release
+    (e.g. from TOASTER_PROJECT), or without build mode, this is the project
     builds page
     """
     try:
@@ -32,7 +33,7 @@ class ProjectUrlNode(template.Node):
         try:
             project = self.project.resolve(context)
             build_mode = os.environ.get('TOASTER_BUILDSERVER') == '1'
-            if project.is_default or not build_mode:
+            if project.is_default or not build_mode or project.release is None:
                 return reverse('projectbuilds', args=(project.id,))
             else:
                 return reverse('project', args=(project.id,))
lib/toaster/toastergui/views.py +7 -0
index c43492af8..1cdf47cc5 100644
@@ -1535,6 +1535,11 @@ if True:
                 return redirect("%s?%s" % (reverse(project_specific, args=(project.pk,)),params))
             else:
                 return redirect(reverse(project_specific, args=(project.pk,)))
+        # projects without a release (e.g. from TOASTER_PROJECT) only
+        # hold command line builds
+        if project.release is None:
+            return redirect('projectbuilds', pid=pid)
+
         context = {"project": project}
         return toaster_render(request, "project.html", context)
 
@@ -1826,6 +1831,8 @@ if True:
             prj = Project.objects.get(id = pid)
         except Project.DoesNotExist:
             return HttpResponseNotFound("<h1>Project id " + pid + " is unavailable</h1>")
+        if prj.release is None:
+            return redirect('projectbuilds', pid=pid)
 
         # remove disallowed and externally managed varaibles from this list
         vars_managed,vars_fstypes,vars_disallowed = get_project_configvars_context()
lib/toaster/toastergui/widgets.py +1 -1
index b32abf40b..eb2050117 100644
@@ -544,7 +544,7 @@ class MostRecentBuildsView(View):
             build['rebuild_url'] = rebuild_url
             build['cancel_url'] = cancel_url
 
-            build['is_default_project_build'] = build_obj.project.is_default
+            build['is_cli_build'] = build_obj.get_buildrequest() is None
 
             build['build_targets_json'] = \
                 template_json(get_tasks(build_obj.target_set.all()))
lib/toaster/tox.ini +2 -1
index 1516a527a..6ae38de3c 100644
@@ -13,9 +13,10 @@ setenv =
     DJANGO_SETTINGS_MODULE=toastermain.settings_test
     TOASTER_BUILDSERVER=1
     BUILDDIR = {env:BUILDDIR}
+    PYTHONPATH = {toxinidir}/..
     EVENTREPLAY_DIR = {env:EVENTREPLAY_DIR:BUILDDIR}
 commands =
-    python3 {toxinidir}/manage.py test tests.db tests.commands tests.builds tests.browser tests.functional tests.views
+    python3 {toxinidir}/manage.py test tests.db tests.commands tests.builds tests.browser tests.functional tests.views tests.buildinfohelper
 deps = 
     -r {toxinidir}/../../toaster-requirements.txt
     -r {toxinidir}/tests/toaster-tests-requirements.txt
Signature · 1 line
2.43.0
#3 lore raw

PATCH 3/3 toaster: take build times from the events

In reply to Patrick Vogelaar

Toaster sets the start and end time of a build to the time it processes the build's first and last event. For live builds this is the build time, but an event log replayed with toaster-eventreplay gets the time of the replay, so all replayed builds show when they were imported and how long the import took.

Remember the time of the latest event that carries one (log records and task events) and use it for the start and end of the build. Live builds get the time of the latest log or task event, which is at most seconds earlier than before. If no such event has been seen yet, the current time is used as before. Task times already come from the build statistics.

Add tests/buildinfohelper/test_build_time.py.

AI-Generated: Uses Kiro (claude-opus-5.5)

---
 lib/bb/ui/buildinfohelper.py                       | 32 ++++++++---
 lib/bb/ui/toasterui.py                             |  1 +
 .../tests/buildinfohelper/test_build_time.py       | 62 ++++++++++++++++++++++
 3 files changed, 88 insertions(+), 7 deletions(-)
lib/bb/ui/buildinfohelper.py +25 -7
index 787cab952..7cc8229d5 100644
@@ -43,7 +43,7 @@ from bb.msg import BBLogFormatter as formatter
 from django.db import models
 from pprint import pformat
 import logging
-from datetime import datetime, timedelta
+from datetime import datetime, timedelta, timezone as dt_timezone
 
 from django.db import transaction
 
@@ -143,10 +143,12 @@ class ORMWrapper(object):
     # pylint: disable=bad-continuation
     # we do not follow the python conventions for continuation indentation due to long lines here
 
-    def get_or_create_build_object(self, brbe, project_name=None):
+    def get_or_create_build_object(self, brbe, project_name=None,
+                                   started_on=None):
         """
         project_name: for command line builds, the project to put the build
         into (created if needed); None or empty for the default project
+        started_on: start time of a new Build object; defaults to now
         """
         project_name = project_name.strip() if project_name else None
         prj = None
@@ -175,7 +177,7 @@ class ORMWrapper(object):
             build.save()
         else:
             # create new Build object
-            now = timezone.now()
+            now = started_on or timezone.now()
             build = Build.objects.create(
                 project=prj,
                 started_on=now,
@@ -217,7 +219,8 @@ class ORMWrapper(object):
             result.append(obj)
         return result
 
-    def update_build_stats_and_outcome(self, build, errors, warnings, taskfailures):
+    def update_build_stats_and_outcome(self, build, errors, warnings, taskfailures,
+                                       completed_on=None):
         assert isinstance(build,Build)
         assert isinstance(errors, int)
         assert isinstance(warnings, int)
@@ -235,7 +238,7 @@ class ORMWrapper(object):
         if errors or taskfailures:
             outcome = Build.FAILED
 
-        build.completed_on = timezone.now()
+        build.completed_on = completed_on or timezone.now()
         build.outcome = outcome
         build.save()
 
@@ -922,6 +925,10 @@ class BuildInfoHelper(object):
 
         self.project = None
 
+        # time of the latest event that has one; event logs can be replayed
+        # long after the build, so build times are taken from the events
+        self.event_time = None
+
         logger.debug("buildinfohelper: Build info helper inited %s" % vars(self))
 
 
@@ -940,7 +947,8 @@ class BuildInfoHelper(object):
             if self.brbe is None:
                 project_name, _ = self.server.runCommand(["getVariable", "TOASTER_PROJECT"])
             self.internal_state['build'] = \
-                self.orm_wrapper.get_or_create_build_object(self.brbe, project_name)
+                self.orm_wrapper.get_or_create_build_object(
+                    self.brbe, project_name, self.event_time)
 
         build = self.internal_state['build']
 
@@ -1103,6 +1111,15 @@ class BuildInfoHelper(object):
             except NotExisting as nee:
                 logger.warning("buildinfohelper: cannot identify layer exception:%s ", nee)
 
+    def update_event_time(self, event):
+        """Remember the time of events that carry one"""
+        if isinstance(event, logging.LogRecord):
+            secs = event.created
+        else:
+            secs = getattr(event, 'time', None)
+        if isinstance(secs, (int, float)):
+            self.event_time = datetime.fromtimestamp(secs, dt_timezone.utc)
+
     def store_started_build(self):
         self._ensure_build()
 
@@ -1210,7 +1227,8 @@ class BuildInfoHelper(object):
     def update_build_information(self, event, errors, warnings, taskfailures):
         self._ensure_build()
         self.orm_wrapper.update_build_stats_and_outcome(
-            self.internal_state['build'], errors, warnings, taskfailures)
+            self.internal_state['build'], errors, warnings, taskfailures,
+            self.event_time)
 
     def store_started_task(self, event):
         assert isinstance(event, (bb.runqueue.sceneQueueTaskStarted, bb.runqueue.runQueueTaskStarted, bb.runqueue.runQueueTaskSkipped))
lib/bb/ui/toasterui.py +1 -0
index 6bd21f184..971d06c03 100644
@@ -224,6 +224,7 @@ def main(server, eventHandler, params):
                 continue
 
             helper.eventHandler(event)
+            buildinfohelper.update_event_time(event)
 
             # pylint: disable=protected-access
             # the code will look into the protected variables of the event; no easy way around this
lib/toaster/tests/buildinfohelper/test_build_time.py new file +62 -0

62 lines not on this page · raw message

Signature · 1 line
2.43.0