xmlrpc.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392
  1. #
  2. # BitBake XMLRPC Server
  3. #
  4. # Copyright (C) 2006 - 2007 Michael 'Mickey' Lauer
  5. # Copyright (C) 2006 - 2008 Richard Purdie
  6. #
  7. # This program is free software; you can redistribute it and/or modify
  8. # it under the terms of the GNU General Public License version 2 as
  9. # published by the Free Software Foundation.
  10. #
  11. # This program is distributed in the hope that it will be useful,
  12. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  13. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  14. # GNU General Public License for more details.
  15. #
  16. # You should have received a copy of the GNU General Public License along
  17. # with this program; if not, write to the Free Software Foundation, Inc.,
  18. # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
  19. """
  20. This module implements an xmlrpc server for BitBake.
  21. Use this by deriving a class from BitBakeXMLRPCServer and then adding
  22. methods which you want to "export" via XMLRPC. If the methods have the
  23. prefix xmlrpc_, then registering those function will happen automatically,
  24. if not, you need to call register_function.
  25. Use register_idle_function() to add a function which the xmlrpc server
  26. calls from within server_forever when no requests are pending. Make sure
  27. that those functions are non-blocking or else you will introduce latency
  28. in the server's main loop.
  29. """
  30. import os
  31. import sys
  32. import hashlib
  33. import time
  34. import socket
  35. import signal
  36. import threading
  37. import pickle
  38. import inspect
  39. import select
  40. import http.client
  41. import xmlrpc.client
  42. from xmlrpc.server import SimpleXMLRPCServer, SimpleXMLRPCRequestHandler
  43. import bb
  44. from bb import daemonize
  45. from bb.ui import uievent
  46. from . import BitBakeBaseServer, BitBakeBaseServerConnection, BaseImplServer
  47. DEBUG = False
  48. class BBTransport(xmlrpc.client.Transport):
  49. def __init__(self, timeout):
  50. self.timeout = timeout
  51. self.connection_token = None
  52. xmlrpc.client.Transport.__init__(self)
  53. # Modified from default to pass timeout to HTTPConnection
  54. def make_connection(self, host):
  55. #return an existing connection if possible. This allows
  56. #HTTP/1.1 keep-alive.
  57. if self._connection and host == self._connection[0]:
  58. return self._connection[1]
  59. # create a HTTP connection object from a host descriptor
  60. chost, self._extra_headers, x509 = self.get_host_info(host)
  61. #store the host argument along with the connection object
  62. self._connection = host, http.client.HTTPConnection(chost, timeout=self.timeout)
  63. return self._connection[1]
  64. def set_connection_token(self, token):
  65. self.connection_token = token
  66. def send_content(self, h, body):
  67. if self.connection_token:
  68. h.putheader("Bitbake-token", self.connection_token)
  69. xmlrpc.client.Transport.send_content(self, h, body)
  70. def _create_server(host, port, timeout = 60):
  71. t = BBTransport(timeout)
  72. s = xmlrpc.client.ServerProxy("http://%s:%d/" % (host, port), transport=t, allow_none=True, use_builtin_types=True)
  73. return s, t
  74. class BitBakeServerCommands():
  75. def __init__(self, server):
  76. self.server = server
  77. self.has_client = False
  78. def registerEventHandler(self, host, port):
  79. """
  80. Register a remote UI Event Handler
  81. """
  82. s, t = _create_server(host, port)
  83. # we don't allow connections if the cooker is running
  84. if (self.cooker.state in [bb.cooker.state.parsing, bb.cooker.state.running]):
  85. return None, "Cooker is busy: %s" % bb.cooker.state.get_name(self.cooker.state)
  86. self.event_handle = bb.event.register_UIHhandler(s, True)
  87. return self.event_handle, 'OK'
  88. def unregisterEventHandler(self, handlerNum):
  89. """
  90. Unregister a remote UI Event Handler
  91. """
  92. return bb.event.unregister_UIHhandler(handlerNum)
  93. def runCommand(self, command):
  94. """
  95. Run a cooker command on the server
  96. """
  97. return self.cooker.command.runCommand(command, self.server.readonly)
  98. def getEventHandle(self):
  99. return self.event_handle
  100. def terminateServer(self):
  101. """
  102. Trigger the server to quit
  103. """
  104. self.server.quit = True
  105. print("Server (cooker) exiting")
  106. return
  107. def addClient(self):
  108. if self.has_client:
  109. return None
  110. token = hashlib.md5(str(time.time()).encode("utf-8")).hexdigest()
  111. self.server.set_connection_token(token)
  112. self.has_client = True
  113. return token
  114. def removeClient(self):
  115. if self.has_client:
  116. self.server.set_connection_token(None)
  117. self.has_client = False
  118. if self.server.single_use:
  119. self.server.quit = True
  120. # This request handler checks if the request has a "Bitbake-token" header
  121. # field (this comes from the client side) and compares it with its internal
  122. # "Bitbake-token" field (this comes from the server). If the two are not
  123. # equal, it is assumed that a client is trying to connect to the server
  124. # while another client is connected to the server. In this case, a 503 error
  125. # ("service unavailable") is returned to the client.
  126. class BitBakeXMLRPCRequestHandler(SimpleXMLRPCRequestHandler):
  127. def __init__(self, request, client_address, server):
  128. self.server = server
  129. SimpleXMLRPCRequestHandler.__init__(self, request, client_address, server)
  130. def do_POST(self):
  131. try:
  132. remote_token = self.headers["Bitbake-token"]
  133. except:
  134. remote_token = None
  135. if remote_token != self.server.connection_token and remote_token != "observer":
  136. self.report_503()
  137. else:
  138. if remote_token == "observer":
  139. self.server.readonly = True
  140. else:
  141. self.server.readonly = False
  142. SimpleXMLRPCRequestHandler.do_POST(self)
  143. def report_503(self):
  144. self.send_response(503)
  145. response = 'No more client allowed'
  146. self.send_header("Content-type", "text/plain")
  147. self.send_header("Content-length", str(len(response)))
  148. self.end_headers()
  149. self.wfile.write(response)
  150. class XMLRPCProxyServer(BaseImplServer):
  151. """ not a real working server, but a stub for a proxy server connection
  152. """
  153. def __init__(self, host, port):
  154. self.host = host
  155. self.port = port
  156. class XMLRPCServer(SimpleXMLRPCServer, BaseImplServer):
  157. # remove this when you're done with debugging
  158. # allow_reuse_address = True
  159. def __init__(self, interface, single_use=False):
  160. """
  161. Constructor
  162. """
  163. BaseImplServer.__init__(self)
  164. self.single_use = single_use
  165. # Use auto port configuration
  166. if (interface[1] == -1):
  167. interface = (interface[0], 0)
  168. SimpleXMLRPCServer.__init__(self, interface,
  169. requestHandler=BitBakeXMLRPCRequestHandler,
  170. logRequests=False, allow_none=True)
  171. self.host, self.port = self.socket.getsockname()
  172. self.connection_token = None
  173. #self.register_introspection_functions()
  174. self.commands = BitBakeServerCommands(self)
  175. self.autoregister_all_functions(self.commands, "")
  176. self.interface = interface
  177. def addcooker(self, cooker):
  178. BaseImplServer.addcooker(self, cooker)
  179. self.commands.cooker = cooker
  180. def autoregister_all_functions(self, context, prefix):
  181. """
  182. Convenience method for registering all functions in the scope
  183. of this class that start with a common prefix
  184. """
  185. methodlist = inspect.getmembers(context, inspect.ismethod)
  186. for name, method in methodlist:
  187. if name.startswith(prefix):
  188. self.register_function(method, name[len(prefix):])
  189. def serve_forever(self):
  190. # Start the actual XMLRPC server
  191. bb.cooker.server_main(self.cooker, self._serve_forever)
  192. def _serve_forever(self):
  193. """
  194. Serve Requests. Overloaded to honor a quit command
  195. """
  196. self.quit = False
  197. while not self.quit:
  198. fds = [self]
  199. nextsleep = 0.1
  200. for function, data in list(self._idlefuns.items()):
  201. retval = None
  202. try:
  203. retval = function(self, data, False)
  204. if retval is False:
  205. del self._idlefuns[function]
  206. elif retval is True:
  207. nextsleep = 0
  208. elif isinstance(retval, float):
  209. if (retval < nextsleep):
  210. nextsleep = retval
  211. else:
  212. fds = fds + retval
  213. except SystemExit:
  214. raise
  215. except:
  216. import traceback
  217. traceback.print_exc()
  218. if retval == None:
  219. # the function execute failed; delete it
  220. del self._idlefuns[function]
  221. pass
  222. socktimeout = self.socket.gettimeout() or nextsleep
  223. socktimeout = min(socktimeout, nextsleep)
  224. # Mirror what BaseServer handle_request would do
  225. try:
  226. fd_sets = select.select(fds, [], [], socktimeout)
  227. if fd_sets[0] and self in fd_sets[0]:
  228. self._handle_request_noblock()
  229. except IOError:
  230. # we ignore interrupted calls
  231. pass
  232. # Tell idle functions we're exiting
  233. for function, data in list(self._idlefuns.items()):
  234. try:
  235. retval = function(self, data, True)
  236. except:
  237. pass
  238. self.server_close()
  239. return
  240. def set_connection_token(self, token):
  241. self.connection_token = token
  242. class BitBakeXMLRPCServerConnection(BitBakeBaseServerConnection):
  243. def __init__(self, serverImpl, clientinfo=("localhost", 0), observer_only = False, featureset = None):
  244. self.connection, self.transport = _create_server(serverImpl.host, serverImpl.port)
  245. self.clientinfo = clientinfo
  246. self.serverImpl = serverImpl
  247. self.observer_only = observer_only
  248. if featureset:
  249. self.featureset = featureset
  250. else:
  251. self.featureset = []
  252. def connect(self, token = None):
  253. if token is None:
  254. if self.observer_only:
  255. token = "observer"
  256. else:
  257. token = self.connection.addClient()
  258. if token is None:
  259. return None
  260. self.transport.set_connection_token(token)
  261. return self
  262. def setupEventQueue(self):
  263. self.events = uievent.BBUIEventQueue(self.connection, self.clientinfo)
  264. for event in bb.event.ui_queue:
  265. self.events.queue_event(event)
  266. _, error = self.connection.runCommand(["setFeatures", self.featureset])
  267. if error:
  268. # disconnect the client, we can't make the setFeature work
  269. self.connection.removeClient()
  270. # no need to log it here, the error shall be sent to the client
  271. raise BaseException(error)
  272. def removeClient(self):
  273. if not self.observer_only:
  274. self.connection.removeClient()
  275. def terminate(self):
  276. # Don't wait for server indefinitely
  277. import socket
  278. socket.setdefaulttimeout(2)
  279. try:
  280. self.events.system_quit()
  281. except:
  282. pass
  283. try:
  284. self.connection.removeClient()
  285. except:
  286. pass
  287. class BitBakeServer(BitBakeBaseServer):
  288. def initServer(self, interface = ("localhost", 0), single_use = False):
  289. self.interface = interface
  290. self.serverImpl = XMLRPCServer(interface, single_use)
  291. def detach(self):
  292. daemonize.createDaemon(self.serverImpl.serve_forever, "bitbake-cookerdaemon.log")
  293. del self.cooker
  294. def establishConnection(self, featureset):
  295. self.connection = BitBakeXMLRPCServerConnection(self.serverImpl, self.interface, False, featureset)
  296. return self.connection.connect()
  297. def set_connection_token(self, token):
  298. self.connection.transport.set_connection_token(token)
  299. class BitBakeXMLRPCClient(BitBakeBaseServer):
  300. def __init__(self, observer_only = False, token = None):
  301. self.token = token
  302. self.observer_only = observer_only
  303. # if we need extra caches, just tell the server to load them all
  304. pass
  305. def saveConnectionDetails(self, remote):
  306. self.remote = remote
  307. def establishConnection(self, featureset):
  308. # The format of "remote" must be "server:port"
  309. try:
  310. [host, port] = self.remote.split(":")
  311. port = int(port)
  312. except Exception as e:
  313. bb.warn("Failed to read remote definition (%s)" % str(e))
  314. raise e
  315. # We need our IP for the server connection. We get the IP
  316. # by trying to connect with the server
  317. try:
  318. s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
  319. s.connect((host, port))
  320. ip = s.getsockname()[0]
  321. s.close()
  322. except Exception as e:
  323. bb.warn("Could not create socket for %s:%s (%s)" % (host, port, str(e)))
  324. raise e
  325. try:
  326. self.serverImpl = XMLRPCProxyServer(host, port, use_builtin_types=True)
  327. self.connection = BitBakeXMLRPCServerConnection(self.serverImpl, (ip, 0), self.observer_only, featureset)
  328. return self.connection.connect(self.token)
  329. except Exception as e:
  330. bb.warn("Could not connect to server at %s:%s (%s)" % (host, port, str(e)))
  331. raise e
  332. def endSession(self):
  333. self.connection.removeClient()