Fix the Update Layer button
cover Fix the Update Layer button
These fix the problems in bug 15395 with the Update Layer button.
1: The button created two update records: the view's, with the task
and its log, and an empty one from update.py, which holds the per-layer updates.
2: The task page showed the live log as a Python bytes literal (since
Django 3.0), and only saw the task finish when the poll reached the process that started it (rpc:// result backend).
3: The task logs volume belonged to root, so the worker could not write
the log. An existing volume keeps its owner and needs a one-time "chown layers" of the task logs directory.
Tested on a test instance loaded with a copy of the layers.openembedded.org database, with RabbitMQ and a Celery worker, by pressing the button for meta-maker and for meta-security (a full parse): before, two records and a b'...' log; after, one record with the layer update attached, the log shown as it runs, and success detected. The worker also needs "layerindex/tasks.py: fix loading the settings in the Celery worker", sent separately. The test suite passes in the Docker image (80 passed, 1 skipped).
Queuing an update behind one that is already running, also asked for in the bug, is not part of this series.
Tim Orling (3):
layerindex: record Update Layer runs in a single update record layerindex/views: fix the live log on the task status page
Dockerfile: create the task logs directory
Dockerfile | 6 ++- layerindex/tasks.py | 6 ++- layerindex/update.py | 30 +++++++++---- layerindex/views.py | 26 ++++-------- tests/test_update_button.py | 84 +++++++++++++++++++++++++++++++++++++ 5 files changed, 124 insertions(+), 28 deletions(-) create mode 100644 tests/test_update_button.py
base-commit: 08e58cdece30019a6f9e5d14af16ebe20afa6177
Signature · 1 line
2.56.0
PATCH 1/3 layerindex: record Update Layer runs in a single update record
The Update Layer button created two update records: one from the view, with the task id and log, and another from update.py, with the layer updates. Add a --update option to update.py, as other update tools have, to record its work in an existing record, and use it from the view. Save only the fields each side sets, so that the task and update.py don't overwrite each other's changes.
[YOCTO #15395]
AI-Generated: Claude Opus 5.5
--- layerindex/tasks.py | 6 ++-- layerindex/update.py | 30 +++++++++++++----- layerindex/views.py | 2 +- tests/test_update_button.py | 62 +++++++++++++++++++++++++++++++++++++ 4 files changed, 90 insertions(+), 10 deletions(-) create mode 100644 tests/test_update_button.py
layerindex/tasks.py +4 -2
@@ -42,7 +42,9 @@ def run_update_command(self, branch_name, update_command): from layerindex.models import Update updateobj = Update.objects.get(task_id=self.request.id) updateobj.started = datetime.now() - updateobj.save() + # Save only the fields set here: the update command may write to the + # same record (update.py --update) + updateobj.save(update_fields=['started']) output = '' shell = False if isinstance(update_command, str):
@@ -71,5 +73,5 @@ def run_update_command(self, branch_name, update_command): updateobj.log = output updateobj.finished = datetime.now() updateobj.retcode = retcode - updateobj.save() + updateobj.save(update_fields=['log', 'finished', 'retcode']) return {'retcode': retcode, 'output': erroutput}
layerindex/update.py +23 -7
@@ -183,6 +183,9 @@ def main(): parser.add_option("-q", "--quiet", help = "Hide all output except error messages", action="store_const", const=logging.ERROR, dest="loglevel") + parser.add_option("-u", "--update", + help = "Record the update in this existing update record instead of creating a new one", + type="int", action="store", dest="update_id") parser.add_option("", "--keep-temp", help = "Preserve temporary directory at the end instead of deleting it", action="store_true")
@@ -267,14 +270,23 @@ def main(): listhandler.setFormatter(logging.Formatter("%(levelname)s: %(message)s")) logger.addHandler(listhandler) - update = Update() - update.started = datetime.now() + if options.update_id: + update = Update.objects.filter(id=options.update_id).first() + if not update: + logger.error("Specified update id %s does not exist in database" % options.update_id) + sys.exit(1) + else: + update = Update() + update.started = datetime.now() if options.fullreload or options.reload: update.reload = True else: update.reload = False if not options.dryrun: - update.save() + if options.update_id: + update.save(update_fields=['reload']) + else: + update.save() try: lockfn = os.path.join(fetchdir, "layerindex.lock") lockfile = utils.lock_file(lockfn, options.timeout, logger)
@@ -611,10 +623,14 @@ def main(): logger.error(traceback.format_exc().rstrip()) sys.exit(1) finally: - update.log = ''.join(listhandler.read()) - update.finished = datetime.now() - if not options.dryrun: - update.save() + # With --update, whatever runs this command (e.g. the + # run_update_command task) records the log and when it finished, + # together with the exit status + if not options.update_id: + update.log = ''.join(listhandler.read()) + update.finished = datetime.now() + if not options.dryrun: + update.save() if not options.dryrun: # Purge old update records
layerindex/views.py +1 -1
@@ -147,7 +147,7 @@ def update_layer_view(request, template_name, branch='master', slug=None): from celery import uuid - cmd = 'layerindex/update.py --layer %s --branch %s;' % (layeritem.name, branch) + cmd = 'layerindex/update.py --layer %s --branch %s --update %%update%%;' % (layeritem.name, branch) task_id = uuid() # Create this here first, because inside the task we don't have all of the required info
tests/test_update_button.py new file +62 -0
62 lines not on this page · raw message
Signature · 1 line
2.56.0
PATCH 2/3 layerindex/views: fix the live log on the task status page
In reply to Tim OrlingThe task status page showed the log as a Python bytes literal, because escape() no longer decodes bytes since Django 3.0, and did not see the task finish when the poll reached another process than the one that started it, because the rpc:// result backend only returns results to that process. Decode the log, and take whether the task finished and its exit status from the update record, which the task already sets.
[YOCTO #15395]
AI-Generated: Claude Opus 5.5
--- layerindex/views.py | 24 ++++++++---------------- tests/test_update_button.py | 22 ++++++++++++++++++++++ 2 files changed, 30 insertions(+), 16 deletions(-)
layerindex/views.py +8 -16
@@ -1671,7 +1671,6 @@ class TaskStatusView(TemplateView): return context def task_log_view(request, task_id): - from celery.result import AsyncResult if not request.user.is_authenticated: raise PermissionDenied
@@ -1679,7 +1678,11 @@ def task_log_view(request, task_id): # Block anything that looks like a path raise Http404 - result = AsyncResult(task_id) + # The task records when it finished and its result in the Update. Read + # that before the log, which is complete by the time it is set. (The + # Celery result backend is no use here: with rpc:// only the process + # that started the task can read the result.) + updateobj = get_object_or_404(Update, task_id=task_id) start = int(request.GET.get('start', 0)) try: f = open(os.path.join(settings.TASK_LOG_DIR, 'task_%s.log' % task_id), 'rb')
@@ -1693,24 +1696,13 @@ def task_log_view(request, task_id): datastr = re.sub(b'\n[^\n]+\r', b'\n', datastr) # We need to escape this or else things that look like tags in the output # will be interpreted as such by the browser - data = escape(datastr) + data = escape(datastr.decode('utf-8', errors='replace')) response = HttpResponse(data) - try: - ready = result.ready() - except ConnectionResetError: - # FIXME this shouldn't be happening so often, but ultimately we don't care - - # the frontend is polling so it'll likely succeed in a subsequent request - ready = False - if ready: + if updateobj.finished: response['Task-Done'] = '1' - updateobj = get_object_or_404(Update, task_id=task_id) response['Task-Duration'] = utils.timesince2(updateobj.started, updateobj.finished) response['Task-Progress'] = 100 - if result.info: - if isinstance(result.info, dict): - response['Task-Result'] = result.info.get('retcode', None) - else: - response['Task-Result'] = -1 + response['Task-Result'] = updateobj.retcode else: response['Task-Done'] = '0' preader = utils.ProgressReader(settings.TASK_LOG_DIR, task_id)
tests/test_update_button.py +22 -0
@@ -60,3 +60,25 @@ def test_run_update_command_keeps_fields_set_by_command(settings, tmp_path, monk assert update.reload assert (update.log, update.retcode) == ('output', 0) assert update.finished is not None + + [email protected]_db [email protected]('finished, retcode, done, result', [ + (False, 0, '0', None), + (True, 0, '1', '0'), + (True, 2, '1', '2'), +]) +def test_task_log_reports_status_from_update(client, django_user_model, settings, tmp_path, + finished, retcode, done, result): + settings.TASK_LOG_DIR = str(tmp_path) + (tmp_path / 'task_test-task.log').write_text('line 1 <b>\n', encoding='utf-8') + Update.objects.create(started=datetime.now(), task_id='test-task', retcode=retcode, + finished=datetime.now() if finished else None) + client.force_login(django_user_model.objects.create_user('user', '[email protected]', 'pw')) + + response = client.get(reverse('task_log', args=('test-task',))) + + assert response.status_code == 200 + assert response.content == b'line 1 <b>\n' + assert response['Task-Done'] == done + assert response.get('Task-Result') == result
Signature · 1 line
2.56.0
PATCH 3/3 Dockerfile: create the task logs directory
In reply to Tim OrlingThe docker-compose setups mount a volume at the task logs directory in layersapp and layerscelery. The image did not have that directory, so the volume belonged to root, and the Celery worker, running as the layers user, could not write the task log: an update started with the Update Layer button failed without any log. Create the directory, owned by the layers user, so that a new volume takes its ownership.
[YOCTO #15395]
AI-Generated: Claude Opus 5.5
--- Dockerfile | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-)
Dockerfile +4 -2
@@ -68,9 +68,11 @@ COPY docker/updatelayers.sh ${APP_DIR}/updatelayers.sh COPY docker/migrate.sh ${APP_DIR}/migrate.sh COPY docker/connectivity_check.sh ${APP_DIR}/connectivity_check.sh -RUN mkdir ${APP_DIR}/workdir \ +# The task logs directory is a volume shared with layerscelery; create it +# here so that the volume belongs to the layers user +RUN mkdir ${APP_DIR}/workdir ${APP_DIR}/layerindex-task-logs \ && adduser --system --uid=500 --home /home/layers layers \ - && chown -R layers ${APP_DIR}/workdir + && chown -R layers ${APP_DIR}/workdir ${APP_DIR}/layerindex-task-logs USER layers # Always copy in .gitconfig and proxy helper script (they need editing to be active)
Signature · 1 line
2.56.0