Skip to contentSkip to conversation

Build cancel

RFC PATCH In review Michael Wood 2 participants 13 messages Feb 22, 2016

lore
Share & tools
lore
#0 lore raw

cover Build cancel

This is the combination of Sujith's and my work on build cancel. It needs an extra bit manual testing due to the number of time and state possibilities that can happen when trying to cancel a build.

http://git.yoctoproject.org/cgit/cgit.cgi/poky-contrib/log/?h=michaelw/sujith/build-cancel

Michael Wood (6):
toaster: Move xhr calls for starting and stopping builds
toaster: xhr Update the implementation of the build cancellation
request
toaster: libtoaster Update implementation of startABuild and
cancelABuild
toaster: bldcontrol models Add a cancelling state the BuildRequest
buildinfohelper: Add handler for cancelling a build
toaster: mrb_section template Add build cancel button

Sujith H (4):
toaster: bldcontrol Add forceShutDown function to BitbakeController
toaster: update BuildEnvironmentController and BitbakeController
toaster: models Add cancelled state to build outcome
toaster: tables BuildsTable exclude cancelled builds

 bitbake/lib/bb/ui/buildinfohelper.py               |  17 +++-
 bitbake/lib/toaster/bldcontrol/bbcontroller.py     |  29 ++----
 .../toaster/bldcontrol/localhostbecontroller.py    |   6 +-
 .../migrations/0002_add_cancelling_state.py        |  19 ++++
 bitbake/lib/toaster/bldcontrol/models.py           |  27 ++++-
 .../orm/migrations/0007_add_cancelled_state.py     |  19 ++++
 bitbake/lib/toaster/orm/models.py                  |   7 +-
 bitbake/lib/toaster/toastergui/api.py              | 109 +++++++++++++++++++++
 .../toaster/toastergui/static/js/customrecipe.js   |   4 +-
 .../lib/toaster/toastergui/static/js/layerBtn.js   |   3 +-
 .../lib/toaster/toastergui/static/js/libtoaster.js |  41 +++++---
 .../toaster/toastergui/static/js/projectpage.js    |   4 +-
 .../toaster/toastergui/static/js/projecttopbar.js  |   6 +-
 .../toaster/toastergui/static/js/recipedetails.js  |   4 +-
 bitbake/lib/toaster/toastergui/tables.py           |  48 +--------
 bitbake/lib/toaster/toastergui/templates/base.html |   1 +
 .../toaster/toastergui/templates/mrb_section.html  | 102 +++++++++++++------
 bitbake/lib/toaster/toastergui/urls.py             |   5 +
 18 files changed, 320 insertions(+), 131 deletions(-)
 create mode 100644 bitbake/lib/toaster/bldcontrol/migrations/0002_add_cancelling_state.py
 create mode 100644 bitbake/lib/toaster/orm/migrations/0007_add_cancelled_state.py
 create mode 100644 bitbake/lib/toaster/toastergui/api.py
Signature · 1 line
2.5.0
#1 lore raw

PATCH 1/10 toaster: bldcontrol Add forceShutDown function to BitbakeController

From: Sujith H <[email protected]>

Add forceShutDown function to BitbakeController class. This function provides a mechanism to cancel the build from toaster. An API which can be used safely to cancel build and hence shutdown running bitbake server.

[YOCTO #6787]

---
 bitbake/lib/toaster/bldcontrol/bbcontroller.py | 3 +++
 1 file changed, 3 insertions(+)
bitbake/lib/toaster/bldcontrol/bbcontroller.py +3 -0
index 1387bda..068b835 100644
@@ -63,6 +63,9 @@ class BitbakeController(object):
             task = "build"
         return self._runCommand(["buildTargets", targets, task])
 
+    def forceShutDown(self):
+        return self._runCommand(["stateForceShutdown"])
+
 
 
 def getBuildEnvironmentController(**kwargs):
Signature · 1 line
2.5.0
#2 lore raw

PATCH 2/10 toaster: Move xhr calls for starting and stopping builds

In reply to Michael Wood

Move the backend xhr implementation of the build request changes into it's own file and out of the ToasterTable definition.
It used to live in the views.py but in a hope of starting to collate logical groups of views move this to a new file called api.

---
 bitbake/lib/toaster/toastergui/api.py    | 74 ++++++++++++++++++++++++++++++++
 bitbake/lib/toaster/toastergui/tables.py | 43 +------------------
 bitbake/lib/toaster/toastergui/urls.py   |  5 +++
 3 files changed, 80 insertions(+), 42 deletions(-)
 create mode 100644 bitbake/lib/toaster/toastergui/api.py
bitbake/lib/toaster/toastergui/api.py new file +74 -0
new file mode 100644
index 0000000..1b1f598
@@ -0,0 +1,74 @@
+#
+# BitBake Toaster Implementation
+#
+# Copyright (C) 2016        Intel Corporation
+#
+# This program is free software; you can redistribute it and/or modify
+# it under the terms of the GNU General Public License version 2 as
+# published by the Free Software Foundation.
+#
+# This program 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, write to the Free Software Foundation, Inc.,
+# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
+
+
+# Temporary home for the UI's misc API
+
+from orm.models import Project, ProjectTarget
+from bldcontrol.models import BuildRequest
+from bldcontrol import bbcontroller
+from django.http import HttpResponse, JsonResponse
+from django.views.generic import View
+
+
+class XhrBuildRequest(View):
+
+    def get(self, request, *args, **kwargs):
+        return HttpResponse()
+
+    def post(self, request, *args, **kwargs):
+        """ Process HTTP POSTs which make build requests """
+
+        project = Project.objects.get(pk=kwargs['pid'])
+
+        if 'buildCancel' in request.POST:
+            for i in request.POST['buildCancel'].strip().split(" "):
+                try:
+                    br = BuildRequest.objects.select_for_update().get(project = project, pk = i, state__lte = BuildRequest.REQ_QUEUED)
+                    br.state = BuildRequest.REQ_DELETED
+                    br.save()
+                except BuildRequest.DoesNotExist:
+                    pass
+
+        if 'buildDelete' in request.POST:
+            for i in request.POST['buildDelete'].strip().split(" "):
+                try:
+                    BuildRequest.objects.select_for_update().get(project = project, pk = i, state__lte = BuildRequest.REQ_DELETED).delete()
+                except BuildRequest.DoesNotExist:
+                    pass
+
+        if 'targets' in request.POST:
+            ProjectTarget.objects.filter(project = project).delete()
+            s = str(request.POST['targets'])
+            for t in s.translate(None, ";%|\"").split(" "):
+                if ":" in t:
+                    target, task = t.split(":")
+                else:
+                    target = t
+                    task = ""
+                ProjectTarget.objects.create(project = project,
+                                             target = target,
+                                             task = task)
+            project.schedule_build()
+
+        # redirect back to builds page so any new builds in progress etc.
+        # are visible
+        response = HttpResponse()
+        response.status_code = 302
+        response['Location'] = request.build_absolute_uri()
+        return response
bitbake/lib/toaster/toastergui/tables.py +1 -42

55 lines not on this page · raw message

bitbake/lib/toaster/toastergui/urls.py +5 -0
index 4aa6488..78cc3bd 100644
@@ -22,6 +22,7 @@ from django.views.generic import RedirectView, TemplateView
 from django.http import HttpResponseBadRequest
 from toastergui import tables
 from toastergui import typeaheads
+from toastergui import api
 
 urlpatterns = patterns('toastergui.views',
         # landing page
@@ -180,6 +181,10 @@ urlpatterns = patterns('toastergui.views',
         url(r'^xhr_customrecipe/', 'xhr_customrecipe',
             name='xhr_customrecipe'),
 
+        url(r'^xhr_buildrequest/project/(?P<pid>\d+)$',
+           api.XhrBuildRequest.as_view(),
+            name='xhr_buildrequest'),
+
           # default redirection
         url(r'^$', RedirectView.as_view(url='landing', permanent=True)),
 )
Signature · 1 line
2.5.0
#3 lore raw

PATCH 3/10 toaster: xhr Update the implementation of the build cancellation request

In reply to Michael Wood

Update the implementation of the backend api for cancelling builds with the new cancelling BuildRequest state and cancelled Build state. Also added some docstring about general usage.

Co-Author: Sujith H <[email protected]>

---
 bitbake/lib/toaster/toastergui/api.py | 53 +++++++++++++++++++++++++++++------
 1 file changed, 44 insertions(+), 9 deletions(-)
bitbake/lib/toaster/toastergui/api.py +44 -9
index 1b1f598..a1e0bc8 100644
@@ -19,7 +19,7 @@
 
 # Temporary home for the UI's misc API
 
-from orm.models import Project, ProjectTarget
+from orm.models import Project, ProjectTarget, Build
 from bldcontrol.models import BuildRequest
 from bldcontrol import bbcontroller
 from django.http import HttpResponse, JsonResponse
@@ -32,18 +32,53 @@ class XhrBuildRequest(View):
         return HttpResponse()
 
     def post(self, request, *args, **kwargs):
-        """ Process HTTP POSTs which make build requests """
+        """
+          Build control
+
+          Entry point: /xhr_buildrequest/<project_id>
+          Method: POST
+
+          Args:
+              id: id of build to change
+              buildCancel = build_request_id ...
+              buildDelete = id ...
+              targets = recipe_name ...
+
+          Returns:
+              {"error": "ok"}
+            or
+              {"error": <error message>}
+        """
 
         project = Project.objects.get(pk=kwargs['pid'])
 
         if 'buildCancel' in request.POST:
             for i in request.POST['buildCancel'].strip().split(" "):
                 try:
-                    br = BuildRequest.objects.select_for_update().get(project = project, pk = i, state__lte = BuildRequest.REQ_QUEUED)
-                    br.state = BuildRequest.REQ_DELETED
+                    br = BuildRequest.objects.get(project=project, pk=i)
+
+                    # We now hand over to the buildinfohelper to update the
+                    # build state once we've finished cancelling
+                    br.state = BuildRequest.REQ_CANCELLING
                     br.save()
+
+                    try:
+                        bbctrl = bbcontroller.BitbakeController(br.environment)
+                        bbctrl.forceShutDown()
+                    except:
+                        # We catch a bunch of exceptions here because
+                        # this is where the server has not had time to start up
+                        # and the build request or build is in transit between
+                        # processes.
+                        # We can safely just set the build as cancelled
+                        # already as it never got started
+                        br.build.outcome = Build.CANCELLED
+                        br.build.save()
+
                 except BuildRequest.DoesNotExist:
-                    pass
+                    return JsonResponse({'error':'No such build id %s' % i})
+
+            return JsonResponse({'error': 'ok'})
 
         if 'buildDelete' in request.POST:
             for i in request.POST['buildDelete'].strip().split(" "):
@@ -51,6 +86,7 @@ class XhrBuildRequest(View):
                     BuildRequest.objects.select_for_update().get(project = project, pk = i, state__lte = BuildRequest.REQ_DELETED).delete()
                 except BuildRequest.DoesNotExist:
                     pass
+            return JsonResponse({'error': 'ok' })
 
         if 'targets' in request.POST:
             ProjectTarget.objects.filter(project = project).delete()
@@ -66,9 +102,8 @@ class XhrBuildRequest(View):
                                              task = task)
             project.schedule_build()
 
-        # redirect back to builds page so any new builds in progress etc.
-        # are visible
+            return JsonResponse({'error': 'ok' })
+
         response = HttpResponse()
-        response.status_code = 302
-        response['Location'] = request.build_absolute_uri()
+        response.status_code = 500
         return response
Signature · 1 line
2.5.0
#4 lore raw

PATCH 4/10 toaster: libtoaster Update implementation of startABuild and cancelABuild

In reply to Michael Wood

Update the implementation of startABuild and cancelAbuild to reflect changes to the backend api. We now have a dedicated endpoint to make calls into so add this url to libtoaster.ctx and allow passing null in as a url value to indicate that we want to use the current project

Also:
- Fix some documentation comments
- Add the convenience of passing in an array of targets to startABuild

---
 .../toaster/toastergui/static/js/customrecipe.js   |  4 +--
 .../lib/toaster/toastergui/static/js/layerBtn.js   |  3 +-
 .../lib/toaster/toastergui/static/js/libtoaster.js | 41 ++++++++++++++--------
 .../toaster/toastergui/static/js/projectpage.js    |  4 +--
 .../toaster/toastergui/static/js/projecttopbar.js  |  6 ++--
 .../toaster/toastergui/static/js/recipedetails.js  |  4 +--
 bitbake/lib/toaster/toastergui/templates/base.html |  1 +
 7 files changed, 34 insertions(+), 29 deletions(-)
bitbake/lib/toaster/toastergui/static/js/customrecipe.js +1 -3
index a1fe486..93f1000 100644
@@ -204,9 +204,7 @@ function customRecipePageInit(ctx) {
 
   /* Trigger a build of your custom image */
   $(".build-custom-image").click(function(){
-    libtoaster.startABuild(libtoaster.ctx.projectBuildsUrl,
-      libtoaster.ctx.projectId,
-      ctx.recipe.name,
+    libtoaster.startABuild(null, ctx.recipe.name,
       function(){
         window.location.replace(libtoaster.ctx.projectBuildsUrl);
     });
bitbake/lib/toaster/toastergui/static/js/layerBtn.js +1 -2
index 7318b3f..025f9d9 100644
@@ -60,8 +60,7 @@ function layerBtnsInit() {
     e.preventDefault();
     var recipe = $(this).data('recipe-name');
 
-    libtoaster.startABuild(libtoaster.ctx.projectBuildsUrl,
-      libtoaster.ctx.projectId, recipe,
+    libtoaster.startABuild(null, recipe,
       function(){
         /* Success */
         window.location.replace(libtoaster.ctx.projectBuildsUrl);
bitbake/lib/toaster/toastergui/static/js/libtoaster.js +26 -15

75 lines not on this page · raw message

bitbake/lib/toaster/toastergui/static/js/projectpage.js +1 -3
index 4a482d7..413714a 100644
@@ -230,9 +230,7 @@ function projectPageInit(ctx) {
 
     toBuild = toBuild.trim();
 
-    libtoaster.startABuild(libtoaster.ctx.projectBuildsUrl,
-      libtoaster.ctx.projectId,
-      toBuild,
+    libtoaster.startABuild(null, toBuild,
       function(){
         /* Build request started */
         window.location.replace(libtoaster.ctx.projectBuildsUrl);
bitbake/lib/toaster/toastergui/static/js/projecttopbar.js +3 -3
index 58a32a0..b09f974 100644
@@ -82,9 +82,9 @@ function projectTopBarInit(ctx) {
     selectedTarget = { name: newBuildTargetInput.val() };
 
     /* Fire off the build */
-    libtoaster.startABuild(libtoaster.ctx.projectBuildsUrl,
-      null, selectedTarget.name, function(){
-      window.location.replace(libtoaster.ctx.projectBuildsUrl);
+    libtoaster.startABuild(null, selectedTarget.name,
+      function(){
+        window.location.replace(libtoaster.ctx.projectBuildsUrl);
     }, null);
   });
 }
bitbake/lib/toaster/toastergui/static/js/recipedetails.js +1 -3
index 2bfd0a4..d5f9eac 100644
@@ -42,9 +42,7 @@ function recipeDetailsPageInit(ctx){
 
   /* Trigger a build of your custom image */
   $(".build-recipe-btn").click(function(){
-    libtoaster.startABuild(libtoaster.ctx.projectBuildsUrl,
-      libtoaster.ctx.projectId,
-      ctx.recipe.name,
+    libtoaster.startABuild(null, ctx.recipe.name,
       function(){
         window.location.replace(libtoaster.ctx.projectBuildsUrl);
     });
bitbake/lib/toaster/toastergui/templates/base.html +1 -0
index 6994bcc..ed15c59 100644
@@ -47,6 +47,7 @@
         projectBuildsUrl: {% url 'projectbuilds' project.id as pburl %}{{pburl|json}},
         xhrCustomRecipeUrl : "{% url 'xhr_customrecipe' %}",
         projectId : {{project.id}},
+        xhrBuildRequestUrl: "{% url 'xhr_buildrequest' project.id %}",
         {% else %}
         projectId : undefined,
         projectPageUrl : undefined,
Signature · 1 line
2.5.0
#5 lore raw

PATCH 5/10 toaster: update BuildEnvironmentController and BitbakeController

In reply to Michael Wood

From: Sujith H <[email protected]>

Remove getBBController function from BuildEnvironmentController. The constructor of BitbakeController is updated appropriately so that call can be made to connect to running server.
The call to startBBServer is removed from bbcontroller and handledin localhostbecontroller.

[YOCTO #6787]

---
 bitbake/lib/toaster/bldcontrol/bbcontroller.py     | 26 ++++------------------
 .../toaster/bldcontrol/localhostbecontroller.py    |  6 +++--
 2 files changed, 8 insertions(+), 24 deletions(-)
bitbake/lib/toaster/bldcontrol/bbcontroller.py +4 -22
index 068b835..c382927 100644
@@ -37,11 +37,12 @@ class BitbakeController(object):
         It is outside the scope of this class on how the server is started and aquired
     """
 
-    def __init__(self, connection):
-        self.connection = connection
+    def __init__(self, be):
+        self.connection = bb.server.xmlrpc._create_server(be.bbaddress,
+                                                          int(be.bbport))[0]
 
     def _runCommand(self, command):
-        result, error = self.connection.connection.runCommand(command)
+        result, error = self.connection.runCommand(command)
         if error:
             raise Exception(error)
         return result
@@ -155,25 +156,6 @@ class BuildEnvironmentController(object):
         raise Exception("FIXME: Must override setLayers")
 
 
-    def getBBController(self):
-        """ returns a BitbakeController to an already started server; this is the point where the server
-            starts if needed; or reconnects to the server if we can
-        """
-        if not self.connection:
-            self.startBBServer()
-            self.be.lock = BuildEnvironment.LOCK_RUNNING
-            self.be.save()
-
-        server = bb.server.xmlrpc.BitBakeXMLRPCClient()
-        server.initServer()
-        server.saveConnectionDetails("%s:%s" % (self.be.bbaddress, self.be.bbport))
-        self.connection = server.establishConnection([])
-
-        self.be.bbtoken = self.connection.transport.connection_token
-        self.be.save()
-
-        return BitbakeController(self.connection)
-
     def getArtifact(self, path):
         """ This call returns an artifact identified by the 'path'. How 'path' is interpreted as
             up to the implementing BEC. The return MUST be a REST URL where a GET will actually return
bitbake/lib/toaster/bldcontrol/localhostbecontroller.py +4 -2
index efd82c3..7de4f63 100644
@@ -32,7 +32,7 @@ import subprocess
 
 from toastermain import settings
 
-from bbcontroller import BuildEnvironmentController, ShellCmdException, BuildSetupException
+from bbcontroller import BuildEnvironmentController, ShellCmdException, BuildSetupException, BitbakeController
 
 import logging
 logger = logging.getLogger("toaster")
@@ -100,6 +100,7 @@ class LocalhostBEController(BuildEnvironmentController):
 
         self.be.bbaddress = "localhost"
         self.be.bbstate = BuildEnvironment.SERVER_STARTED
+        self.be.lock = BuildEnvironment.LOCK_RUNNING
         self.be.save()
 
     def getGitCloneDirectory(self, url, branch):
@@ -306,7 +307,8 @@ class LocalhostBEController(BuildEnvironmentController):
             conf.write('INHERIT+="toaster buildhistory"')
 
         # get the bb server running with the build req id and build env id
-        bbctrl = self.getBBController()
+        self.startBBServer()
+        bbctrl = BitbakeController(self.be)
 
         # set variables; TOASTER_BRBE is not set on the server, as this
         # causes events from command-line builds to be attached to the last
Signature · 1 line
2.5.0
#6 lore raw

PATCH 6/10 toaster: models Add cancelled state to build outcome

In reply to Michael Wood

From: Sujith H <[email protected]>

A new state CANCELLED is introduced to, distinguish the state of build.

[YOCTO #6787]

---
 .../orm/migrations/0007_add_cancelled_state.py        | 19 +++++++++++++++++++
 bitbake/lib/toaster/orm/models.py                     |  7 ++++++-
 2 files changed, 25 insertions(+), 1 deletion(-)
 create mode 100644 bitbake/lib/toaster/orm/migrations/0007_add_cancelled_state.py
bitbake/lib/toaster/orm/migrations/0007_add_cancelled_state.py new file +19 -0
new file mode 100644
index 0000000..8d025cc
@@ -0,0 +1,19 @@
+# -*- coding: utf-8 -*-
+from __future__ import unicode_literals
+
+from django.db import migrations, models
+
+
+class Migration(migrations.Migration):
+
+    dependencies = [
+        ('orm', '0006_customimagerecipe_last_updated'),
+    ]
+
+    operations = [
+        migrations.AlterField(
+            model_name='build',
+            name='outcome',
+            field=models.IntegerField(default=2, choices=[(0, b'Succeeded'), (1, b'Failed'), (2, b'In Progress'), (3, b'Cancelled')]),
+        ),
+    ]
bitbake/lib/toaster/orm/models.py +6 -1
index ab6940f..ed66a16 100644
@@ -353,11 +353,13 @@ class Build(models.Model):
     SUCCEEDED = 0
     FAILED = 1
     IN_PROGRESS = 2
+    CANCELLED = 3
 
     BUILD_OUTCOME = (
         (SUCCEEDED, 'Succeeded'),
         (FAILED, 'Failed'),
         (IN_PROGRESS, 'In Progress'),
+        (CANCELLED, 'Cancelled'),
     )
 
     search_allowed_fields = ['machine', 'cooker_log_path', "target__target", "target__target_image_file__file_name"]
@@ -385,7 +387,10 @@ class Build(models.Model):
         if project:
             builds = builds.filter(project=project)
 
-        finished_criteria = Q(outcome=Build.SUCCEEDED) | Q(outcome=Build.FAILED)
+        finished_criteria = \
+                Q(outcome=Build.SUCCEEDED) | \
+                Q(outcome=Build.FAILED) | \
+                Q(outcome=Build.CANCELLED)
 
         recent_builds = list(itertools.chain(
             builds.filter(outcome=Build.IN_PROGRESS).order_by("-started_on"),
Signature · 1 line
2.5.0
#7 lore raw

PATCH 7/10 toaster: bldcontrol models Add a cancelling state the BuildRequest

In reply to Michael Wood

To accurately reflect the state of a build request we also need a cancelling state. This is set when we've started a build and then for whatever reason cancel it, cancelling is not instantaneous so we have this state to indicate that a cancel is in progress.

Also add a state transition guard. As the state of a BuildRequest can currently be modified by three processes; Toastergui, Runbuilds/bldcontrol and the buildinofhelper we cannot say for sure which process will be running at the time of cancellation so in order to avoid one of these processes making an incorrect transition only allow transitions of state to increase.

e.g. CREATED -> QUEUED -> INPROGRESS
And to ignore such requested changes such as
INPROGRESS -> CREATED

---
 .../migrations/0002_add_cancelling_state.py        | 19 +++++++++++++++
 bitbake/lib/toaster/bldcontrol/models.py           | 27 +++++++++++++++++++++-
 2 files changed, 45 insertions(+), 1 deletion(-)
 create mode 100644 bitbake/lib/toaster/bldcontrol/migrations/0002_add_cancelling_state.py
bitbake/lib/toaster/bldcontrol/migrations/0002_add_cancelling_state.py new file +19 -0
new file mode 100644
index 0000000..efcdf49
@@ -0,0 +1,19 @@
+# -*- coding: utf-8 -*-
+from __future__ import unicode_literals
+
+from django.db import migrations, models
+
+
+class Migration(migrations.Migration):
+
+    dependencies = [
+        ('bldcontrol', '0001_initial'),
+    ]
+
+    operations = [
+        migrations.AlterField(
+            model_name='buildrequest',
+            name='state',
+            field=models.IntegerField(default=0, choices=[(0, b'created'), (1, b'queued'), (2, b'in progress'), (3, b'completed'), (4, b'failed'), (5, b'deleted'), (6, b'cancelling'), (7, b'archive')]),
+        ),
+    ]
bitbake/lib/toaster/bldcontrol/models.py +26 -1
index a3a49ce..0343ae9 100644
@@ -2,6 +2,8 @@ from django.db import models
 from django.core.validators import MaxValueValidator, MinValueValidator
 from orm.models import Project, ProjectLayer, ProjectVariable, ProjectTarget, Build, Layer_Version
 
+import logging
+logger = logging.getLogger("toaster")
 # a BuildEnvironment is the equivalent of the "build/" directory on the localhost
 class BuildEnvironment(models.Model):
     SERVER_STOPPED = 0
@@ -60,7 +62,8 @@ class BuildRequest(models.Model):
     REQ_COMPLETED = 3
     REQ_FAILED = 4
     REQ_DELETED = 5
-    REQ_ARCHIVE = 6
+    REQ_CANCELLING = 6
+    REQ_ARCHIVE = 7
 
     REQUEST_STATE = (
         (REQ_CREATED, "created"),
@@ -69,6 +72,7 @@ class BuildRequest(models.Model):
         (REQ_COMPLETED, "completed"),
         (REQ_FAILED, "failed"),
         (REQ_DELETED, "deleted"),
+        (REQ_CANCELLING, "cancelling"),
         (REQ_ARCHIVE, "archive"),
     )
 
@@ -81,6 +85,27 @@ class BuildRequest(models.Model):
     created     = models.DateTimeField(auto_now_add = True)
     updated     = models.DateTimeField(auto_now = True)
 
+    def __init__(self, *args, **kwargs):
+        super(BuildRequest, self).__init__(*args, **kwargs)
+        # Save the old state incase it's about to be modified
+        self.old_state = self.state
+
+    def save(self, *args, **kwargs):
+        # Check that the state we're trying to set is not going backwards
+        # e.g. from REQ_FAILED to REQ_INPROGRESS
+        if self.old_state != self.state and self.old_state > self.state:
+            logger.warn("Invalid state change requested: "
+                        "Cannot go from %s to %s - ignoring request" %
+                        (BuildRequest.REQUEST_STATE[self.old_state][1],
+                         BuildRequest.REQUEST_STATE[self.state][1])
+                       )
+            # Set property back to the old value
+            self.state = self.old_state
+            return
+
+        super(BuildRequest, self).save(*args, **kwargs)
+
+
     def get_duration(self):
         return (self.updated - self.created).total_seconds()
 
Signature · 1 line
2.5.0
#8 lore raw

PATCH 8/10 buildinfohelper: Add handler for cancelling a build

In reply to Michael Wood

When a build is cancelled the build (action) is complete if it has been caused the request being cancelled then update the build outcome accordingly.

---
 bitbake/lib/bb/ui/buildinfohelper.py | 17 ++++++++++++++++-
 1 file changed, 16 insertions(+), 1 deletion(-)
bitbake/lib/bb/ui/buildinfohelper.py +16 -1
index 81abede..164fb91 100644
@@ -211,6 +211,13 @@ class ORMWrapper(object):
         assert isinstance(errors, int)
         assert isinstance(warnings, int)
 
+        if build.outcome == Build.CANCELLED:
+            return
+
+        if build.buildrequest and \
+           build.buildrequest.state == BuildRequest.REQ_CANCELLING:
+            return
+
         outcome = Build.SUCCEEDED
         if errors or taskfailures:
             outcome = Build.FAILED
@@ -1398,9 +1405,17 @@ class BuildInfoHelper(object):
         be.lock = BuildEnvironment.LOCK_LOCK
         be.save()
         br = BuildRequest.objects.get(pk = br_id)
+
+        # if we're 'done' because we got cancelled update the build outcome
+        if br.state == BuildRequest.REQ_CANCELLING:
+            logger.info("Build cancelled")
+            br.build.outcome = Build.CANCELLED
+            br.build.save()
+            errorcode = 0
+
         if errorcode == 0:
             # request archival of the project artifacts
-            br.state = BuildRequest.REQ_ARCHIVE
+            br.state = BuildRequest.REQ_COMPLETED
         else:
             br.state = BuildRequest.REQ_FAILED
         br.save()
Signature · 1 line
2.5.0
#9 lore raw

PATCH 9/10 toaster: tables BuildsTable exclude cancelled builds

In reply to Michael Wood

From: Sujith H <[email protected]>

Exclude cancelled builds from showing in the builds table

[YOCTO #6787]

---
 bitbake/lib/toaster/toastergui/tables.py | 5 +++--
 1 file changed, 3 insertions(+), 2 deletions(-)
bitbake/lib/toaster/toastergui/tables.py +3 -2
index 4ae2350..4eac78e 100644
@@ -1070,8 +1070,9 @@ class BuildsTable(ToasterTable):
         """
         queryset = self.get_builds()
 
-        # don't include in progress builds
-        queryset = queryset.exclude(outcome=Build.IN_PROGRESS)
+        # Don't include in progress builds pr cancelled builds
+        queryset = queryset.exclude(Q(outcome=Build.IN_PROGRESS) |
+                                    Q(outcome=Build.CANCELLED))
 
         # sort
         queryset = queryset.order_by(self.default_orderby)
Signature · 1 line
2.5.0
#10 lore raw

PATCH 10/10 toaster: mrb_section template Add build cancel button

In reply to Michael Wood

Add the cancel build button to the mrb section template and add the event handlers to cancelABuild.
Also clean up the calls to startABuild to use the updated libtoaster methods and to make the code consistent with it's cancelABuild counterpart.

Co-Author: Sujith H <[email protected]>

---
 .../toaster/toastergui/templates/mrb_section.html  | 102 ++++++++++++++-------
 1 file changed, 71 insertions(+), 31 deletions(-)
bitbake/lib/toaster/toastergui/templates/mrb_section.html +71 -31
index cceee7d..b440023 100644
@@ -99,7 +99,7 @@
                   " title="Builds in this project cannot be started from Toaster: they are started from the command line">
                   </i>
               {% else %}
-                  <button class="btn
+                  <button class="run-again-btn btn
                       {% if build.outcome == build.SUCCEEDED %}
                           btn-success
                       {% elif build.outcome == build.FAILED %}
@@ -108,10 +108,9 @@
                           btn-info
                       {%endif%}
                       pull-right"
-                      onclick='scheduleBuild({% url 'projectbuilds' build.project.id as bpi %}{{bpi|json}},
-                        {{build.project.name|json}},
-                        {% url 'project' build.project.id as purl %}{{purl|json}},
-                        {{build.target_set.all|get_tasks|json}})'>
+                      data-request-url="{% url 'xhr_buildrequest' build.project.pk %}"
+                      data-target='{{build.target_set.all|get_tasks|json}}'>
+
 
                         Run again
                   </button>
@@ -119,46 +118,87 @@
             </div>
     {%endif%}
     {%if build.outcome == build.IN_PROGRESS %}
-            <div class="span4 offset1">
-              <div class="progress" id="build-pc-done-title-{{build.pk}}" style="margin-top:5px;" data-toggle="tooltip" title="{{build.completeper}}% of tasks complete">
-                  <div id="build-pc-done-bar-{{build.pk}}" style="width: {{build.completeper}}%;" class="bar"></div>
-                </div>
-            </div>
-            <div class="lead pull-right"><span id="build-pc-done-{{build.pk}}">{{build.completeper}}</span>% of tasks complete</div>
-    {%endif%}
-        </div>
+    <div class="span4" style="display:none" id="cancelling-msg-{{build.buildrequest.pk}}">
+      <p class="lead">Cancelling the build ...</p>
+    </div>
+    <div class="span4 offset1 progress-info">
+      <div class="progress" id="build-pc-done-title-{{build.pk}}" style="margin-top:5px;" data-toggle="tooltip" title="{{build.completeper}}% of tasks complete">
+        <div id="build-pc-done-bar-{{build.pk}}" style="width: {{build.completeper}}%;" class="bar"></div>
+      </div>
     </div>
+    <div class="lead span3 progress-info"><span id="build-pc-done-{{build.pk}}">{{build.completeper}}</span>% of tasks complete</div>
+    {# No build cancel for command line builds project #}
+    {% if build.project.is_default %}
+    <i class="icon-question-sign get-help get-help-blue pull-right" title="" data-original-title="Builds in this project cannot be cancelled from Toaster: they can only be cancalled from the command line"></i>
+    {% else %}
+    <div class="lead pull-right progress-info">
+      <button class="cancel-build-btn btn btn-info pull-right"
+          data-buildrequest-id={{build.buildrequest.pk}}
+          data-request-url="{% url 'xhr_buildrequest' build.project.pk %}" >
+        Cancel
+      </button>
+    </div>
+    {% endif %}
+
+    {%endif%} {# end if in progress #}
+
+    {% if build.outcome == build.CANCELLED %}
+    <div class="span4">
+      <p class="lead">Build cancelled</p>
+    </div>
+    <button class="btn btn-info pull-right run-again-btn"
+        data-request-url="{% url 'xhr_buildrequest' build.project.pk %}"
+        data-target='{{build.target_set.all|get_tasks|json}}'>
+      Run again
+
+    </button>
+    {% endif %}
+  </div>
+</div>
 
   {% endfor %}
   </div>
 
 <script>
 
-function scheduleBuild(url, projectName, projectUrl, buildlist) {
-  console.log("scheduleBuild");
-  libtoaster.startABuild(url, null, buildlist.join(" "), function(){
-    console.log("reloading page");
-    window.location.reload();
-  }, null);
-}
-
 $(document).ready(function(){
+  {%if mrb_type == 'project' %}
+  var projectBuilds = true;
+  {% else %}
+  var projectBuilds = false;
+  {% endif %}
+
+  $(".cancel-build-btn").click(function(e){
+    e.preventDefault();
 
-  $(".cancel-build-btn").click(function (){
     var url = $(this).data('request-url');
-    var buildIds = $(this).data('build-id');
-    var btn = $(this);
+    var buildReqIds = $(this).data('buildrequest-id');
+    var banner = $(this).parents(".alert");
+
+    banner.find(".progress-info").fadeOut(function(){
+      $("#cancelling-msg-" + buildReqIds).show();
+      libtoaster.cancelABuild(url, buildReqIds, function(){
+        if (projectBuilds == false){
+          /* the all builds page is not 'self updating' like thei
+           * project Builds
+           */
+          window.location.reload();
+        }
+      }, null);
+    });
+  });
+
+  $(".run-again-btn").click(function(e){
+    e.preventDefault();
 
-    libtoaster.cancelABuild(url, buildIds, function(){
-      btn.parents(".alert").fadeOut();
+    var url = $(this).data('request-url');
+    var target = $(this).data('target');
+
+    libtoaster.startABuild(url, target, function(){
+      window.location.reload();
     }, null);
   });
 
-  {%if mrb_type == 'project' %}
-  var projectBuilds = true;
-  {% else %}
-  var projectBuilds = false;
-  {% endif %}
 
   var progressTimer;
 
Signature · 1 line
2.5.0
#11 lore raw
In reply to Michael Wood

I pushed a commit which fixes the command-line builds freezing at 100%; see HEAD of:

poky-contrib, elliot/michaelw/sujith/build-cancel

Elliot

Quoted 60 lines · Michael Wood

This is the combination of Sujith's and my work on build cancel. It needs an extra bit manual testing due to the number of time and state possibilities that can happen when trying to cancel a build.

http://git.yoctoproject.org/cgit/cgit.cgi/poky-contrib/log/?h=michaelw/sujith/build-cancel

Michael Wood (6):
toaster: Move xhr calls for starting and stopping builds
toaster: xhr Update the implementation of the build cancellation
request
toaster: libtoaster Update implementation of startABuild and
cancelABuild
toaster: bldcontrol models Add a cancelling state the BuildRequest
buildinfohelper: Add handler for cancelling a build
toaster: mrb_section template Add build cancel button

Sujith H (4):
toaster: bldcontrol Add forceShutDown function to BitbakeController
toaster: update BuildEnvironmentController and BitbakeController
toaster: models Add cancelled state to build outcome
toaster: tables BuildsTable exclude cancelled builds

 bitbake/lib/bb/ui/buildinfohelper.py               |  17 +++-
 bitbake/lib/toaster/bldcontrol/bbcontroller.py     |  29 ++----
 .../toaster/bldcontrol/localhostbecontroller.py    |   6 +-
 .../migrations/0002_add_cancelling_state.py        |  19 ++++
 bitbake/lib/toaster/bldcontrol/models.py           |  27 ++++-
 .../orm/migrations/0007_add_cancelled_state.py     |  19 ++++
 bitbake/lib/toaster/orm/models.py                  |   7 +-
 bitbake/lib/toaster/toastergui/api.py              | 109
+++++++++++++++++++++
 .../toaster/toastergui/static/js/customrecipe.js   |   4 +-
 .../lib/toaster/toastergui/static/js/layerBtn.js   |   3 +-
 .../lib/toaster/toastergui/static/js/libtoaster.js |  41 +++++---
 .../toaster/toastergui/static/js/projectpage.js    |   4 +-
 .../toaster/toastergui/static/js/projecttopbar.js  |   6 +-
 .../toaster/toastergui/static/js/recipedetails.js  |   4 +-
 bitbake/lib/toaster/toastergui/tables.py           |  48 +--------
 bitbake/lib/toaster/toastergui/templates/base.html |   1 +
 .../toaster/toastergui/templates/mrb_section.html  | 102
+++++++++++++------
 bitbake/lib/toaster/toastergui/urls.py             |   5 +
 18 files changed, 320 insertions(+), 131 deletions(-)
 create mode 100644
bitbake/lib/toaster/bldcontrol/migrations/0002_add_cancelling_state.py
 create mode 100644
bitbake/lib/toaster/orm/migrations/0007_add_cancelled_state.py
 create mode 100644 bitbake/lib/toaster/toastergui/api.py

--
2.5.0

--
_______________________________________________
toaster mailing list
[email protected]
https://lists.yoctoproject.org/listinfo/toaster

Signature · 3 lines
Elliot Smith
Software Engineer
Intel Open Source Technology Centre
#12 lore raw
In reply to Michael Wood
Quoted 4 lines · Michael Wood

This is the combination of Sujith's and my work on build cancel. It needs an extra bit manual testing due to the number of time and state possibilities that can happen when trying to cancel a build.

I've been doing a bit of testing, and have found that I see the loading spinner far more often than on toaster-next. Also, in the log, I'm seeing lots of "database is locked" errors, which is likely to be the reason for the spinner.

Compared to toaster-next, where I rarely get database locking errors, I've had Toaster become unusable 3 times in the past 30 minutes due to database locking on this branch.

Are we polling the server more frequently and possibly causing the locking? Or is there something going on when you cancel a build which is putting the app into a state where locking can occur?

I've also noticed that if Toaster locks up and I restart it, the build which was ongoing before the database locked starts up again. I'm not sure if this happens on toaster-next anyway (and I just haven't noticed because I rarely get database locking), or if something has changed so that build requests can trigger a build again, even if they were interrupted and Toaster has been restarted.

Elliot

Quoted 57 lines

http://git.yoctoproject.org/cgit/cgit.cgi/poky-contrib/log/?h=michaelw/sujith/build-cancel

Michael Wood (6):
toaster: Move xhr calls for starting and stopping builds
toaster: xhr Update the implementation of the build cancellation
request
toaster: libtoaster Update implementation of startABuild and
cancelABuild
toaster: bldcontrol models Add a cancelling state the BuildRequest
buildinfohelper: Add handler for cancelling a build
toaster: mrb_section template Add build cancel button

Sujith H (4):
toaster: bldcontrol Add forceShutDown function to BitbakeController
toaster: update BuildEnvironmentController and BitbakeController
toaster: models Add cancelled state to build outcome
toaster: tables BuildsTable exclude cancelled builds

 bitbake/lib/bb/ui/buildinfohelper.py               |  17 +++-
 bitbake/lib/toaster/bldcontrol/bbcontroller.py     |  29 ++----
 .../toaster/bldcontrol/localhostbecontroller.py    |   6 +-
 .../migrations/0002_add_cancelling_state.py        |  19 ++++
 bitbake/lib/toaster/bldcontrol/models.py           |  27 ++++-
 .../orm/migrations/0007_add_cancelled_state.py     |  19 ++++
 bitbake/lib/toaster/orm/models.py                  |   7 +-
 bitbake/lib/toaster/toastergui/api.py              | 109
+++++++++++++++++++++
 .../toaster/toastergui/static/js/customrecipe.js   |   4 +-
 .../lib/toaster/toastergui/static/js/layerBtn.js   |   3 +-
 .../lib/toaster/toastergui/static/js/libtoaster.js |  41 +++++---
 .../toaster/toastergui/static/js/projectpage.js    |   4 +-
 .../toaster/toastergui/static/js/projecttopbar.js  |   6 +-
 .../toaster/toastergui/static/js/recipedetails.js  |   4 +-
 bitbake/lib/toaster/toastergui/tables.py           |  48 +--------
 bitbake/lib/toaster/toastergui/templates/base.html |   1 +
 .../toaster/toastergui/templates/mrb_section.html  | 102
+++++++++++++------
 bitbake/lib/toaster/toastergui/urls.py             |   5 +
 18 files changed, 320 insertions(+), 131 deletions(-)
 create mode 100644
bitbake/lib/toaster/bldcontrol/migrations/0002_add_cancelling_state.py
 create mode 100644
bitbake/lib/toaster/orm/migrations/0007_add_cancelled_state.py
 create mode 100644 bitbake/lib/toaster/toastergui/api.py

--
2.5.0

--
_______________________________________________
toaster mailing list
[email protected]
https://lists.yoctoproject.org/listinfo/toaster

Signature · 3 lines
Elliot Smith
Software Engineer
Intel Open Source Technology Centre