Skip to contentSkip to conversation

asyncrpc: Avoid file not found traceback in logs

PATCH In review Richard Purdie 2 participants 7 messages Jul 16, 2025 – Jul 17, 2025

lore
Share & tools
lore
#0 lore raw

PATCH 1/4 asyncrpc: Avoid file not found traceback in logs

If the server is quickly stopped, we see tracebacks in the locks due to the file not existing. Hide these as they're not errors.

---
 lib/bb/asyncrpc/serv.py | 5 ++++-
 1 file changed, 4 insertions(+), 1 deletion(-)
lib/bb/asyncrpc/serv.py +4 -1
index 667217c5c1b..35e93f7c969 100644
@@ -211,7 +211,10 @@ class UnixStreamServer(StreamServer):
         self.server.close()
 
     def cleanup(self):
-        os.unlink(self.path)
+        try:
+            os.unlink(self.path)
+        except FileNotFoundError:
+            pass
 
 
 class WebsocketsServer(object):
#1 lore raw

PATCH 2/4 cooker/process/utils: Create profiling common function to remove code duplication

We have code duplication in the way we handle profiling of code sections. Create a common function in utils which covers this.

---
 lib/bb/cooker.py         | 16 +---------------
 lib/bb/server/process.py | 33 ++-------------------------------
 lib/bb/utils.py          | 28 ++++++++++++++++++++++++++++
 3 files changed, 31 insertions(+), 46 deletions(-)
lib/bb/cooker.py +1 -15
index dc131939ed0..74b2d075d00 100644
@@ -2027,21 +2027,7 @@ class Parser(multiprocessing.Process):
             self.exit = True
 
     def run(self):
-
-        if not self.profile:
-            self.realrun()
-            return
-
-        try:
-            import cProfile as profile
-        except:
-            import profile
-        prof = profile.Profile()
-        try:
-            profile.Profile.runcall(prof, self.realrun)
-        finally:
-            logfile = "profile-parse-%s.log" % multiprocessing.current_process().name
-            prof.dump_stats(logfile)
+        bb.utils.profle_function(self.profile, self.realrun, "profile-parse-%s.log" % multiprocessing.current_process().name, process=False)
 
     def realrun(self):
         # Signal handling here is hard. We must not terminate any process or thread holding the write
lib/bb/server/process.py +2 -31
index 4b35be62cd7..78d0a606e23 100644
@@ -140,23 +140,7 @@ class ProcessServer():
             serverlog("Error writing to lock file: %s" % str(e))
             pass
 
-        if self.cooker.configuration.profile:
-            try:
-                import cProfile as profile
-            except:
-                import profile
-            prof = profile.Profile()
-
-            ret = profile.Profile.runcall(prof, self.main)
-
-            prof.dump_stats("profile.log")
-            bb.utils.process_profilelog("profile.log")
-            serverlog("Raw profiling information saved to profile.log and processed statistics to profile.log.processed")
-
-        else:
-            ret = self.main()
-
-        return ret
+        return bb.utils.profle_function(self.cooker.configuration.profile, self.main, "profile.log")
 
     def _idle_check(self):
         return len(self._idlefuns) == 0 and self.cooker.command.currentAsyncCommand is None
@@ -417,20 +401,7 @@ class ProcessServer():
                 serverlog("".join(msg))
 
     def idle_thread(self):
-        if self.cooker.configuration.profile:
-            try:
-                import cProfile as profile
-            except:
-                import profile
-            prof = profile.Profile()
-
-            ret = profile.Profile.runcall(prof, self.idle_thread_internal)
-
-            prof.dump_stats("profile-mainloop.log")
-            bb.utils.process_profilelog("profile-mainloop.log")
-            serverlog("Raw profiling information saved to profile-mainloop.log and processed statistics to profile-mainloop.log.processed")
-        else:
-            self.idle_thread_internal()
+        bb.utils.profle_function(self.cooker.configuration.profile, self.idle_thread_internal, "profile-idleloop.log")
 
     def idle_thread_internal(self):
         def remove_idle_func(function):
lib/bb/utils.py +28 -0
index 1cc74ed5466..0289862c5dd 100644
@@ -1418,6 +1418,34 @@ def cpu_count():
 def nonblockingfd(fd):
     fcntl.fcntl(fd, fcntl.F_SETFL, fcntl.fcntl(fd, fcntl.F_GETFL) | os.O_NONBLOCK)
 
+def profle_function(profile, function, output_fn, process=True):
+    """Common function to profile a code block and optionally process the
+    output using or processing function.
+
+    Arguments:
+
+    -  ``profile``: a boolean saying whether to enable profiling or not
+    -  ``function``: the function call to profile/run
+    -  ``outputfn``: where to write the profiling data
+    -  ``process``: whether to process the profiling data and write a report
+
+    Returns the wrapped function return value
+    """
+    if profile:
+        try:
+            import cProfile as profile
+        except:
+             import profile
+        prof = profile.Profile()
+        ret = profile.Profile.runcall(prof, function)
+        prof.dump_stats(output_fn)
+        if process:
+            process_profilelog(output_fn)
+            serverlog("Raw profiling information saved to %s and processed statistics to %s.processed" % (output_fn, output_fn))
+        return ret
+    else:
+        return function()
+
 def process_profilelog(fn, pout = None):
     # Either call with a list of filenames and set pout or a filename and optionally pout.
     if not pout:
#2 lore raw

PATCH 3/4 event: Fix an event duplication race

In reply to Richard Purdie

It is possible for multple bitbake threads to empty ui_queue in parallel leading to duplicate console messages and much confusion when debuging.

Use the lock to extract the queue data which means only one thread will processing, removing the duplicate out of order messages.

---
 lib/bb/event.py | 7 +++++--
 1 file changed, 5 insertions(+), 2 deletions(-)
lib/bb/event.py +5 -2
index b29f0a55687..2256fed7648 100644
@@ -236,9 +236,12 @@ def fire(event, d):
         # If messages have been queued up, clear the queue
         global _uiready, ui_queue
         if _uiready and ui_queue:
-            for queue_event in ui_queue:
+            with bb.utils.lock_timeout_nocheck(_thread_lock):
+                queue = ui_queue
+                ui_queue = []
+            for queue_event in queue:
                 fire_ui_handlers(queue_event, d)
-            ui_queue = []
+
         fire_ui_handlers(event, d)
 
 def fire_from_worker(event, d):
#3 lore raw

Re: [bitbake-devel] [PATCH 3/4] event: Fix an event duplication race

Quoted 17 lines · Richard Purdie via lists.openembedded.org

It is possible for multple bitbake threads to empty ui_queue in parallel leading to duplicate console messages and much confusion when debuging.

Use the lock to extract the queue data which means only one thread will processing, removing the duplicate out of order messages.

---
 lib/bb/event.py | 7 +++++--
 1 file changed, 5 insertions(+), 2 deletions(-)
lib/bb/event.py +0 -0
index b29f0a55687..2256fed7648 100644

lib/bb/event.py def fire(event, d): · line 242

Quoted 8 lines
lib/bb/event.py +4 -1
@@ -236,9 +236,12 @@ def fire(event, d):
         # If messages have been queued up, clear the queue
         global _uiready, ui_queue
         if _uiready and ui_queue:
-            for queue_event in ui_queue:
+            with bb.utils.lock_timeout_nocheck(_thread_lock):
+                queue = ui_queue
+                ui_queue = []
+            for queue_event in queue:

Do we even need this code anymore? fire_ui_handlers() has a loop to process all the events anyway (although, it looks like it probably should have some locking also, maybe:

while True:
try:

    i = ui_queue.pop()

except IndexError:
break
fire_ui_handler(i)

would work in a lock-less way (or rather, use the GIL as the lock instead).

Quoted 15 lines
lib/bb/event.py +1 -2
                 fire_ui_handlers(queue_event, d)
-            ui_queue = []
+
         fire_ui_handlers(event, d)
 
 def fire_from_worker(event, d):
 
-=-=-=-=-=-=-=-=-=-=-=-

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

#4 lore raw

Re: [bitbake-devel] [PATCH 3/4] event: Fix an event duplication race

Quoted 41 lines · Joshua Watt
Quoted 18 lines · Richard Purdie via lists.openembedded.org

It is possible for multple bitbake threads to empty ui_queue in parallel leading to duplicate console messages and much confusion when debuging.

Use the lock to extract the queue data which means only one thread will processing, removing the duplicate out of order messages.

---
 lib/bb/event.py | 7 +++++--

 1 file changed, 5 insertions(+), 2 deletions(-)
lib/bb/event.py +0 -0
index b29f0a55687..2256fed7648 100644
@@ -236,9 +236,12 @@ def fire(event, d):
          # If messages have been queued up, clear the queue
Quoted 7 lines

         global _uiready, ui_queue
         if _uiready and ui_queue:
-            for queue_event in ui_queue:
+            with bb.utils.lock_timeout_nocheck(_thread_lock):
+                queue = ui_queue
+                ui_queue = []
+            for queue_event in queue:

Do we even need this code anymore? fire_ui_handlers() has a loop to process all the events anyway (although, it looks like it probably should have some locking also, maybe:

while True:
  try:
    i = ui_queue.pop()
  except IndexError:
    break
  fire_ui_handler(i)

Quoted 1 line

would work in a lock-less way (or rather, use the GIL as the lock instead).

We do need this to queue things before the UI handlers are present.

There is actually locking present elsewhere in the fire code, it just works on a per event basis rather than for a group, hence the code difference.

Cheers,

Richard

#5 lore raw

PATCH 4/4 main: Add an option to specify what to profile

In reply to Richard Purdie

Starting with python 3.12, profiling now stays enabled over threads yet you can't extract the profile data in the threads themselves, which makes it difficult to use for our use case.

Our main loop starts the idle loop which starts the parsing threads and this means we can't profile in the main loop and the parsing threads or the idle loop at the same time due to this.

Add options to the commandline so you can specify which piece of bitbake you want to enable profiling for. This allows some profiling with python 3.12 onwards rather than crashing.

---
 bin/bitbake-server       | 2 +-
 lib/bb/cooker.py         | 2 +-
 lib/bb/main.py           | 6 ++++--
 lib/bb/server/process.py | 6 +++---
 4 files changed, 9 insertions(+), 7 deletions(-)
bin/bitbake-server +1 -1
index a559109e3f5..7a13de60de6 100755
@@ -30,7 +30,7 @@ logfile = sys.argv[4]
 lockname = sys.argv[5]
 sockname = sys.argv[6]
 timeout = float(sys.argv[7])
-profile = bool(int(sys.argv[8]))
+profile = list(sys.argv[8])
 xmlrpcinterface = (sys.argv[9], int(sys.argv[10]))
 if xmlrpcinterface[0] == "None":
     xmlrpcinterface = (None, xmlrpcinterface[1])
lib/bb/cooker.py +1 -1
index 74b2d075d00..260cba1e212 100644
@@ -2027,7 +2027,7 @@ class Parser(multiprocessing.Process):
             self.exit = True
 
     def run(self):
-        bb.utils.profle_function(self.profile, self.realrun, "profile-parse-%s.log" % multiprocessing.current_process().name, process=False)
+        bb.utils.profle_function("parsing" in self.profile, self.realrun, "profile-parse-%s.log" % multiprocessing.current_process().name, process=False)
 
     def realrun(self):
         # Signal handling here is hard. We must not terminate any process or thread holding the write
lib/bb/main.py +4 -2
index bca8ebfa090..597cb278464 100755
@@ -208,8 +208,10 @@ def create_bitbake_parser():
                              "failed and anything depending on it cannot be built, as much as "
                              "possible will be built before stopping.")
 
-    exec_group.add_argument("-P", "--profile", action="store_true",
-                        help="Profile the command and save reports.")
+    exec_group.add_argument("-P", "--profile", action="append",
+                        default=[],
+                        help="Profile the command and save reports. Specify 'main', 'idle' or 'parsing' "
+                             "to indicate which bitbake code to profile.")
 
     exec_group.add_argument("-S", "--dump-signatures", action="append",
                         default=[], metavar="SIGNATURE_HANDLER",
lib/bb/server/process.py +3 -3
index 78d0a606e23..da3f833f1d5 100644
@@ -140,7 +140,7 @@ class ProcessServer():
             serverlog("Error writing to lock file: %s" % str(e))
             pass
 
-        return bb.utils.profle_function(self.cooker.configuration.profile, self.main, "profile.log")
+        return bb.utils.profle_function("main" in self.cooker.configuration.profile, self.main, "profile.log")
 
     def _idle_check(self):
         return len(self._idlefuns) == 0 and self.cooker.command.currentAsyncCommand is None
@@ -401,7 +401,7 @@ class ProcessServer():
                 serverlog("".join(msg))
 
     def idle_thread(self):
-        bb.utils.profle_function(self.cooker.configuration.profile, self.idle_thread_internal, "profile-idleloop.log")
+        bb.utils.profle_function("idle" in self.cooker.configuration.profile, self.idle_thread_internal, "profile-idleloop.log")
 
     def idle_thread_internal(self):
         def remove_idle_func(function):
@@ -603,7 +603,7 @@ class BitBakeServer(object):
         os.set_inheritable(self.bitbake_lock.fileno(), True)
         os.set_inheritable(self.readypipein, True)
         serverscript = os.path.realpath(os.path.dirname(__file__) + "/../../../bin/bitbake-server")
-        os.execl(sys.executable, sys.executable, serverscript, "decafbad", str(self.bitbake_lock.fileno()), str(self.readypipein), self.logfile, self.bitbake_lock.name, self.sockname,  str(self.server_timeout or 0), str(int(self.profile)), str(self.xmlrpcinterface[0]), str(self.xmlrpcinterface[1]))
+        os.execl(sys.executable, sys.executable, serverscript, "decafbad", str(self.bitbake_lock.fileno()), str(self.readypipein), self.logfile, self.bitbake_lock.name, self.sockname,  str(self.server_timeout or 0), str(list(self.profile)), str(self.xmlrpcinterface[0]), str(self.xmlrpcinterface[1]))
 
 def execServer(lockfd, readypipeinfd, lockname, sockname, server_timeout, xmlrpcinterface, profile):
 
Reviewed-by on v1 1/4
#6 lore raw
In reply to Richard Purdie

LGTM

Quoted 34 lines · Richard Purdie via lists.openembedded.org

If the server is quickly stopped, we see tracebacks in the locks due to the file not existing. Hide these as they're not errors.

---
 lib/bb/asyncrpc/serv.py | 5 ++++-
 1 file changed, 4 insertions(+), 1 deletion(-)
lib/bb/asyncrpc/serv.py +4 -2
index 667217c5c1b..35e93f7c969 100644
@@ -211,7 +211,10 @@ class UnixStreamServer(StreamServer):
         self.server.close()
 
     def cleanup(self):
-        os.unlink(self.path)
+        try:
+            os.unlink(self.path)
+        except FileNotFoundError:
+            pass
 
 
 class WebsocketsServer(object):
 
-=-=-=-=-=-=-=-=-=-=-=-

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