Skip to contentSkip to conversation

knotty: Ping the server/cooker periodically

PATCH New Richard Purdie 1 participant 7 messages Dec 21, 2022

lore
Share & tools
lore
#0 lore raw

PATCH 1/7 knotty: Ping the server/cooker periodically

We've seeing failures where the UI hangs if the server disappears. Ping the cooker/server if we've not had any events in the last minute so we can check if it is still alive.

---
 lib/bb/ui/knotty.py | 12 +++++++++++-
 1 file changed, 11 insertions(+), 1 deletion(-)
lib/bb/ui/knotty.py +11 -1
index 61cf0a37f4..ab1a367be0 100644
@@ -625,7 +625,8 @@ def main(server, eventHandler, params, tf = TerminalFilter):
 
     printintervaldelta = 10 * 60 # 10 minutes
     printinterval = printintervaldelta
-    lastprint = time.time()
+    pinginterval = 1 * 60 # 1 minutes
+    lastevent = lastprint = time.time()
 
     termfilter = tf(main, helper, console_handlers, params.options.quiet)
     atexit.register(termfilter.finish)
@@ -637,6 +638,14 @@ def main(server, eventHandler, params, tf = TerminalFilter):
                 printinterval += printintervaldelta
             event = eventHandler.waitEvent(0)
             if event is None:
+                if (lastevent + pinginterval) <= time.time():
+                    ret, error = server.runCommand(["ping"])
+                    if error or not ret:
+                        termfilter.clearFooter()
+                        print("No reply after pinging server (%s, %s), exiting." % (str(error), str(ret)))
+                        return_value = 3
+                        main.shutdown = 2
+                    lastevent = time.time()
                 if main.shutdown > 1:
                     break
                 if not parseprogress:
@@ -644,6 +653,7 @@ def main(server, eventHandler, params, tf = TerminalFilter):
                 event = eventHandler.waitEvent(0.25)
                 if event is None:
                     continue
+            lastevent = time.time()
             helper.eventHandler(event)
             if isinstance(event, bb.runqueue.runQueueExitWait):
                 if not main.shutdown:
Signature · 1 line
2.37.2
#1 lore raw

PATCH 2/7 event: Add enable/disable heartbeat code

Currently heartbeat events are always generated by the server whilst it is active. Change this so they only appear when builds are running, which is when most code would expect to be executed. This removes a number of races around changes in the datastore which can happen outside of builds.

---
 lib/bb/cooker.py         | 4 ++++
 lib/bb/event.py          | 9 +++++++++
 lib/bb/server/process.py | 4 ++--
 3 files changed, 15 insertions(+), 2 deletions(-)
lib/bb/cooker.py +4 -0
index 48c3002ce3..815610ff82 100644
@@ -1467,6 +1467,7 @@ class BBCooker:
         buildname = self.databuilder.mcdata[mc].getVar("BUILDNAME")
         if fireevents:
             bb.event.fire(bb.event.BuildStarted(buildname, [item]), self.databuilder.mcdata[mc])
+            bb.event.enable_heartbeat()
 
         # Execute the runqueue
         runlist = [[mc, item, task, fn]]
@@ -1500,6 +1501,7 @@ class BBCooker:
             if not retval:
                 if fireevents:
                     bb.event.fire(bb.event.BuildCompleted(len(rq.rqdata.runtaskentries), buildname, item, failures, interrupted), self.databuilder.mcdata[mc])
+                    bb.event.disable_heartbeat()
                 self.command.finishAsyncCommand(msg)
                 # We trashed self.recipecaches above
                 self.parsecache_valid = False
@@ -1545,6 +1547,7 @@ class BBCooker:
                     for mc in self.multiconfigs:
                         bb.event.fire(bb.event.BuildCompleted(len(rq.rqdata.runtaskentries), buildname, targets, failures, interrupted), self.databuilder.mcdata[mc])
                 finally:
+                    bb.event.disable_heartbeat()
                     self.command.finishAsyncCommand(msg)
                 return False
             if retval is True:
@@ -1578,6 +1581,7 @@ class BBCooker:
 
         for mc in self.multiconfigs:
             bb.event.fire(bb.event.BuildStarted(buildname, ntargets), self.databuilder.mcdata[mc])
+        bb.event.enable_heartbeat()
 
         rq = bb.runqueue.RunQueue(self, self.data, self.recipecaches, taskdata, runlist)
         if 'universe' in targets:
lib/bb/event.py +9 -0
index 97668601a1..21e9a1b025 100644
@@ -69,6 +69,7 @@ _eventfilter = None
 _uiready = False
 _thread_lock = threading.Lock()
 _thread_lock_enabled = False
+_heartbeat_enabled = False
 
 if hasattr(__builtins__, '__setitem__'):
     builtins = __builtins__
@@ -83,6 +84,14 @@ def disable_threadlock():
     global _thread_lock_enabled
     _thread_lock_enabled = False
 
+def enable_heartbeat():
+    global _heartbeat_enabled
+    _heartbeat_enabled = True
+
+def disable_heartbeat():
+    global _heartbeat_enabled
+    _heartbeat_enabled = False
+
 def execute_handler(name, handler, event, d):
     event.data = d
     addedd = False
lib/bb/server/process.py +2 -2
index 586d46af88..91eb6e0ad9 100644
@@ -382,7 +382,7 @@ class ProcessServer():
 
         # Create new heartbeat event?
         now = time.time()
-        if now >= self.next_heartbeat:
+        if bb.event._heartbeat_enabled and now >= self.next_heartbeat:
             # We might have missed heartbeats. Just trigger once in
             # that case and continue after the usual delay.
             self.next_heartbeat += self.heartbeat_seconds
@@ -396,7 +396,7 @@ class ProcessServer():
                     if not isinstance(exc, bb.BBHandledException):
                         logger.exception('Running heartbeat function')
                     self.quit = True
-        if nextsleep and now + nextsleep > self.next_heartbeat:
+        if nextsleep and bb.event._heartbeat_enabled and now + nextsleep > self.next_heartbeat:
             # Shorten timeout so that we we wake up in time for
             # the heartbeat.
             nextsleep = self.next_heartbeat - now
Signature · 1 line
2.37.2
#2 lore raw

PATCH 3/7 event: builtins fix for 'd' deletion

In reply to Richard Purdie

I've been seeing event handlers where 'd' seems to disappear half way through event handler execution. This is problematic when multiple threads are active since this code assumes single threading.

The easiest fix is to change the handler function calls to contain d as a parameter as we do elsewhere for other functions. This will break any non-text handlers but I was only able to spot one of those in runqueue. It will also break handlers than call functions that assume 'd' is in the global namespace but those failures should be obvious and we can fix those to pass d around.

This solution avoids manipulating builtins which was always a horrible thing to do anyway and solves the issue without needing locking, thankfully.

---
 lib/bb/event.py       | 18 ++++--------------
 lib/bb/runqueue.py    |  2 +-
 lib/bb/tests/color.py |  2 +-
 lib/bb/tests/event.py | 21 +++++++++++----------
 4 files changed, 17 insertions(+), 26 deletions(-)
lib/bb/event.py +4 -14
index 21e9a1b025..db90724444 100644
@@ -71,11 +71,6 @@ _thread_lock = threading.Lock()
 _thread_lock_enabled = False
 _heartbeat_enabled = False
 
-if hasattr(__builtins__, '__setitem__'):
-    builtins = __builtins__
-else:
-    builtins = __builtins__.__dict__
-
 def enable_threadlock():
     global _thread_lock_enabled
     _thread_lock_enabled = True
@@ -94,12 +89,8 @@ def disable_heartbeat():
 
 def execute_handler(name, handler, event, d):
     event.data = d
-    addedd = False
-    if 'd' not in builtins:
-        builtins['d'] = d
-        addedd = True
     try:
-        ret = handler(event)
+        ret = handler(event, d)
     except (bb.parse.SkipRecipe, bb.BBHandledException):
         raise
     except Exception:
@@ -113,8 +104,7 @@ def execute_handler(name, handler, event, d):
         raise
     finally:
         del event.data
-        if addedd:
-            del builtins['d']
+
 
 def fire_class_handlers(event, d):
     if isinstance(event, logging.LogRecord):
@@ -262,12 +252,12 @@ def register(name, handler, mask=None, filename=None, lineno=None, data=None):
     if handler is not None:
         # handle string containing python code
         if isinstance(handler, str):
-            tmp = "def %s(e):\n%s" % (name, handler)
+            tmp = "def %s(e, d):\n%s" % (name, handler)
             try:
                 code = bb.methodpool.compile_cache(tmp)
                 if not code:
                     if filename is None:
-                        filename = "%s(e)" % name
+                        filename = "%s(e, d)" % name
                     code = compile(tmp, filename, "exec", ast.PyCF_ONLY_AST)
                     if lineno is not None:
                         ast.increment_lineno(code, lineno-1)
lib/bb/runqueue.py +1 -1
index b9dd830b31..ce711b6252 100644
@@ -1511,7 +1511,7 @@ class RunQueue:
 
             if not self.dm_event_handler_registered:
                  res = bb.event.register(self.dm_event_handler_name,
-                                         lambda x: self.dm.check(self) if self.state in [runQueueRunning, runQueueCleanUp] else False,
+                                         lambda x, y: self.dm.check(self) if self.state in [runQueueRunning, runQueueCleanUp] else False,
                                          ('bb.event.HeartbeatEvent',), data=self.cfgData)
                  self.dm_event_handler_registered = True
 
lib/bb/tests/color.py +1 -1
index 88dd278006..bb70cb393d 100644
@@ -20,7 +20,7 @@ class ProgressWatcher:
     def __init__(self):
         self._reports = []
 
-    def handle_event(self, event):
+    def handle_event(self, event, d):
         self._reports.append((event.progress, event.rate))
 
     def reports(self):
lib/bb/tests/event.py +11 -10
index 9ca7e9bc8e..4de4cced5e 100644
@@ -157,7 +157,7 @@ class EventHandlingTest(unittest.TestCase):
                                  self._test_process.event_handler,
                                  event,
                                  None)
-        self._test_process.event_handler.assert_called_once_with(event)
+        self._test_process.event_handler.assert_called_once_with(event, None)
 
     def test_fire_class_handlers(self):
         """ Test fire_class_handlers method """
@@ -175,10 +175,10 @@ class EventHandlingTest(unittest.TestCase):
         bb.event.fire_class_handlers(event1, None)
         bb.event.fire_class_handlers(event2, None)
         bb.event.fire_class_handlers(event2, None)
-        expected_event_handler1 = [call(event1)]
-        expected_event_handler2 = [call(event1),
-                                   call(event2),
-                                   call(event2)]
+        expected_event_handler1 = [call(event1, None)]
+        expected_event_handler2 = [call(event1, None),
+                                   call(event2, None),
+                                   call(event2, None)]
         self.assertEqual(self._test_process.event_handler1.call_args_list,
                          expected_event_handler1)
         self.assertEqual(self._test_process.event_handler2.call_args_list,
@@ -205,7 +205,7 @@ class EventHandlingTest(unittest.TestCase):
         bb.event.fire_class_handlers(event2, None)
         bb.event.fire_class_handlers(event2, None)
         expected_event_handler1 = []
-        expected_event_handler2 = [call(event1)]
+        expected_event_handler2 = [call(event1, None)]
         self.assertEqual(self._test_process.event_handler1.call_args_list,
                          expected_event_handler1)
         self.assertEqual(self._test_process.event_handler2.call_args_list,
@@ -223,7 +223,7 @@ class EventHandlingTest(unittest.TestCase):
         self.assertEqual(result, bb.event.Registered)
         bb.event.fire_class_handlers(event1, None)
         bb.event.fire_class_handlers(event2, None)
-        expected = [call(event1), call(event2)]
+        expected = [call(event1, None), call(event2, None)]
         self.assertEqual(self._test_process.event_handler1.call_args_list,
                          expected)
 
@@ -237,7 +237,7 @@ class EventHandlingTest(unittest.TestCase):
         self.assertEqual(result, bb.event.Registered)
         bb.event.fire_class_handlers(event1, None)
         bb.event.fire_class_handlers(event2, None)
-        expected = [call(event1), call(event2), call(event1)]
+        expected = [call(event1, None), call(event2, None), call(event1, None)]
         self.assertEqual(self._test_process.event_handler1.call_args_list,
                          expected)
 
@@ -251,7 +251,7 @@ class EventHandlingTest(unittest.TestCase):
         self.assertEqual(result, bb.event.Registered)
         bb.event.fire_class_handlers(event1, None)
         bb.event.fire_class_handlers(event2, None)
-        expected = [call(event1), call(event2), call(event1), call(event2)]
+        expected = [call(event1,None), call(event2, None), call(event1, None), call(event2, None)]
         self.assertEqual(self._test_process.event_handler1.call_args_list,
                          expected)
 
@@ -359,9 +359,10 @@ class EventHandlingTest(unittest.TestCase):
 
         event1 = bb.event.ConfigParsed()
         bb.event.fire(event1, None)
-        expected = [call(event1)]
+        expected = [call(event1, None)]
         self.assertEqual(self._test_process.event_handler1.call_args_list,
                          expected)
+        expected = [call(event1)]
         self.assertEqual(self._test_ui1.event.send.call_args_list,
                          expected)
 
Signature · 1 line
2.37.2
#3 lore raw

PATCH 4/7 server/process: Run idle commands in a separate idle thread

In reply to Richard Purdie

When bitbake is off running heavier "idle" commands, it doesn't service it's command socket which means stopping/interrupting it is hard. It also means we can't "ping" from the UI to know if it is still alive.

For those reasons, split idle command execution into it's own thread.

The commands are generally already self containted so this is easier than expected. We do have to be careful to only handle inotify poll() from a single thread at a time. It also means we always have to use a thread lock when sending events since both the idle thread and the command thread may generate log messages (and hence events). The patch does depend on a couple of previous fixes to the builtins locking in event.py and the heartbeat enable/disable changes.

---
 lib/bb/command.py        |  4 +--
 lib/bb/cooker.py         | 19 +++++++++----
 lib/bb/server/process.py | 60 +++++++++++++++++++++++++---------------
 3 files changed, 54 insertions(+), 29 deletions(-)
lib/bb/command.py +2 -2
index 0208e30ec4..20a8b86653 100644
@@ -84,7 +84,7 @@ class Command:
                 if not hasattr(command_method, 'readonly') or not getattr(command_method, 'readonly'):
                     return None, "Not able to execute not readonly commands in readonly mode"
             try:
-                self.cooker.process_inotify_updates()
+                self.cooker.process_inotify_updates_apply()
                 if getattr(command_method, 'needconfig', True):
                     self.cooker.updateCacheSync()
                 result = command_method(self, commandline)
@@ -109,7 +109,7 @@ class Command:
 
     def runAsyncCommand(self):
         try:
-            self.cooker.process_inotify_updates()
+            self.cooker.process_inotify_updates_apply()
             if self.cooker.state in (bb.cooker.state.error, bb.cooker.state.shutdown, bb.cooker.state.forceshutdown):
                 # updateCache will trigger a shutdown of the parser
                 # and then raise BBHandledException triggering an exit
lib/bb/cooker.py +14 -5
index 815610ff82..1daa587ac5 100644
@@ -220,6 +220,8 @@ class BBCooker:
         bb.debug(1, "BBCooker startup complete %s" % time.time())
         sys.stdout.flush()
 
+        self.inotify_threadlock = threading.Lock()
+
     def init_configdata(self):
         if not hasattr(self, "data"):
             self.initConfigurationData()
@@ -248,11 +250,18 @@ class BBCooker:
         self.notifier = pyinotify.Notifier(self.watcher, self.notifications)
 
     def process_inotify_updates(self):
-        for n in [self.confignotifier, self.notifier]:
-            if n and n.check_events(timeout=0):
-                # read notified events and enqueue them
-                n.read_events()
-                n.process_events()
+        with self.inotify_threadlock:
+            for n in [self.confignotifier, self.notifier]:
+                if n and n.check_events(timeout=0):
+                    # read notified events and enqueue them
+                    n.read_events()
+
+    def process_inotify_updates_apply(self):
+        with self.inotify_threadlock:
+            for n in [self.confignotifier, self.notifier]:
+                if n and n.check_events(timeout=0):
+                    n.read_events()
+                    n.process_events()
 
     def config_notifications(self, event):
         if event.maskname == "IN_Q_OVERFLOW":
lib/bb/server/process.py +38 -22

89 lines not on this page · raw message

Signature · 1 line
2.37.2
#4 lore raw

PATCH 5/7 server/process: Avoid dangling async commands

In reply to Richard Purdie

There is a race where the client can have disconnected but the async command hasn't finished running and isn't cleared up by the idle handler. If a client connects and finds this state, it will fail as the server appears busy and no new async command can execute. The old idle handler code makes this unlikely but could explain some race issues. The new code with idle handling in a separate thread makes it much more likely.

---
 lib/bb/command.py        | 3 +++
 lib/bb/server/process.py | 1 +
 2 files changed, 4 insertions(+)
lib/bb/command.py +3 -0
index 20a8b86653..1224eee413 100644
@@ -152,6 +152,9 @@ class Command:
             bb.event.fire(CommandExit(code), self.cooker.data)
         else:
             bb.event.fire(CommandCompleted(), self.cooker.data)
+        self.finishAsyncDisconnect()
+
+    def finishAsyncDisconnect(self):
         self.currentAsyncCommand = None
         self.cooker.finishcommand()
 
lib/bb/server/process.py +1 -0
index 6f43330fae..c9984539e8 100644
@@ -177,6 +177,7 @@ class ProcessServer():
                 self.command_channel = False
                 del self.event_writer
                 self.lastui = time.time()
+                self.cooker.command.finishAsyncDisconnect()
                 self.cooker.clientComplete()
                 self.haveui = False
             ready = select.select(fds,[],[],0)[0]
Signature · 1 line
2.37.2
#5 lore raw

PATCH 6/7 process: Improve client disconnect/idle sync

In reply to Richard Purdie

When clients are disconnecting, we need to ensure things are in sync with the idle thread. This patch is probably a little paranoid but it doesn't really hurt to ensure things are properly in sync and nothing unexpected will execute. A simple counter to show activity seems to easiest way to synchronise.

---
 lib/bb/server/process.py | 13 +++++++++++++
 1 file changed, 13 insertions(+)
lib/bb/server/process.py +13 -0
index c9984539e8..12dfb6ea19 100644
@@ -88,6 +88,7 @@ class ProcessServer():
         self.maxuiwait = 30
         self.xmlrpc = False
 
+        self.idle_count = 1
         self.idle = None
         self._idlefuns = {}
 
@@ -178,6 +179,13 @@ class ProcessServer():
                 del self.event_writer
                 self.lastui = time.time()
                 self.cooker.command.finishAsyncDisconnect()
+
+                # Wait for the idle loop to have executed (5s max)
+                count = self.idle_count
+                start = time.time()
+                while count == self.idle_count and time.time() < (start + 5):
+                    continue
+
                 self.cooker.clientComplete()
                 self.haveui = False
             ready = select.select(fds,[],[],0)[0]
@@ -360,6 +368,11 @@ class ProcessServer():
 
     def idle_thread(self):
         while not self.quit:
+            # Show activity
+            if self.idle_count > 100000000:
+                self.idle_count = 1
+            self.idle_count = self.idle_count + 1
+
             nextsleep = 0.1
             fds = []
             for function, data in list(self._idlefuns.items()):
Signature · 1 line
2.37.2
#6 lore raw

PATCH 7/7 knotty: Avoid looping with tracebacks

In reply to Richard Purdie

If there are events queued and there is an exception in the main loop of the UI code, it will print tracebacks on the console indefinitely. Avoid that by improving the loop exit conditions.

---
 lib/bb/ui/knotty.py | 4 +---
 1 file changed, 1 insertion(+), 3 deletions(-)
lib/bb/ui/knotty.py +1 -3
index ab1a367be0..c398f591e8 100644
@@ -631,7 +631,7 @@ def main(server, eventHandler, params, tf = TerminalFilter):
     termfilter = tf(main, helper, console_handlers, params.options.quiet)
     atexit.register(termfilter.finish)
 
-    while True:
+    while main.shutdown < 2:
         try:
             if (lastprint + printinterval) <= time.time():
                 termfilter.keepAlive(printinterval)
@@ -646,8 +646,6 @@ def main(server, eventHandler, params, tf = TerminalFilter):
                         return_value = 3
                         main.shutdown = 2
                     lastevent = time.time()
-                if main.shutdown > 1:
-                    break
                 if not parseprogress:
                     termfilter.updateFooter()
                 event = eventHandler.waitEvent(0.25)
Signature · 1 line
2.37.2