Skip to contentSkip to conversation

knotty: Ping the server/cooker periodically

PATCH In review Richard Purdie 2 participants 8 messages Dec 20, 2022

lore
Share & tools
lore
#0 lore raw

PATCH 1/6 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/6 siggen: Minor code improvement

Tweak the code to remove duplication and only set if the attribute isn't already there to avoid overwriting.

---
 lib/bb/siggen.py | 6 +++---
 1 file changed, 3 insertions(+), 3 deletions(-)
lib/bb/siggen.py +3 -3
index f551c74890..0e79404f76 100644
@@ -273,11 +273,11 @@ class SignatureGeneratorBasic(SignatureGenerator):
         super().setup_datacache_from_datastore(mcfn, d)
 
         mc = bb.runqueue.mc_from_tid(mcfn)
-        setattr(self.datacaches[mc], "siggen_varvals", {})
+        for attr in ["siggen_varvals", "siggen_taskdeps", "siggen_gendeps"]:
+            if not hasattr(self.datacaches[mc], attr):
+                setattr(self.datacaches[mc], attr, {})
         self.datacaches[mc].siggen_varvals[mcfn] = d.getVar("__siggen_varvals")
-        setattr(self.datacaches[mc], "siggen_taskdeps", {})
         self.datacaches[mc].siggen_taskdeps[mcfn] = d.getVar("__siggen_taskdeps")
-        setattr(self.datacaches[mc], "siggen_gendeps", {})
         self.datacaches[mc].siggen_gendeps[mcfn] = d.getVar("__siggen_gendeps")
 
     def rundep_check(self, fn, recipename, task, dep, depname, dataCaches):
Signature · 1 line
2.37.2
#2 lore raw

PATCH 3/6 event: Add enable/disable heartbeat code

In reply to Richard Purdie

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 12498a6c47..826f6f52cc 100644
@@ -372,7 +372,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
@@ -386,7 +386,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
#3 lore raw

PATCH 4/6 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. Add in a recursive lock to avoid d being deleted from a context it shouldn't be.

---
 lib/bb/event.py | 7 +++++++
 1 file changed, 7 insertions(+)
lib/bb/event.py +7 -0
index 21e9a1b025..5df5b3a3ee 100644
@@ -68,6 +68,7 @@ _catchall_handlers = {}
 _eventfilter = None
 _uiready = False
 _thread_lock = threading.Lock()
+_builtins_lock = threading.RLock()
 _thread_lock_enabled = False
 _heartbeat_enabled = False
 
@@ -93,6 +94,9 @@ def disable_heartbeat():
     _heartbeat_enabled = False
 
 def execute_handler(name, handler, event, d):
+    if _thread_lock_enabled:
+        _builtins_lock.acquire()
+
     event.data = d
     addedd = False
     if 'd' not in builtins:
@@ -115,6 +119,9 @@ def execute_handler(name, handler, event, d):
         del event.data
         if addedd:
             del builtins['d']
+        if _thread_lock_enabled:
+            _builtins_lock.release()
+
 
 def fire_class_handlers(event, d):
     if isinstance(event, logging.LogRecord):
Signature · 1 line
2.37.2
#4 lore raw

Re: [bitbake-devel] [PATCH 4/6] event: builtins fix for 'd' deletion

Quoted 16 lines · 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. Add in a recursive lock to avoid d being deleted from a context it shouldn't be.

---
 lib/bb/event.py | 7 +++++++
 1 file changed, 7 insertions(+)
lib/bb/event.py +0 -0
index 21e9a1b025..5df5b3a3ee 100644

lib/bb/event.py _catchall_handlers = {} · line 71

Quoted 4 lines
lib/bb/event.py +1 -0
@@ -68,6 +68,7 @@ _catchall_handlers = {}
 _eventfilter = None
 _uiready = False
 _thread_lock = threading.Lock()
+_builtins_lock = threading.RLock()

Does this need to be a recursive lock?

Quoted 35 lines
lib/bb/event.py +6 -1
 _thread_lock_enabled = False
 _heartbeat_enabled = False
 
@@ -93,6 +94,9 @@ def disable_heartbeat():
     _heartbeat_enabled = False
 
 def execute_handler(name, handler, event, d):
+    if _thread_lock_enabled:
+        _builtins_lock.acquire()
+
     event.data = d
     addedd = False
     if 'd' not in builtins:
@@ -115,6 +119,9 @@ def execute_handler(name, handler, event, d):
         del event.data
         if addedd:
             del builtins['d']
+        if _thread_lock_enabled:
+            _builtins_lock.release()
+
 
 def fire_class_handlers(event, d):
     if isinstance(event, logging.LogRecord):
--

2.37.2

-=-=-=-=-=-=-=-=-=-=-=-
Links: You receive all messages sent to this group.
View/Reply Online (#14212): https://lists.openembedded.org/g/bitbake-devel/message/14212
Mute This Topic: https://lists.openembedded.org/mt/95787500/3616693
Group Owner: [email protected]
Unsubscribe: https://lists.openembedded.org/g/bitbake-devel/unsub [[email protected]]
-=-=-=-=-=-=-=-=-=-=-=-

#5 lore raw

Re: [bitbake-devel] [PATCH 4/6] event: builtins fix for 'd' deletion

Quoted 13 lines · Joshua Watt
Quoted 11 lines · 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. Add in a recursive lock to avoid d being deleted from a context it shouldn't be.

---
 lib/bb/event.py | 7 +++++++
 1 file changed, 7 insertions(+)
Quoted 11 lines

lib/bb/event.py _catchall_handlers = {} · line 71

Quoted 9 lines
lib/bb/event.py +1 -0
index 21e9a1b025..5df5b3a3ee 100644
@@ -68,6 +68,7 @@ _catchall_handlers = {}
 _eventfilter = None
 _uiready = False
 _thread_lock = threading.Lock()
+_builtins_lock = threading.RLock()

Does this need to be a recursive lock?

Yes, in testing these can be re-enterant (think an event handler that does a bb.warn()) so yes, it does need to be.

Cheers,

Richard

#6 lore raw

PATCH 5/6 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/cooker.py         | 13 +++++----
 lib/bb/server/process.py | 60 +++++++++++++++++++++++++---------------
 2 files changed, 46 insertions(+), 27 deletions(-)
lib/bb/cooker.py +8 -5
index 815610ff82..f578d2ceea 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,12 @@ 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()
+                    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
#7 lore raw

PATCH 6/6 server/process: Add bitbake.sock race handling

In reply to Richard Purdie

We've seen cases where the bitbake.sock file appears to disappear but the server continues to hold bitbake.lock. The most likely explaination is that some previous build directory was moved out the way, a server there kept running, eventually exited and removed the sock file from the wrong directory.

To guard against this, save the inode information for the sock file and check it before deleting the file. The new code isn't entirely race free but should guard against what is a rare but annoying potential issue.

---
 lib/bb/server/process.py | 12 +++++++++++-
 1 file changed, 11 insertions(+), 1 deletion(-)
lib/bb/server/process.py +11 -1
index 95e2968742..6f43330fae 100644
@@ -28,6 +28,7 @@ import datetime
 import pickle
 import traceback
 import gc
+import stat
 import bb.server.xmlrpcserver
 from bb import daemonize
 from multiprocessing import queues
@@ -94,6 +95,9 @@ class ProcessServer():
         self.bitbake_lock_name = lockname
         self.sock = sock
         self.sockname = sockname
+        # It is possible the directory may be renamed. Cache the inode of the socket file
+        # so we can tell if things changed.
+        self.sockinode = os.stat(self.sockname)[stat.ST_INO]
 
         self.server_timeout = server_timeout
         self.timeout = self.server_timeout
@@ -281,8 +285,14 @@ class ProcessServer():
 
         serverlog("Exiting (socket: %s)" % os.path.exists(self.sockname))
         # Remove the socket file so we don't get any more connections to avoid races
+        # The build directory could have been renamed so if the file isn't the one we created
+        # we shouldn't delete it.
         try:
-            os.unlink(self.sockname)
+            sockinode = os.stat(self.sockname)[stat.ST_INO]
+            if sockinode == self.sockinode:
+                os.unlink(self.sockname)
+            else:
+                serverlog("bitbake.sock inode mismatch (%s vs %s), not deleting." % (sockinode, self.sockinode))
         except Exception as err:
             serverlog("Removing socket file '%s' failed (%s)" % (self.sockname, err))
         self.sock.close()
Signature · 1 line
2.37.2