Skip to contentSkip to conversation

process: Avoid printing binary strings for leftover processes

PATCH New Richard Purdie 1 participant 4 messages Sep 4, 2020

lore
Share & tools
lore
#0 lore raw

PATCH 1/4 process: Avoid printing binary strings for leftover processes

The binary string printed into the output is ugly, parse this so the linebreaks come out in the logs and make them much more readable (I was misssing the information initially despite looking for it).

---
 lib/bb/server/process.py | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)
lib/bb/server/process.py +1 -1
index c972fe567d..5b4d92dc80 100644
@@ -295,7 +295,7 @@ class ProcessServer():
 
                 msg = "Delaying shutdown due to active processes which appear to be holding bitbake.lock"
                 if procs:
-                    msg += ":\n%s" % str(procs)
+                    msg += ":\n%s" % str(procs.decode("utf-8"))
                 print(msg)
 
     def idle_commands(self, delay, fds=None):
Signature · 1 line
2.25.1
#1 lore raw

PATCH 2/4 server/process: Ensure logging is flushed

The cookerlog output goes to a file and its misleading to look at it and not have it up to date with what the cooker is actually doing. Ensure written data is flushed.

Ultimately this should be using python's logging but that is for another day, we need simple fixes right now.

---
 lib/bb/server/process.py | 44 +++++++++++++++++++++-------------------
 1 file changed, 23 insertions(+), 21 deletions(-)
lib/bb/server/process.py +23 -21
index 5b4d92dc80..2be4588a4f 100644
@@ -35,6 +35,10 @@ logger = logging.getLogger('BitBake')
 class ProcessTimeout(SystemExit):
     pass
 
+def serverlog(msg):
+    print(msg)
+    sys.stdout.flush()
+
 class ProcessServer():
     profile_filename = "profile.log"
     profile_processed_filename = "profile.log.processed"
@@ -73,7 +77,7 @@ class ProcessServer():
         if self.xmlrpcinterface[0]:
             self.xmlrpc = bb.server.xmlrpcserver.BitBakeXMLRPCServer(self.xmlrpcinterface, self.cooker, self)
 
-            print("Bitbake XMLRPC server address: %s, server port: %s" % (self.xmlrpc.host, self.xmlrpc.port))
+            serverlog("Bitbake XMLRPC server address: %s, server port: %s" % (self.xmlrpc.host, self.xmlrpc.port))
 
         try:
             self.bitbake_lock.seek(0)
@@ -84,7 +88,7 @@ class ProcessServer():
                 self.bitbake_lock.write("%s\n" % (os.getpid()))
             self.bitbake_lock.flush()
         except Exception as e:
-            print("Error writing to lock file: %s" % str(e))
+            serverlog("Error writing to lock file: %s" % str(e))
             pass
 
         if self.cooker.configuration.profile:
@@ -98,7 +102,7 @@ class ProcessServer():
 
             prof.dump_stats("profile.log")
             bb.utils.process_profilelog("profile.log")
-            print("Raw profiling information saved to profile.log and processed statistics to profile.log.processed")
+            serverlog("Raw profiling information saved to profile.log and processed statistics to profile.log.processed")
 
         else:
             ret = self.main()
@@ -118,10 +122,10 @@ class ProcessServer():
         if self.xmlrpc:
             fds.append(self.xmlrpc)
         seendata = False
-        print("Entering server connection loop")
+        serverlog("Entering server connection loop")
 
         def disconnect_client(self, fds):
-            print("Disconnecting Client")
+            serverlog("Disconnecting Client")
             if self.controllersock:
                 fds.remove(self.controllersock)
                 self.controllersock.close()
@@ -139,12 +143,12 @@ class ProcessServer():
                 self.haveui = False
             ready = select.select(fds,[],[],0)[0]
             if newconnections:
-                print("Starting new client")
+                serverlog("Starting new client")
                 conn = newconnections.pop(-1)
                 fds.append(conn)
                 self.controllersock = conn
             elif self.timeout is None and not ready:
-                print("No timeout, exiting.")
+                serverlog("No timeout, exiting.")
                 self.quit = True
 
         self.lastui = time.time()
@@ -153,17 +157,17 @@ class ProcessServer():
                 while select.select([self.sock],[],[],0)[0]:
                     controllersock, address = self.sock.accept()
                     if self.controllersock:
-                        print("Queuing %s (%s)" % (str(ready), str(newconnections)))
+                        serverlog("Queuing %s (%s)" % (str(ready), str(newconnections)))
                         newconnections.append(controllersock)
                     else:
-                        print("Accepting %s (%s)" % (str(ready), str(newconnections)))
+                        serverlog("Accepting %s (%s)" % (str(ready), str(newconnections)))
                         self.controllersock = controllersock
                         fds.append(controllersock)
             if self.controllersock in ready:
                 try:
-                    print("Processing Client")
+                    serverlog("Processing Client")
                     ui_fds = recvfds(self.controllersock, 3)
-                    print("Connecting Client")
+                    serverlog("Connecting Client")
 
                     # Where to write events to
                     writer = ConnectionWriter(ui_fds[0])
@@ -187,14 +191,14 @@ class ProcessServer():
 
             if not self.timeout == -1.0 and not self.haveui and self.timeout and \
                     (self.lastui + self.timeout) < time.time():
-                print("Server timeout, exiting.")
+                serverlog("Server timeout, exiting.")
                 self.quit = True
 
             # If we don't see a UI connection within maxuiwait, its unlikely we're going to see
             # one. We have had issue with processes hanging indefinitely so timing out UI-less
             # servers is useful.
             if not self.hadanyui and not self.xmlrpc and not self.timeout and (self.lastui + self.maxuiwait) < time.time():
-                print("No UI connection within max timeout, exiting to avoid infinite loop.")
+                serverlog("No UI connection within max timeout, exiting to avoid infinite loop.")
                 self.quit = True
 
             if self.command_channel in ready:
@@ -209,7 +213,7 @@ class ProcessServer():
                     self.quit = True
                     continue
                 try:
-                    print("Running command %s" % command)
+                    serverlog("Running command %s" % command)
                     self.command_channel_reply.send(self.cooker.command.runCommand(command))
                 except Exception as e:
                    logger.exception('Exception in server main event loop running command %s (%s)' % (command, str(e)))
@@ -236,9 +240,9 @@ class ProcessServer():
             ready = self.idle_commands(.1, fds)
 
         if len(threading.enumerate()) != 1:
-            print("More than one thread left?: " + str(threading.enumerate()))
+            serverlog("More than one thread left?: " + str(threading.enumerate()))
 
-        print("Exiting")
+        serverlog("Exiting")
         # Remove the socket file so we don't get any more connections to avoid races
         try:
             os.unlink(self.sockname)
@@ -296,7 +300,7 @@ class ProcessServer():
                 msg = "Delaying shutdown due to active processes which appear to be holding bitbake.lock"
                 if procs:
                     msg += ":\n%s" % str(procs.decode("utf-8"))
-                print(msg)
+                serverlog(msg)
 
     def idle_commands(self, delay, fds=None):
         nextsleep = delay
@@ -485,8 +489,7 @@ def execServer(lockfd, readypipeinfd, lockname, sockname, server_timeout, xmlrpc
     import bb.cookerdata
     import bb.cooker
 
-    print(start_log_format % (os.getpid(), datetime.datetime.now().strftime(start_log_datetime_format)))
-    sys.stdout.flush()
+    serverlog(start_log_format % (os.getpid(), datetime.datetime.now().strftime(start_log_datetime_format)))
 
     try:
         bitbake_lock = os.fdopen(lockfd, "w")
@@ -515,8 +518,7 @@ def execServer(lockfd, readypipeinfd, lockname, sockname, server_timeout, xmlrpc
         writer.send("r")
         writer.close()
         server.cooker = cooker
-        print("Started bitbake server pid %d" % os.getpid())
-        sys.stdout.flush()
+        serverlog("Started bitbake server pid %d" % os.getpid())
 
         server.run()
     finally:
Signature · 1 line
2.25.1
#2 lore raw

PATCH 3/4 server/process: Ensure we don't keep looping if some other server is started

In reply to Richard Purdie

Shwoing "leftover process" messages when a new server has started and is being used by some UI is horrible. Compare the PID data from the lockfile to avoid this (and the ton of confusing log data it generates).

---
 lib/bb/server/process.py | 11 +++++++++++
 1 file changed, 11 insertions(+)
lib/bb/server/process.py +11 -0
index 2be4588a4f..47e687f4ef 100644
@@ -266,10 +266,21 @@ class ProcessServer():
         # Finally release the lockfile but warn about other processes holding it open
         lock = self.bitbake_lock
         lockfile = self.bitbake_lock_name
+        with open(lockfile, "r") as f:
+            lockcontents = f.readlines()
+
         lock.close()
         lock = None
 
         while not lock:
+            try:
+                with open(lockfile, "r") as f:
+                    lockcontents2 = f.readlines()
+            except FileNotFoundError:
+                return
+            if lockcontents2 != lockcontents:
+                # A new server was started, the lockfile contents changed, we can exit
+                return
             i = 0
             lock = None
             while not lock and i < 30:
Signature · 1 line
2.25.1
#3 lore raw

PATCH 4/4 server/process: Don't show tracebacks if the lockfile is removed

In reply to Richard Purdie

lsof/fuser error if the file doesn't exist. It can be deleted by something else so ignore this if it happens and loop.

---
 lib/bb/server/process.py | 6 ++++++
 1 file changed, 6 insertions(+)
lib/bb/server/process.py +6 -0
index 47e687f4ef..0871e50ce3 100644
@@ -297,6 +297,9 @@ class ProcessServer():
                 procs = None
                 try:
                     procs = subprocess.check_output(["lsof", '-w', lockfile], stderr=subprocess.STDOUT)
+                except subprocess.CalledProcessError:
+                    # File was deleted?
+                    continue
                 except OSError as e:
                     if e.errno != errno.ENOENT:
                         raise
@@ -304,6 +307,9 @@ class ProcessServer():
                     # Fall back to fuser if lsof is unavailable
                     try:
                         procs = subprocess.check_output(["fuser", '-v', lockfile], stderr=subprocess.STDOUT)
+                    except subprocess.CalledProcessError:
+                        # File was deleted?
+                        continue
                     except OSError as e:
                         if e.errno != errno.ENOENT:
                             raise
Signature · 1 line
2.25.1