bitbake server: create common server infrastructure
PATCH 1/4 bitbake server: create common server infrastructure
From: Alexandru DAMIAN <[email protected]>
In an attempt to minimize code duplication, create clear interfaces, and maximize code reuse through OOP, bb.server adds base classes for the BitBakeServer, BitBakeServerConnection and actual server implementations instructed in particular server types.
These classes document the minimum interfaces that the derived classes must implement, and provide boilerplate code.
Changes to None, Process and XMLRPC servers as to use the common server infrastructure.
--- lib/bb/server/__init__.py | 96 +++++++++++++++++++++++++++++++++++++++++++++++ lib/bb/server/process.py | 54 +++++++++++--------------- lib/bb/server/xmlrpc.py | 64 ++++++++++++------------------- 3 files changed, 142 insertions(+), 72 deletions(-)
lib/bb/server/__init__.py +96 -0
@@ -0,0 +1,96 @@ +# +# BitBake Base Server Code +# +# Copyright (C) 2006 - 2007 Michael 'Mickey' Lauer +# Copyright (C) 2006 - 2008 Richard Purdie +# Copyright (C) 2013 Alexandru Damian +# +# This program is free software; you can redistribute it and/or modify +# it under the terms of the GNU General Public License version 2 as +# published by the Free Software Foundation. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License along +# 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. + +""" + +""" 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 + + +""" 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): + raise "Must redefine the %s.establishConnection()" % self.__class__.__name__ + + def endSession(self): + self.connection.terminate()
lib/bb/server/process.py +21 -33
120 lines not on this page · raw message
lib/bb/server/xmlrpc.py +25 -39
139 lines not on this page · raw message
Signature · 1 line
1.8.1.2
PATCH 2/4 xmlrpc: fixes for bitbake resident server
From: Alexandru DAMIAN <[email protected]>
This patch enables the XMLRPC server to remain resident in memory after a task is run, and to accept a new controlling client. To check the server after task completion, do
lsof bitbake.lock
in the build directory. Kill the server with kill.
--- lib/bb/server/xmlrpc.py | 20 +++++++++----------- 1 file changed, 9 insertions(+), 11 deletions(-)
lib/bb/server/xmlrpc.py +9 -11
@@ -227,7 +227,6 @@ class BitBakeXMLRPCRequestHandler(SimpleXMLRPCRequestHandler): self.end_headers() self.wfile.write(response) - class BitBakeUIEventServer(threading.Thread): class EventAdapter(): """
@@ -273,9 +272,10 @@ class BitBakeUIEventServer(threading.Thread): if evt: self.connection.event.sendpickle(pickle.dumps(evt)) -class BitBakeXMLRPCEventServerController(SimpleXMLRPCServer): +class BitBakeXMLRPCEventServerController(SimpleXMLRPCServer, threading.Thread): def __init__(self, interface): SimpleXMLRPCServer.__init__(self, interface, logRequests=False, allow_none=True) + threading.Thread.__init__(self) self.register_function(self.registerEventHandler, "registerEventHandler") self.register_function(self.unregisterEventHandler, "unregisterEventHandler") self.register_function(self.terminateServer, "terminateServer")
@@ -283,6 +283,7 @@ class BitBakeXMLRPCEventServerController(SimpleXMLRPCServer): self.quit = False self.clients = {} self.client_ui_ids = {} + self.timeout = 1 # timeout for .handle_request() def registerEventHandler(self, host, port): """
@@ -317,13 +318,14 @@ class BitBakeXMLRPCEventServerController(SimpleXMLRPCServer): def runCommand(self, cmd): return None - def serve_forever(self, main_server): - self.main_server = main_server + def run(self): + self.serve_forever() + + def serve_forever(self): while not self.quit: self.handle_request() self.server_close() - class XMLRPCProxyServer(BaseImplServer): """ not a real working server, but a stub for a proxy server connection
@@ -368,15 +370,11 @@ class XMLRPCServer(SimpleXMLRPCServer, BaseImplServer): def serve_forever(self): # Create and run the event server controller in a separate thread - evt_server_ctrl = BitBakeXMLRPCEventServerController((self.host, self.port + 2)) - self.event_controller_thread = threading.Thread(target = evt_server_ctrl.serve_forever, args = (self,)) + self.event_controller_thread = BitBakeXMLRPCEventServerController((self.host, self.port + 2)) self.event_controller_thread.start() # Start the actual XMLRPC server bb.cooker.server_main(self.cooker, self._serve_forever) - def removeClient(self): - self.commands.removeClient() - def _serve_forever(self): """ Serve Requests. Overloaded to honor a quit command
@@ -453,7 +451,7 @@ class BitBakeXMLRPCServerConnection(BitBakeBaseServerConnection): except: pass try: - self.connection.terminateServer() + self.connection.removeClient() except: pass
Signature · 1 line
1.8.1.2
PATCH 3/4 bitbake: fixes in executable
In reply to Alex DAMIANFrom: Alexandru DAMIAN <[email protected]>
Two fixes in bitbake related to running remote servers -
* can now specify correctly the bind port
* the information in print conforms to common server infrastructure
--- bin/bitbake | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-)
bin/bitbake +3 -2
@@ -204,7 +204,8 @@ class BitBakeConfigParameters(cookerdata.ConfigParameters): def start_server(servermodule, configParams, configuration): server = servermodule.BitBakeServer() if configParams.bind: - server.initServer((configParams.bind, 0)) + (host, port) = configParams.bind.split(':') + server.initServer((host, int(port))) else: server.initServer()
@@ -313,7 +314,7 @@ def main(): bb.event.ui_queue = [] server_connection.terminate() else: - print("server address: %s, server port: %s" % (server.serverinfo.host, server.serverinfo.port)) + print("server address: %s, server port: %s" % (server.serverImpl.host, server.serverImpl.port)) return 1
Signature · 1 line
1.8.1.2
Re: [PATCH 3/4] bitbake: fixes in executable
Quoted 16 lines · Alex DAMIAN
From: Alexandru DAMIAN <[email protected]>
Two fixes in bitbake related to running remote servers -
* can now specify correctly the bind port
* the information in print conforms to common server infrastructureSigned-off-by Alexandru DAMIAN <[email protected]>--- bin/bitbake | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-)bin/bitbake +0
-0
bin/bitbake class BitBakeConfigParameters(cookerdata.ConfigParameters): · line 207
Quoted 5 lines
bin/bitbake +1
-1@@ -204,7 +204,8 @@ class BitBakeConfigParameters(cookerdata.ConfigParameters): def start_server(servermodule, configParams, configuration): server = servermodule.BitBakeServer() if configParams.bind: - server.initServer((configParams.bind, 0)) + (host, port) = configParams.bind.split(':')
[::]:1025
I.e. Does that work nicely on my v6-only box or did you mean .rsplit(':',2) ? thanks,
Quoted 13 lines
bin/bitbake +2
-1+ server.initServer((host, int(port))) else: server.initServer()@@ -313,7 +314,7 @@ def main(): bb.event.ui_queue = [] server_connection.terminate() else: - print("server address: %s, server port: %s" % (server.serverinfo.host, server.serverinfo.port)) + print("server address: %s, server port: %s" % (server.serverImpl.host, server.serverImpl.port)) return 1
Re: [PATCH 3/4] bitbake: fixes in executable
Point taken. Unfortunately, this type of code if all over the place in
BB, so a subsequent patch will have to solve it, once we have testing environment going on for this.
I'll add this to my list, but it is low priority. Patches welcome, though :)
Alex
Quoted 45 lines · Bernhard Reutner-Fischer
bin/bitbake class
Quoted 16 lines · Alex DAMIAN
From: Alexandru DAMIAN <[email protected]>
Two fixes in bitbake related to running remote servers -
* can now specify correctly the bind port
* the information in print conforms to common server infrastructureSigned-off-by Alexandru DAMIAN <[email protected]>--- bin/bitbake | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-)bin/bitbake +0
-0@@ -204,7 +204,8 @@ classBitBakeConfigParameters(cookerdata.ConfigParameters):
bin/bitbake class BitBakeConfigParameters(cookerdata.ConfigParameters): · line 207
Quoted 5 lines
bin/bitbake +1
-1def start_server(servermodule, configParams, configuration): server = servermodule.BitBakeServer() if configParams.bind: - server.initServer((configParams.bind, 0)) + (host, port) = configParams.bind.split(':')[::]:1025
I.e. Does that work nicely on my v6-only box or did you mean .rsplit(':',2) ?
thanks,bin/bitbake def main(): · line 316
Quoted 9 lines
bin/bitbake +1
-1+ server.initServer((host, int(port))) else: server.initServer()@@ -313,7 +314,7 @@ def main(): bb.event.ui_queue = [] server_connection.terminate() else: - print("server address: %s, server port: %s" %(server.serverinfo.host, server.serverinfo.port))
bin/bitbake def main(): · line 317
Quoted 1 line
bin/bitbake +1
-0+ print("server address: %s, server port: %s" %(server.serverImpl.host, server.serverImpl.port))
Quoted 3 lines
bin/bitbake +0
-0return 1
PATCH 4/4 xmlrpc: add support for event-observer-only connection
In reply to Alex DAMIANFrom: Alexandru DAMIAN <[email protected]>
This patch adds support for multiple UI clients acting only as event syncs. Summary of changes:
bitbake: adds support for --observe-only command line parameter
xmlrpc server: create a Observer-only connection type, and small changes to accomodate new incoming parameters
event queue: add exclusive access to structures for multithreaded operation; this is needed by accepting new UI handlers on a different thread
knotty: support for observer-only connections
Other minor cosmetic changes to support new parameters to functions were made
Based on original patch by Bogdan Marinescu <[email protected]>
--- bin/bitbake | 8 ++++++- lib/bb/event.py | 63 ++++++++++++++++++++++++++++++++++--------------- lib/bb/server/xmlrpc.py | 57 +++++++++++++++++++++++++++++++++++++------- lib/bb/ui/knotty.py | 29 +++++++++++++---------- lib/bb/ui/uievent.py | 4 ++-- 5 files changed, 119 insertions(+), 42 deletions(-)
bin/bitbake +7 -1
@@ -197,6 +197,9 @@ class BitBakeConfigParameters(cookerdata.ConfigParameters): parser.add_option("", "--remote-server", help = "Connect to the specified server", action = "store", dest = "remote_server", default = False) + parser.add_option("", "--observe-only", help = "Connect to a server as an observing-only client", + action = "store_true", dest = "observe_only", default = False) + options, targets = parser.parse_args(sys.argv) return options, targets[1:]
@@ -269,6 +272,9 @@ def main(): if configParams.remote_server and configParams.servertype != "xmlrpc": sys.exit("FATAL: If '--remote-server' is defined, we must set the servertype as 'xmlrpc'.\n") + if configParams.observe_only and (not configParams.remote_server or configParams.bind): + sys.exit("FATAL: '--observe-only' can only be used by UI clients connecting to a server.\n") + if "BBDEBUG" in os.environ: level = int(os.environ["BBDEBUG"]) if level > configuration.debug:
@@ -295,7 +301,7 @@ def main(): server = start_server(servermodule, configParams, configuration) else: # we start a stub server that is actually a XMLRPClient to - server = servermodule.BitBakeXMLRPCClient() + server = servermodule.BitBakeXMLRPCClient(configParams.observe_only) server.saveConnectionDetails(configParams.remote_server) logger.removeHandler(handler)
lib/bb/event.py +44 -19
97 lines not on this page · raw message
lib/bb/server/xmlrpc.py +49 -8
116 lines not on this page · raw message
lib/bb/ui/knotty.py +17 -12
@@ -216,21 +216,28 @@ class TerminalFilter(object): fd = sys.stdin.fileno() self.termios.tcsetattr(fd, self.termios.TCSADRAIN, self.stdinbackup) -def main(server, eventHandler, params, tf = TerminalFilter): - +def _log_settings_from_server(server): # Get values of variables which control our output includelogs, error = server.runCommand(["getVariable", "BBINCLUDELOGS"]) if error: logger.error("Unable to get the value of BBINCLUDELOGS variable: %s" % error) - return 1 + raise error loglines, error = server.runCommand(["getVariable", "BBINCLUDELOGS_LINES"]) if error: logger.error("Unable to get the value of BBINCLUDELOGS_LINES variable: %s" % error) - return 1 + raise error consolelogfile, error = server.runCommand(["getVariable", "BB_CONSOLELOG"]) if error: logger.error("Unable to get the value of BB_CONSOLELOG variable: %s" % error) - return 1 + raise error + return includelogs, loglines, consolelogfile + +def main(server, eventHandler, params, tf = TerminalFilter): + + if params.observe_only: + includelogs, loglines, consolelogfile = None, None, None + else: + includelogs, loglines, consolelogfile = _log_settings_from_server(server) if sys.stdin.isatty() and sys.stdout.isatty(): log_exec_tty = True
@@ -254,7 +261,7 @@ def main(server, eventHandler, params, tf = TerminalFilter): consolelog.setFormatter(conlogformat) logger.addHandler(consolelog) - try: + if not params.observe_only: params.updateFromServer(server) cmdline = params.parseActions() if not cmdline:
@@ -271,9 +278,7 @@ def main(server, eventHandler, params, tf = TerminalFilter): elif ret != True: logger.error("Command '%s' failed: returned %s" % (cmdline, ret)) return 1 - except xmlrpclib.Fault as x: - logger.error("XMLRPC Fault getting commandline:\n %s" % x) - return 1 + parseprogress = None cacheprogress = None
@@ -320,7 +325,7 @@ def main(server, eventHandler, params, tf = TerminalFilter): elif event.levelno == format.WARNING: warnings = warnings + 1 # For "normal" logging conditions, don't show note logs from tasks - # but do show them if the user has changed the default log level to + # but do show them if the user has changed the default log level to # include verbose/debug messages if event.taskpid != 0 and event.levelno <= format.NOTE: continue
@@ -469,12 +474,12 @@ def main(server, eventHandler, params, tf = TerminalFilter): pass except KeyboardInterrupt: termfilter.clearFooter() - if main.shutdown == 1: + if not params.observe_only and main.shutdown == 1: print("\nSecond Keyboard Interrupt, stopping...\n") _, error = server.runCommand(["stateStop"]) if error: logger.error("Unable to cleanly stop: %s" % error) - if main.shutdown == 0: + if not params.observe_only and main.shutdown == 0: print("\nKeyboard Interrupt, closing down...\n") interrupted = True _, error = server.runCommand(["stateShutdown"])
lib/bb/ui/uievent.py +2 -2
@@ -28,7 +28,7 @@ import socket, threading, pickle from SimpleXMLRPCServer import SimpleXMLRPCServer, SimpleXMLRPCRequestHandler class BBUIEventQueue: - def __init__(self, BBServer, clientinfo=("localhost, 0")): + def __init__(self, BBServer, clientinfo=("localhost, 0"), replay = False): self.eventQueue = [] self.eventQueueLock = threading.Lock()
@@ -44,7 +44,7 @@ class BBUIEventQueue: server.register_function( self.send_event, "event.sendpickle" ) server.socket.settimeout(1) - self.EventHandle = self.BBServer.registerEventHandler(self.host, self.port) + self.EventHandle = self.BBServer.registerEventHandler(self.host, self.port, replay) self.server = server
Signature · 1 line
1.8.1.2
Re: [PATCH 4/4] xmlrpc: add support for event-observer-only connection
Quoted 19 lines · Alex DAMIAN
From: Alexandru DAMIAN <[email protected]>
This patch adds support for multiple UI clients acting only as event syncs. Summary of changes:
bitbake: adds support for --observe-only command line parameter
xmlrpc server: create a Observer-only connection type, and small changes to accomodate new incoming parameters
event queue: add exclusive access to structures for multithreaded operation; this is needed by accepting new UI handlers on a different thread
knotty: support for observer-only connections
Other minor cosmetic changes to support new parameters to functions were made
Based on original patch by Bogdan Marinescu <[email protected]>
Quoted 8 lines
Signed-off-by Alexandru DAMIAN <[email protected]>--- bin/bitbake | 8 ++++++- lib/bb/event.py | 63 ++++++++++++++++++++++++++++++++++--------------- lib/bb/server/xmlrpc.py | 57 +++++++++++++++++++++++++++++++++++++------- lib/bb/ui/knotty.py | 29 +++++++++++++---------- lib/bb/ui/uievent.py | 4 ++-- 5 files changed, 119 insertions(+), 42 deletions(-)
I merged the other three patches in the series. I was not happy with the commit message summary as "XXX: fixes for XXX" tells me nothing. In this case I rewrote them as examples of what looks better but please think about those a bit more in future.
For this patch I have some concerns.
Quoted 25 lines
bin/bitbake +6
-0@@ -197,6 +197,9 @@ class BitBakeConfigParameters(cookerdata.ConfigParameters): parser.add_option("", "--remote-server", help = "Connect to the specified server", action = "store", dest = "remote_server", default = False) + parser.add_option("", "--observe-only", help = "Connect to a server as an observing-only client", + action = "store_true", dest = "observe_only", default = False) + options, targets = parser.parse_args(sys.argv) return options, targets[1:]@@ -269,6 +272,9 @@ def main(): if configParams.remote_server and configParams.servertype != "xmlrpc": sys.exit("FATAL: If '--remote-server' is defined, we must set the servertype as 'xmlrpc'.\n") + if configParams.observe_only and (not configParams.remote_server or configParams.bind): + sys.exit("FATAL: '--observe-only' can only be used by UI clients connecting to a server.\n") + if "BBDEBUG" in os.environ: level = int(os.environ["BBDEBUG"]) if level > configuration.debug:
bin/bitbake def main(): · line 305
Quoted 6 lines
bin/bitbake +1
-1@@ -295,7 +301,7 @@ def main(): server = start_server(servermodule, configParams, configuration) else: # we start a stub server that is actually a XMLRPClient to - server = servermodule.BitBakeXMLRPCClient() + server = servermodule.BitBakeXMLRPCClient(configParams.observe_only) server.saveConnectionDetails(configParams.remote_server)
Do we really need a commandline option for this or is this something the UIs can figure out and do for themselves?
lib/bb/event.py import atexit · line 36
Quoted 10 lines
bin/bitbake +0
-0logger.removeHandler(handler)lib/bb/event.py +1
-0@@ -33,12 +33,15 @@ import atexit import traceback import bb.utils import bb.compat +import threading
I've already mentioned that mixing mutliprocessing and threading in bitbake has been known to cause problems. Did you investigate those issues and do we know this is safe here?
I actually don't even understand why we're locking this. Only the server process should be able to touching this queue.
Quoted 56 lines
lib/bb/event.py +21
-15# This is the pid for which we should generate the event. This is set when # the runqueue forks off. worker_pid = 0 worker_pipe = None +_ui_handlers_lock = threading.Lock() + logger = logging.getLogger('BitBake.Event') class Event(object):@@ -93,6 +96,8 @@ def fire_class_handlers(event, d): continue ui_queue = [] +_ui_event_history = [] +_ui_event_history_lock = threading.Lock() @atexit.register def print_ui_queue(): """If we're exiting before a UI has been spawned, display any queued@@ -124,22 +129,34 @@ def fire_ui_handlers(event, d): # No UI handlers registered yet, queue up the messages ui_queue.append(event) return - + _ui_event_history_lock.acquire() + _ui_event_history.append(event) + _ui_event_history_lock.release() errors = [] - for h in _ui_handlers: - #print "Sending event %s" % event - try: - # We use pickle here since it better handles object instances - # which xmlrpc's marshaller does not. Events *must* be serializable - # by pickle. - if hasattr(_ui_handlers[h].event, "sendpickle"): - _ui_handlers[h].event.sendpickle((pickle.dumps(event))) - else: - _ui_handlers[h].event.send(event) - except: - errors.append(h) - for h in errors: - del _ui_handlers[h] + _ui_handlers_lock.acquire() + try: + for h in _ui_handlers: + #print "Sending event %s" % event + try: + # We use pickle here since it better handles object instances + # which xmlrpc's marshaller does not. Events *must* be serializable + # by pickle. + if hasattr(_ui_handlers[h].event, "sendpickle"): + _ui_handlers[h].event.sendpickle((pickle.dumps(event))) + else: + _ui_handlers[h].event.send(event) + except: + errors.append(h)
lib/bb/event.py def fire_ui_handlers(event, d): · line 159
Quoted 10 lines
lib/bb/event.py +10
-0+ for h in errors: + del _ui_handlers[h] + finally: + _ui_handlers_lock.release() + +def get_event_history(): + _ui_event_history_lock.acquire() + evt_copy = _ui_event_history[:] + _ui_event_history_lock.release() + return evt_copy
I'm afraid I don't like this at all. Why do we need to keep event history? Surely the UIs are meant to query the server for current state, not rely on a reply of existing events?
Reading the code I can figure out what you're doing and why and answer my own questions. The commit message however sucks as it doesn't tell me any of this. The locking and so on also looks inappropriate and worrisome.
So this patch needs some further thought/work.
Cheers,
Richard