Skip to contentSkip to conversation

event/command: Allow UI to request the UI eventhander ID

PATCH In review Richard Purdie 1 participant 7 messages Jul 18, 2017

lore
Share & tools
lore
#0 lore raw

PATCH 1/6 event/command: Allow UI to request the UI eventhander ID

The UI may want to change its event mask however to do this, it needs the event handler's ID. Tweak the code to allow this to be stored and add a command to query it.

Use the new command in the process server backend.

---
 lib/bb/command.py        |  5 +++++
 lib/bb/event.py          | 11 ++++++++---
 lib/bb/server/process.py |  7 ++++++-
 3 files changed, 19 insertions(+), 4 deletions(-)
lib/bb/command.py +5 -0
index 36891b9..eb7c86f 100644
@@ -238,6 +238,11 @@ class CommandsSync:
         return command.cooker.matchFile(fMatch)
     matchFile.needconfig = False
 
+    def getUIHandlerNum(self, command, params):
+        return bb.event.get_uihandler()
+    getUIHandlerNum.needconfig = False
+    getUIHandlerNum.readonly = True
+
     def setEventMask(self, command, params):
         handlerNum = params[0]
         llevel = params[1]
lib/bb/event.py +8 -3
index d5c5ef3..92ee3e9 100644
@@ -288,13 +288,13 @@ def set_eventfilter(func):
     _eventfilter = func
 
 def register_UIHhandler(handler, mainui=False):
-    if mainui:
-        global _uiready
-        _uiready = True
     bb.event._ui_handler_seq = bb.event._ui_handler_seq + 1
     _ui_handlers[_ui_handler_seq] = handler
     level, debug_domains = bb.msg.constructLogOptions()
     _ui_logfilters[_ui_handler_seq] = UIEventFilter(level, debug_domains)
+    if mainui:
+        global _uiready
+        _uiready = _ui_handler_seq
     return _ui_handler_seq
 
 def unregister_UIHhandler(handlerNum, mainui=False):
@@ -305,6 +305,11 @@ def unregister_UIHhandler(handlerNum, mainui=False):
         del _ui_handlers[handlerNum]
     return
 
+def get_uihandler():
+    if _uiready is False:
+        return None
+    return _uiready
+
 # Class to allow filtering of events and specific filtering of LogRecords *before* we put them over the IPC
 class UIEventFilter(object):
     def __init__(self, level, debug_domains):
lib/bb/server/process.py +6 -1
index a8ba468..cfcd764 100644
@@ -63,7 +63,12 @@ class ServerCommunicator():
                 pass
 
     def getEventHandle(self):
-        return self.event_handle.value
+        handle, error = self.runCommand(["getUIHandlerNum"])
+        if error:
+            logger.error("Unable to get UI Handler Number: %s" % error)
+            raise BaseException(error)
+
+        return handle
 
 class EventAdapter():
     """
Signature · 1 line
2.7.4
#1 lore raw

PATCH 2/6 server: Remove base classes and inline code

In preparation for rewriting this code, expand the relatively useless base classes into the code itself.

---
 lib/bb/server/__init__.py | 72 -----------------------------------------------
 lib/bb/server/process.py  | 34 ++++++++++++++++++----
 lib/bb/server/xmlrpc.py   | 60 +++++++++++++++++++++++++++++++++------
 3 files changed, 80 insertions(+), 86 deletions(-)
lib/bb/server/__init__.py +0 -72
index 538a633..345691e 100644
@@ -25,75 +25,3 @@ approach to the interface, and minimize risks associated with code duplication.
 
 """
 
-"""  BaseImplServer() the base class for all XXServer() implementations.
-
-    These classes contain the actual code that runs the server side, i.e.
-    listens for the commands and executes them. Although these implementations
-    contain all the data of the original bitbake command, i.e the cooker instance,
-    they may well run on a different process or even machine.
-
-"""
-
-class BaseImplServer():
-    def __init__(self):
-        self._idlefuns = {}
-
-    def addcooker(self, cooker):
-        self.cooker = cooker
-
-    def register_idle_function(self, function, data):
-        """Register a function to be called while the server is idle"""
-        assert hasattr(function, '__call__')
-        self._idlefuns[function] = data
-
-
-
-""" BitBakeBaseServerConnection class is the common ancestor to all
-    BitBakeServerConnection classes.
-
-    These classes control the remote server. The only command currently
-    implemented is the terminate() command.
-
-"""
-
-class BitBakeBaseServerConnection():
-    def __init__(self, serverImpl):
-        pass
-
-    def terminate(self):
-        pass
-
-    def setupEventQueue(self):
-        pass
-
-
-""" BitBakeBaseServer class is the common ancestor to all Bitbake servers
-
-    Derive this class in order to implement a BitBakeServer which is the
-    controlling stub for the actual server implementation
-
-"""
-class BitBakeBaseServer(object):
-    def initServer(self):
-        self.serverImpl = None  # we ensure a runtime crash if not overloaded
-        self.connection = None
-        return
-
-    def addcooker(self, cooker):
-        self.cooker = cooker
-        self.serverImpl.addcooker(cooker)
-
-    def getServerIdleCB(self):
-        return self.serverImpl.register_idle_function
-
-    def saveConnectionDetails(self):
-        return
-
-    def detach(self):
-        return
-
-    def establishConnection(self, featureset):
-        raise   "Must redefine the %s.establishConnection()" % self.__class__.__name__
-
-    def endSession(self):
-        self.connection.terminate()
lib/bb/server/process.py +28 -6
index cfcd764..48da7fe 100644
@@ -33,8 +33,6 @@ import select
 from queue import Empty
 from multiprocessing import Event, Process, util, Queue, Pipe, queues, Manager
 
-from . import BitBakeBaseServer, BitBakeBaseServerConnection, BaseImplServer
-
 logger = logging.getLogger('BitBake')
 
 class ServerCommunicator():
@@ -85,12 +83,12 @@ class EventAdapter():
             print("EventAdapter puked: %s" % str(err))
 
 
-class ProcessServer(Process, BaseImplServer):
+class ProcessServer(Process):
     profile_filename = "profile.log"
     profile_processed_filename = "profile.log.processed"
 
     def __init__(self, command_channel, event_queue, featurelist):
-        BaseImplServer.__init__(self)
+        self._idlefuns = {}
         Process.__init__(self)
         self.command_channel = command_channel
         self.event_queue = event_queue
@@ -208,7 +206,15 @@ class ProcessServer(Process, BaseImplServer):
         self.quitin.send("quit")
         self.quitin.close()
 
-class BitBakeProcessServerConnection(BitBakeBaseServerConnection):
+    def addcooker(self, cooker):
+        self.cooker = cooker
+
+    def register_idle_function(self, function, data):
+        """Register a function to be called while the server is idle"""
+        assert hasattr(function, '__call__')
+        self._idlefuns[function] = data
+
+class BitBakeProcessServerConnection(object):
     def __init__(self, serverImpl, ui_channel, event_queue):
         self.procserver = serverImpl
         self.ui_channel = ui_channel
@@ -247,6 +253,9 @@ class BitBakeProcessServerConnection(BitBakeBaseServerConnection):
         # fd leakage because isn't called on Queue.close()
         self.event_queue._writer.close()
 
+    def setupEventQueue(self):
+        pass
+
 # Wrap Queue to provide API which isn't server implementation specific
 class ProcessEventQueue(multiprocessing.queues.Queue):
     def __init__(self, maxsize):
@@ -279,7 +288,7 @@ class ProcessEventQueue(multiprocessing.queues.Queue):
                 sys.exit(1)
             return None
 
-class BitBakeServer(BitBakeBaseServer):
+class BitBakeServer(object):
     def initServer(self, single_use=True):
         # establish communication channels.  We use bidirectional pipes for
         # ui <--> server command/response pairs
@@ -304,3 +313,16 @@ class BitBakeServer(BitBakeBaseServer):
             raise BaseException(error)
         signal.signal(signal.SIGTERM, lambda i, s: self.connection.sigterm_terminate())
         return self.connection
+
+    def addcooker(self, cooker):
+        self.cooker = cooker
+        self.serverImpl.addcooker(cooker)
+
+    def getServerIdleCB(self):
+        return self.serverImpl.register_idle_function
+
+    def saveConnectionDetails(self):
+        return
+
+    def endSession(self):
+        self.connection.terminate()
lib/bb/server/xmlrpc.py +52 -8

112 lines not on this page · raw message

Signature · 1 line
2.7.4
#2 lore raw

PATCH 3/6 cookerdata: Add a function to find TOPDIR

In reply to Richard Purdie

Finding the top level build directory is currently hard and relies on having a complete cooker being setup. Add a helper function which does the same thing without all the extra overhead. This is needed to be able to locate the bitbake lockfile and hence the socket for connecting clients in the new server model.

---
 lib/bb/cookerdata.py | 21 +++++++++++++++++++++
 1 file changed, 21 insertions(+)
lib/bb/cookerdata.py +21 -0
index 644bb38..aa0a641 100644
@@ -230,6 +230,27 @@ def findConfigFile(configfile, data):
 
     return None
 
+#
+# We search for a conf/bblayers.conf under an entry in BBPATH or in cwd working 
+# up to /. If that fails, we search for a conf/bitbake.conf in BBPATH.
+#
+
+def findTopdir():
+    d = bb.data.init()
+    bbpath = None
+    if 'BBPATH' in os.environ:
+        bbpath = os.environ['BBPATH']
+        d.setVar('BBPATH', bbpath)
+
+    layerconf = findConfigFile("bblayers.conf", d)
+    if layerconf:
+        return os.path.dirname(os.path.dirname(layerconf))
+    if bbpath:
+        bitbakeconf = bb.utils.which(bbpath, "conf/bitbake.conf")
+        if bitbakeconf:
+            return os.path.dirname(os.path.dirname(bitbakeconf))
+    return None
+
 class CookerDataBuilder(object):
 
     def __init__(self, cookercfg, worker = False):
Signature · 1 line
2.7.4
#3 lore raw

PATCH 4/6 daemonize: Various fixes

In reply to Richard Purdie

Currently if this code is used with something like oeqa's xml logging it fails as sys.stdout is an io stream. Add in try/except to handle this case.

Add a waitpid() call to remove a zombie whilst forking.

Also, append to the logfile, don't overwrite it (otherwise debugging can be a real pain when the server is restarting for unknown reasons).

---
 lib/bb/daemonize.py | 20 ++++++++++++--------
 1 file changed, 12 insertions(+), 8 deletions(-)
lib/bb/daemonize.py +12 -8
index ab4a954..8380828 100644
@@ -29,6 +29,7 @@ __version__ = "0.2"
 # Standard Python modules.
 import os                    # Miscellaneous OS interfaces.
 import sys                   # System-specific parameters and functions.
+import io
 
 # Default daemon parameters.
 # File mode creation mask of the daemon.
@@ -124,6 +125,7 @@ def createDaemon(function, logfile):
         # streams to be flushed twice and any temporary files may be unexpectedly
         # removed.  It's therefore recommended that child branches of a fork()
         # and the parent branch(es) of a daemon use _exit().
+        os.waitpid(pid, 0)
         return
 
     # Close all open file descriptors.  This prevents the child from keeping
@@ -177,16 +179,18 @@ def createDaemon(function, logfile):
 #    os.dup2(0, 1)                      # standard output (1)
 #    os.dup2(0, 2)                      # standard error (2)
 
-
-    si = open('/dev/null', 'r')
-    so = open(logfile, 'w')
-    se = so
-
-
     # Replace those fds with our own
+    si = open('/dev/null', 'r')
     os.dup2(si.fileno(), sys.stdin.fileno())
-    os.dup2(so.fileno(), sys.stdout.fileno())
-    os.dup2(se.fileno(), sys.stderr.fileno())
+
+    try:
+        so = open(logfile, 'a+')
+        se = so
+        os.dup2(so.fileno(), sys.stdout.fileno())
+        os.dup2(se.fileno(), sys.stderr.fileno())
+    except io.UnsupportedOperation:
+        sys.stdout = open(logfile, 'a+')
+        sys.stderr = sys.stdout
 
     function()
 
Signature · 1 line
2.7.4
#4 lore raw

PATCH 5/6 server: Rework the server API so process and xmlrpc servers coexist

In reply to Richard Purdie

This changes the way bitbake server works quite radically. Now, the server is always a process based server with the option of starting an XMLRPC listener on a specific inferface/port.

Behind the scenes this is done with a "bitbake.sock" file alongside the bitbake.lock file. If we can obtain the lock, we know we need to start a server. The server always listens on the socket and UIs can then connect to this. UIs connect by sending a set of three file descriptors over the domain socket, one for sending commands, one for receiving command results and the other for receiving events.

These changes meant we can throw away all the horrid server abstraction code, the plugable transport option to bitbake and the code becomes much more readable and debuggable. It also likely removes a ton of ways you could hang the UI/cooker in weird ways due to all the race conditions that existed with previous processes.

Changes:

* The foreground option for bitbake-server was dropped. Just tail the log if you really want this, the codepaths were complicated enough without adding one for this.
* BBSERVER="autodetect" was dropped. The server will autostart and autoconnect in process mode. You have to specify an xmlrpc server address since that can't be autodetected. I can't see a use case for autodetect now.
* The transport/servetype option to bitbake was dropped.
* A BB_SERVER_TIMEOUT variable is added which allows the server to stay resident for a period of time after the last client disconnects before unloading. This is used if the -T/--idle-timeout option is not passed to bitbake.

This change is invasive and may well introduce new issues however I believe the codebase is in a much better position for further development and debugging.

---
 lib/bb/cooker.py              |  58 +----
 lib/bb/cookerdata.py          |   5 +-
 lib/bb/main.py                | 224 +++++-----------
 lib/bb/server/__init__.py     |   6 -
 lib/bb/server/process.py      | 592 +++++++++++++++++++++++++++---------------
 lib/bb/server/process.py.orig | 323 +++++++++++++++++++++++
 lib/bb/server/xmlrpc.py       | 492 -----------------------------------
 lib/bb/server/xmlrpcclient.py | 154 +++++++++++
 lib/bb/server/xmlrpcserver.py | 158 +++++++++++
 lib/bb/tinfoil.py             |   2 +-
 lib/prserv/serv.py            |   4 +-
 11 files changed, 1102 insertions(+), 916 deletions(-)
 create mode 100644 lib/bb/server/process.py.orig
 delete mode 100644 lib/bb/server/xmlrpc.py
 create mode 100644 lib/bb/server/xmlrpcclient.py
 create mode 100644 lib/bb/server/xmlrpcserver.py
lib/bb/cooker.py +1 -57
index dc8f54c..313090b 100644
@@ -215,19 +215,6 @@ class BBCooker:
 
         self.configuration.server_register_idlecallback(_process_inotify_updates, [self.confignotifier, self.notifier])
 
-        # Take a lock so only one copy of bitbake can run against a given build
-        # directory at a time
-        if not self.lockBitbake():
-            bb.fatal("Only one copy of bitbake should be run against a build directory")
-        try:
-            self.lock.seek(0)
-            self.lock.truncate()
-            if len(configuration.interface) >= 2:
-                self.lock.write("%s:%s\n" % (configuration.interface[0], configuration.interface[1]));
-            self.lock.flush()
-        except:
-            pass
-
         # TOSTOP must not be set or our children will hang when they output
         try:
             fd = sys.stdout.fileno()
@@ -1557,33 +1544,6 @@ class BBCooker:
     def post_serve(self):
         prserv.serv.auto_shutdown(self.data)
         bb.event.fire(CookerExit(), self.data)
-        lockfile = self.lock.name
-        self.lock.close()
-        self.lock = None
-
-        while not self.lock:
-            with bb.utils.timeout(3):
-                self.lock = bb.utils.lockfile(lockfile, shared=False, retry=False, block=True)
-                if not self.lock:
-                    # Some systems may not have lsof available
-                    procs = None
-                    try:
-                        procs = subprocess.check_output(["lsof", '-w', lockfile], stderr=subprocess.STDOUT)
-                    except OSError as e:
-                        if e.errno != errno.ENOENT:
-                            raise
-                    if procs is None:
-                        # Fall back to fuser if lsof is unavailable
-                        try:
-                            procs = subprocess.check_output(["fuser", '-v', lockfile], stderr=subprocess.STDOUT)
-                        except OSError as e:
-                            if e.errno != errno.ENOENT:
-                                raise
-
-                    msg = "Delaying shutdown due to active processes which appear to be holding bitbake.lock"
-                    if procs:
-                        msg += ":\n%s" % str(procs)
-                    print(msg)
 
 
     def shutdown(self, force = False):
@@ -1605,23 +1565,7 @@ class BBCooker:
 
     def clientComplete(self):
         """Called when the client is done using the server"""
-        if self.configuration.server_only:
-            self.finishcommand()
-        else:
-            self.shutdown(True)
-
-    def lockBitbake(self):
-        if not hasattr(self, 'lock'):
-            self.lock = None
-            if self.data:
-                lockfile = self.data.expand("${TOPDIR}/bitbake.lock")
-                if lockfile:
-                    self.lock = bb.utils.lockfile(lockfile, False, False)
-        return self.lock
-
-    def unlockBitbake(self):
-        if hasattr(self, 'lock') and self.lock:
-            bb.utils.unlockfile(self.lock)
+        self.finishcommand()
 
 def server_main(cooker, func, *args):
     cooker.pre_serve()
lib/bb/cookerdata.py +3 -2
index aa0a641..9d1d3d2 100644
@@ -76,7 +76,7 @@ class ConfigParameters(object):
         for o in ["abort", "tryaltconfigs", "force", "invalidate_stamp", 
                   "verbose", "debug", "dry_run", "dump_signatures", 
                   "debug_domains", "extra_assume_provided", "profile",
-                  "prefile", "postfile", "tracking"]:
+                  "prefile", "postfile", "tracking", "server_timeout"]:
             options[o] = getattr(self.options, o)
 
         ret, error = server.runCommand(["updateConfig", options, environment, sys.argv])
@@ -144,7 +144,8 @@ class CookerConfiguration(object):
         self.dump_signatures = []
         self.dry_run = False
         self.tracking = False
-        self.interface = []
+        self.xmlrpcinterface = []
+        self.server_timeout = None
         self.writeeventlog = False
         self.server_only = False
         self.limited_deps = False
lib/bb/main.py +71 -153

320 lines not on this page · raw message

lib/bb/server/__init__.py +0 -6
index 345691e..5a3fba9 100644
@@ -18,10 +18,4 @@
 # with this program; if not, write to the Free Software Foundation, Inc.,
 # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
 
-""" Base code for Bitbake server process
-
-Have a common base for that all Bitbake server classes ensures a consistent
-approach to the interface, and minimize risks associated with code duplication.
-
-"""
 
lib/bb/server/process.py +389 -203

657 lines not on this page · raw message

lib/bb/server/process.py.orig new file +323 -0

323 lines not on this page · raw message

lib/bb/server/xmlrpc.py deleted +0 -492

492 lines not on this page · raw message

lib/bb/server/xmlrpcclient.py new file +154 -0

154 lines not on this page · raw message

lib/bb/server/xmlrpcserver.py new file +158 -0

158 lines not on this page · raw message

lib/bb/tinfoil.py +1 -1
index fb0da62..303ce02 100644
@@ -243,7 +243,7 @@ class Tinfoil:
         cookerconfig = CookerConfiguration()
         cookerconfig.setConfigParameters(config_params)
 
-        server, self.server_connection, ui_module = setup_bitbake(config_params,
+        self.server_connection, ui_module = setup_bitbake(config_params,
                             cookerconfig,
                             extrafeatures,
                             setup_logging=False)
lib/prserv/serv.py +2 -2
index a7efa58..5f061c2 100644
@@ -6,7 +6,7 @@ import queue
 import socket
 import io
 import sqlite3
-import bb.server.xmlrpc
+import bb.server.xmlrpcclient
 import prserv
 import prserv.db
 import errno
@@ -300,7 +300,7 @@ class PRServerConnection(object):
             host, port = singleton.getinfo()
         self.host = host
         self.port = port
-        self.connection, self.transport = bb.server.xmlrpc._create_server(self.host, self.port)
+        self.connection, self.transport = bb.server.xmlrpcclient._create_server(self.host, self.port)
 
     def terminate(self):
         try:
Signature · 1 line
2.7.4
#5 lore raw

Re: [PATCH 5/6] server: Rework the server API so process and xmlrpc servers coexist

Quoted 7 lines · Richard Purdie

 lib/bb/cooker.py              |  58 +---- lib/bb/cookerdata.py          |   5 +-
 lib/bb/main.py                | 224 +++++----------- lib/bb/server/__init__.py     |   6 - lib/bb/server/process.py      | 592 +++++++++++++++++++++++++++-----
----------
 lib/bb/server/process.py.orig | 323 +++++++++++++++++++++++

Spotted this sneaked in, its killed in -next.

Quoted 11 lines

 lib/bb/server/xmlrpc.py       | 492 --------------------------------
---
 lib/bb/server/xmlrpcclient.py | 154 +++++++++++ lib/bb/server/xmlrpcserver.py | 158 +++++++++++ lib/bb/tinfoil.py             |   2 +-
 lib/prserv/serv.py            |   4 +-

 11 files changed, 1102 insertions(+), 916 deletions(-)

 create mode 100644 lib/bb/server/process.py.orig
 delete mode 100644 lib/bb/server/xmlrpc.py
 create mode 100644 lib/bb/server/xmlrpcclient.py
 create mode 100644 lib/bb/server/xmlrpcserver.py

which makes the diffstat a better looking:

 10 files changed, 779 insertions(+), 916 deletions(-)

 delete mode 100644 lib/bb/server/xmlrpc.py
 create mode 100644 lib/bb/server/xmlrpcclient.py
 create mode 100644 lib/bb/server/xmlrpcserver.py

Cheers,

Richard

#6 lore raw

PATCH 6/6 cookerdata/cooker: Restore original datastore upon client disconnect

In reply to Richard Purdie
---
 lib/bb/cooker.py     | 2 ++
 lib/bb/cookerdata.py | 7 +++++++
 2 files changed, 9 insertions(+)
lib/bb/cooker.py +2 -0
index 313090b..a3058dd 100644
@@ -1566,6 +1566,8 @@ class BBCooker:
     def clientComplete(self):
         """Called when the client is done using the server"""
         self.finishcommand()
+        self.databuilder.reset()
+        self.data = self.databuilder.data
 
 def server_main(cooker, func, *args):
     cooker.pre_serve()
lib/bb/cookerdata.py +7 -0
index 9d1d3d2..e6662d0 100644
@@ -328,6 +328,13 @@ class CookerDataBuilder(object):
             logger.exception("Error parsing configuration files")
             raise bb.BBHandledException
 
+        # Create a copy so we can reset at a later date when UIs disconnect
+        self.origdata = self.data
+        self.data = bb.data.createCopy(self.origdata)
+
+    def reset(self):
+        self.data = bb.data.createCopy(self.origdata)
+
     def _findLayerConf(self, data):
         return findConfigFile("bblayers.conf", data)
 
Signature · 1 line
2.7.4