tinfoil.py 20 KB

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