Skip to contentSkip to conversation

rrs_upgrade_history: skip a commit that takes too long to analyse

PATCH Superseded Tim Orling 1 participant 1 message Nov 15

v1 of 2 Superseded Latest is v2 →

lore
Share & tools
lore

Tim Orling

author
#0 lore raw

PATCH 1/1 rrs_upgrade_history: skip a commit that takes too long to analyse

A commit that made the parse hang stalled the whole run, and kept the update lock, until someone killed it. Add an optional timeout to run_command_interruptible(), which kills the command's whole process group (in the hangs seen, the stuck process was the BitBake server it started), and a --commit-timeout option to rrs_upgrade_history.py, default one hour. A commit that times out is logged and skipped.

[YOCTO #16508]

AI-Generated: Claude Opus 5.5

---

This applies on top of the series "Get the RRS update scripts working again" (patchwork 104071-104076), which also changes rrs/tools/rrs_upgrade_history.py:
https://lore.kernel.org/all/[email protected]/

 layerindex/utils.py               | 42 +++++++++++++++++--
 rrs/tools/rrs_upgrade_history.py  | 11 ++++-
 tests/test_run_command_timeout.py | 67 +++++++++++++++++++++++++++++++
 3 files changed, 116 insertions(+), 4 deletions(-)
 create mode 100644 tests/test_run_command_timeout.py
layerindex/utils.py +39 -3
index fd29de0..1c812bc 100644
@@ -18,6 +18,7 @@ import signal
 import errno
 import shutil
 import codecs
+import threading
 import re
 from datetime import datetime
 from bs4 import BeautifulSoup
@@ -512,19 +513,50 @@ def setup_core_layer_sys_path(settings, branchname):
         sys.path.insert(0, os.path.join(core_layerdir, 'lib'))
 
 
-def run_command_interruptible(cmd):
+def run_command_interruptible(cmd, timeout=None):
     """
     Run a command with output displayed on the console, but ensure any Ctrl+C is
     processed only by the child process.
+
+    If timeout is given (in seconds) and the command is still running after
+    it, the command and every process it started are killed and
+    subprocess.TimeoutExpired is raised, with the output so far.
     """
     def reenable_sigint():
         signal.signal(signal.SIGINT, signal.SIG_DFL)
 
-    signal.signal(signal.SIGINT, signal.SIG_IGN)
+    process = None
+    timer = None
+    timed_out = threading.Event()
+
+    def forward_sigint(signum, frame):
+        if process:
+            os.killpg(process.pid, signal.SIGINT)
+
+    def kill_group():
+        # The command's own children (e.g. a BitBake server) may be the ones
+        # that hang, and they keep the output pipe open, so kill them all
+        timed_out.set()
+        for sig, wait in ((signal.SIGTERM, 10), (signal.SIGKILL, 0)):
+            try:
+                os.killpg(process.pid, sig)
+            except ProcessLookupError:
+                return
+            deadline = time.monotonic() + wait
+            while process.poll() is None and time.monotonic() < deadline:
+                time.sleep(0.1)
+
+    # With a timeout the command runs in its own process group so that it
+    # can be killed as a whole; Ctrl+C then reaches only us, so pass it on
+    signal.signal(signal.SIGINT, forward_sigint if timeout else signal.SIG_IGN)
     try:
         process = subprocess.Popen(
-            cmd, cwd=os.path.dirname(sys.argv[0]), shell=True, preexec_fn=reenable_sigint, stdout=subprocess.PIPE, stderr=subprocess.STDOUT
+            cmd, cwd=os.path.dirname(sys.argv[0]), shell=True, preexec_fn=reenable_sigint, start_new_session=bool(timeout), stdout=subprocess.PIPE, stderr=subprocess.STDOUT
         )
+        if timeout:
+            timer = threading.Timer(timeout, kill_group)
+            timer.daemon = True
+            timer.start()
 
         reader = codecs.getreader('utf-8')(process.stdout, errors='surrogateescape')
         buf = ''
@@ -538,7 +570,11 @@ def run_command_interruptible(cmd):
                 break
 
     finally:
+        if timer:
+            timer.cancel()
         signal.signal(signal.SIGINT, signal.SIG_DFL)
+    if timed_out.is_set():
+        raise subprocess.TimeoutExpired(cmd, timeout, output=buf)
     return process.returncode, buf
 
 
rrs/tools/rrs_upgrade_history.py +10 -1
index 6bf230b..b20ef4e 100755
@@ -15,6 +15,7 @@
 import sys
 import os.path
 import optparse
+import subprocess
 import logging
 from datetime import date, datetime, timedelta, timezone
 
@@ -92,7 +93,11 @@ def run_internal(maintplanlayerbranch, commit, commitdate, options, logger, bitb
     if options.loglevel == logging.DEBUG:
         cmd += ' --debug'
     logger.debug('Running %s' % cmd)
-    ret, output = utils.run_command_interruptible(cmd)
+    try:
+        ret, output = utils.run_command_interruptible(cmd, timeout=options.commit_timeout or None)
+    except subprocess.TimeoutExpired:
+        logger.error('Analysing commit %s timed out after %d seconds; skipping it' % (commit, options.commit_timeout))
+        return
     if ret == 254:
         # Interrupted by user, break out of loop
         logger.info('Update interrupted, exiting')
@@ -299,6 +304,10 @@ if __name__=="__main__":
             help="Specify maintenance plan to operate on (default is all plans that have updates enabled)",
             action="store", dest="plan", default=None)
 
+    parser.add_option("--commit-timeout",
+            help="Seconds after which analysing one commit is stopped and the commit skipped, 0 for no limit (default %default)",
+            action="store", type="int", dest="commit_timeout", default=3600)
+
     parser.add_option("-F", "--filter-files",
             help="Only operate on a specified subset of files (filepath 'startswith')",
             action="store", dest="filter_files", default='')
tests/test_run_command_timeout.py new file +67 -0

67 lines not on this page · raw message

Signature · 1 line
2.56.1