tinfoil.py 17 KB

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