tinfoil.py 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434
  1. # tinfoil: a simple wrapper around cooker for bitbake-based command-line utilities
  2. #
  3. # Copyright (C) 2012-2016 Intel Corporation
  4. # Copyright (C) 2011 Mentor Graphics Corporation
  5. #
  6. # This program is free software; you can redistribute it and/or modify
  7. # it under the terms of the GNU General Public License version 2 as
  8. # published by the Free Software Foundation.
  9. #
  10. # This program is distributed in the hope that it will be useful,
  11. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  13. # GNU General Public License for more details.
  14. #
  15. # You should have received a copy of the GNU General Public License along
  16. # with this program; if not, write to the Free Software Foundation, Inc.,
  17. # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
  18. import logging
  19. import os
  20. import sys
  21. import atexit
  22. import re
  23. from collections import OrderedDict, defaultdict
  24. import bb.cache
  25. import bb.cooker
  26. import bb.providers
  27. import bb.taskdata
  28. import bb.utils
  29. import bb.command
  30. import bb.remotedata
  31. from bb.cookerdata import CookerConfiguration, ConfigParameters
  32. from bb.main import setup_bitbake, BitBakeConfigParameters, BBMainException
  33. import bb.fetch2
  34. # We need this in order to shut down the connection to the bitbake server,
  35. # otherwise the process will never properly exit
  36. _server_connections = []
  37. def _terminate_connections():
  38. for connection in _server_connections:
  39. connection.terminate()
  40. atexit.register(_terminate_connections)
  41. class TinfoilUIException(Exception):
  42. """Exception raised when the UI returns non-zero from its main function"""
  43. def __init__(self, returncode):
  44. self.returncode = returncode
  45. def __repr__(self):
  46. return 'UI module main returned %d' % self.returncode
  47. class TinfoilCommandFailed(Exception):
  48. """Exception raised when run_command fails"""
  49. class TinfoilDataStoreConnector:
  50. def __init__(self, tinfoil, dsindex):
  51. self.tinfoil = tinfoil
  52. self.dsindex = dsindex
  53. def getVar(self, name):
  54. value = self.tinfoil.run_command('dataStoreConnectorFindVar', self.dsindex, name)
  55. if isinstance(value, dict):
  56. if '_connector_origtype' in value:
  57. value['_content'] = self.tinfoil._reconvert_type(value['_content'], value['_connector_origtype'])
  58. del value['_connector_origtype']
  59. return value
  60. def getKeys(self):
  61. return set(self.tinfoil.run_command('dataStoreConnectorGetKeys', self.dsindex))
  62. def getVarHistory(self, name):
  63. return self.tinfoil.run_command('dataStoreConnectorGetVarHistory', self.dsindex, name)
  64. def expandPythonRef(self, varname, expr, d):
  65. ds = bb.remotedata.RemoteDatastores.transmit_datastore(d)
  66. ret = self.tinfoil.run_command('dataStoreConnectorExpandPythonRef', ds, varname, expr)
  67. return ret
  68. def setVar(self, varname, value):
  69. if self.dsindex is None:
  70. self.tinfoil.run_command('setVariable', varname, value)
  71. else:
  72. # Not currently implemented - indicate that setting should
  73. # be redirected to local side
  74. return True
  75. class TinfoilCookerAdapter:
  76. """
  77. Provide an adapter for existing code that expects to access a cooker object via Tinfoil,
  78. since now Tinfoil is on the client side it no longer has direct access.
  79. """
  80. class TinfoilCookerCollectionAdapter:
  81. """ cooker.collection adapter """
  82. def __init__(self, tinfoil):
  83. self.tinfoil = tinfoil
  84. def get_file_appends(self, fn):
  85. return self.tinfoil.get_file_appends(fn)
  86. def __getattr__(self, name):
  87. if name == 'overlayed':
  88. return self.tinfoil.get_overlayed_recipes()
  89. elif name == 'bbappends':
  90. return self.tinfoil.run_command('getAllAppends')
  91. else:
  92. raise AttributeError("%s instance has no attribute '%s'" % (self.__class__.__name__, name))
  93. class TinfoilRecipeCacheAdapter:
  94. """ cooker.recipecache adapter """
  95. def __init__(self, tinfoil):
  96. self.tinfoil = tinfoil
  97. self._cache = {}
  98. def get_pkg_pn_fn(self):
  99. pkg_pn = defaultdict(list, self.tinfoil.run_command('getRecipes') or [])
  100. pkg_fn = {}
  101. for pn, fnlist in pkg_pn.items():
  102. for fn in fnlist:
  103. pkg_fn[fn] = pn
  104. self._cache['pkg_pn'] = pkg_pn
  105. self._cache['pkg_fn'] = pkg_fn
  106. def __getattr__(self, name):
  107. # Grab these only when they are requested since they aren't always used
  108. if name in self._cache:
  109. return self._cache[name]
  110. elif name == 'pkg_pn':
  111. self.get_pkg_pn_fn()
  112. return self._cache[name]
  113. elif name == 'pkg_fn':
  114. self.get_pkg_pn_fn()
  115. return self._cache[name]
  116. elif name == 'deps':
  117. attrvalue = defaultdict(list, self.tinfoil.run_command('getRecipeDepends') or [])
  118. elif name == 'rundeps':
  119. attrvalue = defaultdict(lambda: defaultdict(list), self.tinfoil.run_command('getRuntimeDepends') or [])
  120. elif name == 'runrecs':
  121. attrvalue = defaultdict(lambda: defaultdict(list), self.tinfoil.run_command('getRuntimeRecommends') or [])
  122. elif name == 'pkg_pepvpr':
  123. attrvalue = self.tinfoil.run_command('getRecipeVersions') or {}
  124. elif name == 'inherits':
  125. attrvalue = self.tinfoil.run_command('getRecipeInherits') or {}
  126. elif name == 'bbfile_priority':
  127. attrvalue = self.tinfoil.run_command('getBbFilePriority') or {}
  128. elif name == 'pkg_dp':
  129. attrvalue = self.tinfoil.run_command('getDefaultPreference') or {}
  130. else:
  131. raise AttributeError("%s instance has no attribute '%s'" % (self.__class__.__name__, name))
  132. self._cache[name] = attrvalue
  133. return attrvalue
  134. def __init__(self, tinfoil):
  135. self.tinfoil = tinfoil
  136. self.collection = self.TinfoilCookerCollectionAdapter(tinfoil)
  137. self.recipecaches = {}
  138. # FIXME all machines
  139. self.recipecaches[''] = self.TinfoilRecipeCacheAdapter(tinfoil)
  140. self._cache = {}
  141. def __getattr__(self, name):
  142. # Grab these only when they are requested since they aren't always used
  143. if name in self._cache:
  144. return self._cache[name]
  145. elif name == 'skiplist':
  146. attrvalue = self.tinfoil.get_skipped_recipes()
  147. elif name == 'bbfile_config_priorities':
  148. ret = self.tinfoil.run_command('getLayerPriorities')
  149. bbfile_config_priorities = []
  150. for collection, pattern, regex, pri in ret:
  151. bbfile_config_priorities.append((collection, pattern, re.compile(regex), pri))
  152. attrvalue = bbfile_config_priorities
  153. else:
  154. raise AttributeError("%s instance has no attribute '%s'" % (self.__class__.__name__, name))
  155. self._cache[name] = attrvalue
  156. return attrvalue
  157. def findBestProvider(self, pn):
  158. return self.tinfoil.find_best_provider(pn)
  159. class Tinfoil:
  160. def __init__(self, output=sys.stdout, tracking=False):
  161. self.logger = logging.getLogger('BitBake')
  162. self.config_data = None
  163. self.cooker = None
  164. self.tracking = tracking
  165. self.ui_module = None
  166. self.server_connection = None
  167. def __enter__(self):
  168. return self
  169. def __exit__(self, type, value, traceback):
  170. self.shutdown()
  171. def prepare(self, config_only=False, config_params=None, quiet=0):
  172. if self.tracking:
  173. extrafeatures = [bb.cooker.CookerFeatures.BASEDATASTORE_TRACKING]
  174. else:
  175. extrafeatures = []
  176. if not config_params:
  177. config_params = TinfoilConfigParameters(config_only=config_only, quiet=quiet)
  178. cookerconfig = CookerConfiguration()
  179. cookerconfig.setConfigParameters(config_params)
  180. server, self.server_connection, ui_module = setup_bitbake(config_params,
  181. cookerconfig,
  182. extrafeatures)
  183. self.ui_module = ui_module
  184. if self.server_connection:
  185. _server_connections.append(self.server_connection)
  186. if config_only:
  187. config_params.updateToServer(self.server_connection.connection, os.environ.copy())
  188. self.run_command('parseConfiguration')
  189. else:
  190. self.run_actions(config_params)
  191. self.config_data = bb.data.init()
  192. connector = TinfoilDataStoreConnector(self, None)
  193. self.config_data.setVar('_remote_data', connector)
  194. self.cooker = TinfoilCookerAdapter(self)
  195. self.cooker_data = self.cooker.recipecaches['']
  196. else:
  197. raise Exception('Failed to start bitbake server')
  198. def run_actions(self, config_params):
  199. """
  200. Run the actions specified in config_params through the UI.
  201. """
  202. ret = self.ui_module.main(self.server_connection.connection, self.server_connection.events, config_params)
  203. if ret:
  204. raise TinfoilUIException(ret)
  205. def parseRecipes(self):
  206. """
  207. Force a parse of all recipes. Normally you should specify
  208. config_only=False when calling prepare() instead of using this
  209. function; this function is designed for situations where you need
  210. to initialise Tinfoil and use it with config_only=True first and
  211. then conditionally call this function to parse recipes later.
  212. """
  213. config_params = TinfoilConfigParameters(config_only=False)
  214. self.run_actions(config_params)
  215. def run_command(self, command, *params):
  216. """
  217. Run a command on the server (as implemented in bb.command).
  218. Note that there are two types of command - synchronous and
  219. asynchronous; in order to receive the results of asynchronous
  220. commands you will need to set an appropriate event mask
  221. using set_event_mask() and listen for the result using
  222. wait_event() - with the correct event mask you'll at least get
  223. bb.command.CommandCompleted and possibly other events before
  224. that depending on the command.
  225. """
  226. if not self.server_connection:
  227. raise Exception('Not connected to server (did you call .prepare()?)')
  228. commandline = [command]
  229. if params:
  230. commandline.extend(params)
  231. result = self.server_connection.connection.runCommand(commandline)
  232. if result[1]:
  233. raise TinfoilCommandFailed(result[1])
  234. return result[0]
  235. def set_event_mask(self, eventlist):
  236. """Set the event mask which will be applied within wait_event()"""
  237. if not self.server_connection:
  238. raise Exception('Not connected to server (did you call .prepare()?)')
  239. llevel, debug_domains = bb.msg.constructLogOptions()
  240. ret = self.run_command('setEventMask', self.server_connection.connection.getEventHandle(), llevel, debug_domains, eventlist)
  241. if not ret:
  242. raise Exception('setEventMask failed')
  243. def wait_event(self, timeout=0):
  244. """
  245. Wait for an event from the server for the specified time.
  246. A timeout of 0 means don't wait if there are no events in the queue.
  247. Returns the next event in the queue or None if the timeout was
  248. reached. Note that in order to recieve any events you will
  249. first need to set the internal event mask using set_event_mask()
  250. (otherwise whatever event mask the UI set up will be in effect).
  251. """
  252. if not self.server_connection:
  253. raise Exception('Not connected to server (did you call .prepare()?)')
  254. return self.server_connection.events.waitEvent(timeout)
  255. def get_overlayed_recipes(self):
  256. return defaultdict(list, self.run_command('getOverlayedRecipes'))
  257. def get_skipped_recipes(self):
  258. return OrderedDict(self.run_command('getSkippedRecipes'))
  259. def get_all_providers(self):
  260. return defaultdict(list, self.run_command('allProviders'))
  261. def find_providers(self):
  262. return self.run_command('findProviders')
  263. def find_best_provider(self, pn):
  264. return self.run_command('findBestProvider', pn)
  265. def get_runtime_providers(self, rdep):
  266. return self.run_command('getRuntimeProviders', rdep)
  267. def get_recipe_file(self, pn):
  268. """
  269. Get the file name for the specified recipe/target. Raises
  270. bb.providers.NoProvider if there is no match or the recipe was
  271. skipped.
  272. """
  273. best = self.find_best_provider(pn)
  274. if not best:
  275. skiplist = self.get_skipped_recipes()
  276. taskdata = bb.taskdata.TaskData(None, skiplist=skiplist)
  277. skipreasons = taskdata.get_reasons(pn)
  278. if skipreasons:
  279. raise bb.providers.NoProvider(skipreasons)
  280. else:
  281. raise bb.providers.NoProvider('Unable to find any recipe file matching %s' % pn)
  282. return best[3]
  283. def get_file_appends(self, fn):
  284. return self.run_command('getFileAppends', fn)
  285. def parse_recipe(self, pn):
  286. """
  287. Parse the specified recipe and return a datastore object
  288. representing the environment for the recipe.
  289. """
  290. fn = self.get_recipe_file(pn)
  291. return self.parse_recipe_file(fn)
  292. def parse_recipe_file(self, fn, appends=True, appendlist=None, config_data=None):
  293. """
  294. Parse the specified recipe file (with or without bbappends)
  295. and return a datastore object representing the environment
  296. for the recipe.
  297. Parameters:
  298. fn: recipe file to parse - can be a file path or virtual
  299. specification
  300. appends: True to apply bbappends, False otherwise
  301. appendlist: optional list of bbappend files to apply, if you
  302. want to filter them
  303. config_data: custom config datastore to use. NOTE: if you
  304. specify config_data then you cannot use a virtual
  305. specification for fn.
  306. """
  307. if appends and appendlist == []:
  308. appends = False
  309. if config_data:
  310. dctr = bb.remotedata.RemoteDatastores.transmit_datastore(config_data)
  311. dscon = self.run_command('parseRecipeFile', fn, appends, appendlist, dctr)
  312. else:
  313. dscon = self.run_command('parseRecipeFile', fn, appends, appendlist)
  314. if dscon:
  315. return self._reconvert_type(dscon, 'DataStoreConnectionHandle')
  316. else:
  317. return None
  318. def build_file(self, buildfile, task):
  319. """
  320. Runs the specified task for just a single recipe (i.e. no dependencies).
  321. This is equivalent to bitbake -b.
  322. """
  323. return self.run_command('buildFile', buildfile, task)
  324. def shutdown(self):
  325. if self.server_connection:
  326. self.run_command('clientComplete')
  327. _server_connections.remove(self.server_connection)
  328. bb.event.ui_queue = []
  329. self.server_connection.terminate()
  330. self.server_connection = None
  331. def _reconvert_type(self, obj, origtypename):
  332. """
  333. Convert an object back to the right type, in the case
  334. that marshalling has changed it (especially with xmlrpc)
  335. """
  336. supported_types = {
  337. 'set': set,
  338. 'DataStoreConnectionHandle': bb.command.DataStoreConnectionHandle,
  339. }
  340. origtype = supported_types.get(origtypename, None)
  341. if origtype is None:
  342. raise Exception('Unsupported type "%s"' % origtypename)
  343. if type(obj) == origtype:
  344. newobj = obj
  345. elif isinstance(obj, dict):
  346. # New style class
  347. newobj = origtype()
  348. for k,v in obj.items():
  349. setattr(newobj, k, v)
  350. else:
  351. # Assume we can coerce the type
  352. newobj = origtype(obj)
  353. if isinstance(newobj, bb.command.DataStoreConnectionHandle):
  354. connector = TinfoilDataStoreConnector(self, newobj.dsindex)
  355. newobj = bb.data.init()
  356. newobj.setVar('_remote_data', connector)
  357. return newobj
  358. class TinfoilConfigParameters(BitBakeConfigParameters):
  359. def __init__(self, config_only, **options):
  360. self.initial_options = options
  361. # Apply some sane defaults
  362. if not 'parse_only' in options:
  363. self.initial_options['parse_only'] = not config_only
  364. #if not 'status_only' in options:
  365. # self.initial_options['status_only'] = config_only
  366. if not 'ui' in options:
  367. self.initial_options['ui'] = 'knotty'
  368. if not 'argv' in options:
  369. self.initial_options['argv'] = []
  370. super(TinfoilConfigParameters, self).__init__()
  371. def parseCommandLine(self, argv=None):
  372. # We don't want any parameters parsed from the command line
  373. opts = super(TinfoilConfigParameters, self).parseCommandLine([])
  374. for key, val in self.initial_options.items():
  375. setattr(opts[0], key, val)
  376. return opts