tinfoil.py 38 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890
  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. # Copyright (C) 2006-2012 Richard Purdie
  6. #
  7. # SPDX-License-Identifier: GPL-2.0-only
  8. #
  9. import logging
  10. import os
  11. import sys
  12. import atexit
  13. import re
  14. from collections import OrderedDict, defaultdict
  15. import bb.cache
  16. import bb.cooker
  17. import bb.providers
  18. import bb.taskdata
  19. import bb.utils
  20. import bb.command
  21. import bb.remotedata
  22. from bb.cookerdata import CookerConfiguration, ConfigParameters
  23. from bb.main import setup_bitbake, BitBakeConfigParameters, BBMainException
  24. import bb.fetch2
  25. # We need this in order to shut down the connection to the bitbake server,
  26. # otherwise the process will never properly exit
  27. _server_connections = []
  28. def _terminate_connections():
  29. for connection in _server_connections:
  30. connection.terminate()
  31. atexit.register(_terminate_connections)
  32. class TinfoilUIException(Exception):
  33. """Exception raised when the UI returns non-zero from its main function"""
  34. def __init__(self, returncode):
  35. self.returncode = returncode
  36. def __repr__(self):
  37. return 'UI module main returned %d' % self.returncode
  38. class TinfoilCommandFailed(Exception):
  39. """Exception raised when run_command fails"""
  40. class TinfoilDataStoreConnector:
  41. """Connector object used to enable access to datastore objects via tinfoil"""
  42. def __init__(self, tinfoil, dsindex):
  43. self.tinfoil = tinfoil
  44. self.dsindex = dsindex
  45. def getVar(self, name):
  46. value = self.tinfoil.run_command('dataStoreConnectorFindVar', self.dsindex, name)
  47. overrides = None
  48. if isinstance(value, dict):
  49. if '_connector_origtype' in value:
  50. value['_content'] = self.tinfoil._reconvert_type(value['_content'], value['_connector_origtype'])
  51. del value['_connector_origtype']
  52. if '_connector_overrides' in value:
  53. overrides = value['_connector_overrides']
  54. del value['_connector_overrides']
  55. return value, overrides
  56. def getKeys(self):
  57. return set(self.tinfoil.run_command('dataStoreConnectorGetKeys', self.dsindex))
  58. def getVarHistory(self, name):
  59. return self.tinfoil.run_command('dataStoreConnectorGetVarHistory', self.dsindex, name)
  60. def expandPythonRef(self, varname, expr, d):
  61. ds = bb.remotedata.RemoteDatastores.transmit_datastore(d)
  62. ret = self.tinfoil.run_command('dataStoreConnectorExpandPythonRef', ds, varname, expr)
  63. return ret
  64. def setVar(self, varname, value):
  65. if self.dsindex is None:
  66. self.tinfoil.run_command('setVariable', varname, value)
  67. else:
  68. # Not currently implemented - indicate that setting should
  69. # be redirected to local side
  70. return True
  71. def setVarFlag(self, varname, flagname, value):
  72. if self.dsindex is None:
  73. self.tinfoil.run_command('dataStoreConnectorSetVarFlag', self.dsindex, varname, flagname, value)
  74. else:
  75. # Not currently implemented - indicate that setting should
  76. # be redirected to local side
  77. return True
  78. def delVar(self, varname):
  79. if self.dsindex is None:
  80. self.tinfoil.run_command('dataStoreConnectorDelVar', self.dsindex, varname)
  81. else:
  82. # Not currently implemented - indicate that setting should
  83. # be redirected to local side
  84. return True
  85. def delVarFlag(self, varname, flagname):
  86. if self.dsindex is None:
  87. self.tinfoil.run_command('dataStoreConnectorDelVar', self.dsindex, varname, flagname)
  88. else:
  89. # Not currently implemented - indicate that setting should
  90. # be redirected to local side
  91. return True
  92. def renameVar(self, name, newname):
  93. if self.dsindex is None:
  94. self.tinfoil.run_command('dataStoreConnectorRenameVar', self.dsindex, name, newname)
  95. else:
  96. # Not currently implemented - indicate that setting should
  97. # be redirected to local side
  98. return True
  99. class TinfoilCookerAdapter:
  100. """
  101. Provide an adapter for existing code that expects to access a cooker object via Tinfoil,
  102. since now Tinfoil is on the client side it no longer has direct access.
  103. """
  104. class TinfoilCookerCollectionAdapter:
  105. """ cooker.collection adapter """
  106. def __init__(self, tinfoil):
  107. self.tinfoil = tinfoil
  108. def get_file_appends(self, fn):
  109. return self.tinfoil.get_file_appends(fn)
  110. def __getattr__(self, name):
  111. if name == 'overlayed':
  112. return self.tinfoil.get_overlayed_recipes()
  113. elif name == 'bbappends':
  114. return self.tinfoil.run_command('getAllAppends')
  115. else:
  116. raise AttributeError("%s instance has no attribute '%s'" % (self.__class__.__name__, name))
  117. class TinfoilRecipeCacheAdapter:
  118. """ cooker.recipecache adapter """
  119. def __init__(self, tinfoil):
  120. self.tinfoil = tinfoil
  121. self._cache = {}
  122. def get_pkg_pn_fn(self):
  123. pkg_pn = defaultdict(list, self.tinfoil.run_command('getRecipes') or [])
  124. pkg_fn = {}
  125. for pn, fnlist in pkg_pn.items():
  126. for fn in fnlist:
  127. pkg_fn[fn] = pn
  128. self._cache['pkg_pn'] = pkg_pn
  129. self._cache['pkg_fn'] = pkg_fn
  130. def __getattr__(self, name):
  131. # Grab these only when they are requested since they aren't always used
  132. if name in self._cache:
  133. return self._cache[name]
  134. elif name == 'pkg_pn':
  135. self.get_pkg_pn_fn()
  136. return self._cache[name]
  137. elif name == 'pkg_fn':
  138. self.get_pkg_pn_fn()
  139. return self._cache[name]
  140. elif name == 'deps':
  141. attrvalue = defaultdict(list, self.tinfoil.run_command('getRecipeDepends') or [])
  142. elif name == 'rundeps':
  143. attrvalue = defaultdict(lambda: defaultdict(list), self.tinfoil.run_command('getRuntimeDepends') or [])
  144. elif name == 'runrecs':
  145. attrvalue = defaultdict(lambda: defaultdict(list), self.tinfoil.run_command('getRuntimeRecommends') or [])
  146. elif name == 'pkg_pepvpr':
  147. attrvalue = self.tinfoil.run_command('getRecipeVersions') or {}
  148. elif name == 'inherits':
  149. attrvalue = self.tinfoil.run_command('getRecipeInherits') or {}
  150. elif name == 'bbfile_priority':
  151. attrvalue = self.tinfoil.run_command('getBbFilePriority') or {}
  152. elif name == 'pkg_dp':
  153. attrvalue = self.tinfoil.run_command('getDefaultPreference') or {}
  154. elif name == 'fn_provides':
  155. attrvalue = self.tinfoil.run_command('getRecipeProvides') or {}
  156. elif name == 'packages':
  157. attrvalue = self.tinfoil.run_command('getRecipePackages') or {}
  158. elif name == 'packages_dynamic':
  159. attrvalue = self.tinfoil.run_command('getRecipePackagesDynamic') or {}
  160. elif name == 'rproviders':
  161. attrvalue = self.tinfoil.run_command('getRProviders') 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 TinfoilRecipeInfo:
  192. """
  193. Provides a convenient representation of the cached information for a single recipe.
  194. Some attributes are set on construction, others are read on-demand (which internally
  195. may result in a remote procedure call to the bitbake server the first time).
  196. Note that only information which is cached is available through this object - if
  197. you need other variable values you will need to parse the recipe using
  198. Tinfoil.parse_recipe().
  199. """
  200. def __init__(self, recipecache, d, pn, fn, fns):
  201. self._recipecache = recipecache
  202. self._d = d
  203. self.pn = pn
  204. self.fn = fn
  205. self.fns = fns
  206. self.inherit_files = recipecache.inherits[fn]
  207. self.depends = recipecache.deps[fn]
  208. (self.pe, self.pv, self.pr) = recipecache.pkg_pepvpr[fn]
  209. self._cached_packages = None
  210. self._cached_rprovides = None
  211. self._cached_packages_dynamic = None
  212. def __getattr__(self, name):
  213. if name == 'alternates':
  214. return [x for x in self.fns if x != self.fn]
  215. elif name == 'rdepends':
  216. return self._recipecache.rundeps[self.fn]
  217. elif name == 'rrecommends':
  218. return self._recipecache.runrecs[self.fn]
  219. elif name == 'provides':
  220. return self._recipecache.fn_provides[self.fn]
  221. elif name == 'packages':
  222. if self._cached_packages is None:
  223. self._cached_packages = []
  224. for pkg, fns in self._recipecache.packages.items():
  225. if self.fn in fns:
  226. self._cached_packages.append(pkg)
  227. return self._cached_packages
  228. elif name == 'packages_dynamic':
  229. if self._cached_packages_dynamic is None:
  230. self._cached_packages_dynamic = []
  231. for pkg, fns in self._recipecache.packages_dynamic.items():
  232. if self.fn in fns:
  233. self._cached_packages_dynamic.append(pkg)
  234. return self._cached_packages_dynamic
  235. elif name == 'rprovides':
  236. if self._cached_rprovides is None:
  237. self._cached_rprovides = []
  238. for pkg, fns in self._recipecache.rproviders.items():
  239. if self.fn in fns:
  240. self._cached_rprovides.append(pkg)
  241. return self._cached_rprovides
  242. else:
  243. raise AttributeError("%s instance has no attribute '%s'" % (self.__class__.__name__, name))
  244. def inherits(self, only_recipe=False):
  245. """
  246. Get the inherited classes for a recipe. Returns the class names only.
  247. Parameters:
  248. only_recipe: True to return only the classes inherited by the recipe
  249. itself, False to return all classes inherited within
  250. the context for the recipe (which includes globally
  251. inherited classes).
  252. """
  253. if only_recipe:
  254. global_inherit = [x for x in (self._d.getVar('BBINCLUDED') or '').split() if x.endswith('.bbclass')]
  255. else:
  256. global_inherit = []
  257. for clsfile in self.inherit_files:
  258. if only_recipe and clsfile in global_inherit:
  259. continue
  260. clsname = os.path.splitext(os.path.basename(clsfile))[0]
  261. yield clsname
  262. def __str__(self):
  263. return '%s' % self.pn
  264. class Tinfoil:
  265. """
  266. Tinfoil - an API for scripts and utilities to query
  267. BitBake internals and perform build operations.
  268. """
  269. def __init__(self, output=sys.stdout, tracking=False, setup_logging=True):
  270. """
  271. Create a new tinfoil object.
  272. Parameters:
  273. output: specifies where console output should be sent. Defaults
  274. to sys.stdout.
  275. tracking: True to enable variable history tracking, False to
  276. disable it (default). Enabling this has a minor
  277. performance impact so typically it isn't enabled
  278. unless you need to query variable history.
  279. setup_logging: True to setup a logger so that things like
  280. bb.warn() will work immediately and timeout warnings
  281. are visible; False to let BitBake do this itself.
  282. """
  283. self.logger = logging.getLogger('BitBake')
  284. self.config_data = None
  285. self.cooker = None
  286. self.tracking = tracking
  287. self.ui_module = None
  288. self.server_connection = None
  289. self.recipes_parsed = False
  290. self.quiet = 0
  291. self.oldhandlers = self.logger.handlers[:]
  292. if setup_logging:
  293. # This is the *client-side* logger, nothing to do with
  294. # logging messages from the server
  295. bb.msg.logger_create('BitBake', output)
  296. self.localhandlers = []
  297. for handler in self.logger.handlers:
  298. if handler not in self.oldhandlers:
  299. self.localhandlers.append(handler)
  300. def __enter__(self):
  301. return self
  302. def __exit__(self, type, value, traceback):
  303. self.shutdown()
  304. def prepare(self, config_only=False, config_params=None, quiet=0, extra_features=None):
  305. """
  306. Prepares the underlying BitBake system to be used via tinfoil.
  307. This function must be called prior to calling any of the other
  308. functions in the API.
  309. NOTE: if you call prepare() you must absolutely call shutdown()
  310. before your code terminates. You can use a "with" block to ensure
  311. this happens e.g.
  312. with bb.tinfoil.Tinfoil() as tinfoil:
  313. tinfoil.prepare()
  314. ...
  315. Parameters:
  316. config_only: True to read only the configuration and not load
  317. the cache / parse recipes. This is useful if you just
  318. want to query the value of a variable at the global
  319. level or you want to do anything else that doesn't
  320. involve knowing anything about the recipes in the
  321. current configuration. False loads the cache / parses
  322. recipes.
  323. config_params: optionally specify your own configuration
  324. parameters. If not specified an instance of
  325. TinfoilConfigParameters will be created internally.
  326. quiet: quiet level controlling console output - equivalent
  327. to bitbake's -q/--quiet option. Default of 0 gives
  328. the same output level as normal bitbake execution.
  329. extra_features: extra features to be added to the feature
  330. set requested from the server. See
  331. CookerFeatures._feature_list for possible
  332. features.
  333. """
  334. self.quiet = quiet
  335. if self.tracking:
  336. extrafeatures = [bb.cooker.CookerFeatures.BASEDATASTORE_TRACKING]
  337. else:
  338. extrafeatures = []
  339. if extra_features:
  340. extrafeatures += extra_features
  341. if not config_params:
  342. config_params = TinfoilConfigParameters(config_only=config_only, quiet=quiet)
  343. cookerconfig = CookerConfiguration()
  344. cookerconfig.setConfigParameters(config_params)
  345. if not config_only:
  346. # Disable local loggers because the UI module is going to set up its own
  347. for handler in self.localhandlers:
  348. self.logger.handlers.remove(handler)
  349. self.localhandlers = []
  350. self.server_connection, ui_module = setup_bitbake(config_params,
  351. cookerconfig,
  352. extrafeatures)
  353. self.ui_module = ui_module
  354. # Ensure the path to bitbake's bin directory is in PATH so that things like
  355. # bitbake-worker can be run (usually this is the case, but it doesn't have to be)
  356. path = os.getenv('PATH').split(':')
  357. bitbakebinpath = os.path.abspath(os.path.join(os.path.dirname(os.path.abspath(__file__)), '..', '..', 'bin'))
  358. for entry in path:
  359. if entry.endswith(os.sep):
  360. entry = entry[:-1]
  361. if os.path.abspath(entry) == bitbakebinpath:
  362. break
  363. else:
  364. path.insert(0, bitbakebinpath)
  365. os.environ['PATH'] = ':'.join(path)
  366. if self.server_connection:
  367. _server_connections.append(self.server_connection)
  368. if config_only:
  369. config_params.updateToServer(self.server_connection.connection, os.environ.copy())
  370. self.run_command('parseConfiguration')
  371. else:
  372. self.run_actions(config_params)
  373. self.recipes_parsed = True
  374. self.config_data = bb.data.init()
  375. connector = TinfoilDataStoreConnector(self, None)
  376. self.config_data.setVar('_remote_data', connector)
  377. self.cooker = TinfoilCookerAdapter(self)
  378. self.cooker_data = self.cooker.recipecaches['']
  379. else:
  380. raise Exception('Failed to start bitbake server')
  381. def run_actions(self, config_params):
  382. """
  383. Run the actions specified in config_params through the UI.
  384. """
  385. ret = self.ui_module.main(self.server_connection.connection, self.server_connection.events, config_params)
  386. if ret:
  387. raise TinfoilUIException(ret)
  388. def parseRecipes(self):
  389. """
  390. Legacy function - use parse_recipes() instead.
  391. """
  392. self.parse_recipes()
  393. def parse_recipes(self):
  394. """
  395. Load information on all recipes. Normally you should specify
  396. config_only=False when calling prepare() instead of using this
  397. function; this function is designed for situations where you need
  398. to initialise Tinfoil and use it with config_only=True first and
  399. then conditionally call this function to parse recipes later.
  400. """
  401. config_params = TinfoilConfigParameters(config_only=False)
  402. self.run_actions(config_params)
  403. self.recipes_parsed = True
  404. def run_command(self, command, *params):
  405. """
  406. Run a command on the server (as implemented in bb.command).
  407. Note that there are two types of command - synchronous and
  408. asynchronous; in order to receive the results of asynchronous
  409. commands you will need to set an appropriate event mask
  410. using set_event_mask() and listen for the result using
  411. wait_event() - with the correct event mask you'll at least get
  412. bb.command.CommandCompleted and possibly other events before
  413. that depending on the command.
  414. """
  415. if not self.server_connection:
  416. raise Exception('Not connected to server (did you call .prepare()?)')
  417. commandline = [command]
  418. if params:
  419. commandline.extend(params)
  420. result = self.server_connection.connection.runCommand(commandline)
  421. if result[1]:
  422. raise TinfoilCommandFailed(result[1])
  423. return result[0]
  424. def set_event_mask(self, eventlist):
  425. """Set the event mask which will be applied within wait_event()"""
  426. if not self.server_connection:
  427. raise Exception('Not connected to server (did you call .prepare()?)')
  428. llevel, debug_domains = bb.msg.constructLogOptions()
  429. ret = self.run_command('setEventMask', self.server_connection.connection.getEventHandle(), llevel, debug_domains, eventlist)
  430. if not ret:
  431. raise Exception('setEventMask failed')
  432. def wait_event(self, timeout=0):
  433. """
  434. Wait for an event from the server for the specified time.
  435. A timeout of 0 means don't wait if there are no events in the queue.
  436. Returns the next event in the queue or None if the timeout was
  437. reached. Note that in order to recieve any events you will
  438. first need to set the internal event mask using set_event_mask()
  439. (otherwise whatever event mask the UI set up will be in effect).
  440. """
  441. if not self.server_connection:
  442. raise Exception('Not connected to server (did you call .prepare()?)')
  443. return self.server_connection.events.waitEvent(timeout)
  444. def get_overlayed_recipes(self):
  445. """
  446. Find recipes which are overlayed (i.e. where recipes exist in multiple layers)
  447. """
  448. return defaultdict(list, self.run_command('getOverlayedRecipes'))
  449. def get_skipped_recipes(self):
  450. """
  451. Find recipes which were skipped (i.e. SkipRecipe was raised
  452. during parsing).
  453. """
  454. return OrderedDict(self.run_command('getSkippedRecipes'))
  455. def get_all_providers(self):
  456. return defaultdict(list, self.run_command('allProviders'))
  457. def find_providers(self):
  458. return self.run_command('findProviders')
  459. def find_best_provider(self, pn):
  460. return self.run_command('findBestProvider', pn)
  461. def get_runtime_providers(self, rdep):
  462. return self.run_command('getRuntimeProviders', rdep)
  463. def get_recipe_file(self, pn):
  464. """
  465. Get the file name for the specified recipe/target. Raises
  466. bb.providers.NoProvider if there is no match or the recipe was
  467. skipped.
  468. """
  469. best = self.find_best_provider(pn)
  470. if not best or (len(best) > 3 and not best[3]):
  471. skiplist = self.get_skipped_recipes()
  472. taskdata = bb.taskdata.TaskData(None, skiplist=skiplist)
  473. skipreasons = taskdata.get_reasons(pn)
  474. if skipreasons:
  475. raise bb.providers.NoProvider('%s is unavailable:\n %s' % (pn, ' \n'.join(skipreasons)))
  476. else:
  477. raise bb.providers.NoProvider('Unable to find any recipe file matching "%s"' % pn)
  478. return best[3]
  479. def get_file_appends(self, fn):
  480. """
  481. Find the bbappends for a recipe file
  482. """
  483. return self.run_command('getFileAppends', fn)
  484. def all_recipes(self, mc='', sort=True):
  485. """
  486. Enable iterating over all recipes in the current configuration.
  487. Returns an iterator over TinfoilRecipeInfo objects created on demand.
  488. Parameters:
  489. mc: The multiconfig, default of '' uses the main configuration.
  490. sort: True to sort recipes alphabetically (default), False otherwise
  491. """
  492. recipecache = self.cooker.recipecaches[mc]
  493. if sort:
  494. recipes = sorted(recipecache.pkg_pn.items())
  495. else:
  496. recipes = recipecache.pkg_pn.items()
  497. for pn, fns in recipes:
  498. prov = self.find_best_provider(pn)
  499. recipe = TinfoilRecipeInfo(recipecache,
  500. self.config_data,
  501. pn=pn,
  502. fn=prov[3],
  503. fns=fns)
  504. yield recipe
  505. def all_recipe_files(self, mc='', variants=True, preferred_only=False):
  506. """
  507. Enable iterating over all recipe files in the current configuration.
  508. Returns an iterator over file paths.
  509. Parameters:
  510. mc: The multiconfig, default of '' uses the main configuration.
  511. variants: True to include variants of recipes created through
  512. BBCLASSEXTEND (default) or False to exclude them
  513. preferred_only: True to include only the preferred recipe where
  514. multiple exist providing the same PN, False to list
  515. all recipes
  516. """
  517. recipecache = self.cooker.recipecaches[mc]
  518. if preferred_only:
  519. files = []
  520. for pn in recipecache.pkg_pn.keys():
  521. prov = self.find_best_provider(pn)
  522. files.append(prov[3])
  523. else:
  524. files = recipecache.pkg_fn.keys()
  525. for fn in sorted(files):
  526. if not variants and fn.startswith('virtual:'):
  527. continue
  528. yield fn
  529. def get_recipe_info(self, pn, mc=''):
  530. """
  531. Get information on a specific recipe in the current configuration by name (PN).
  532. Returns a TinfoilRecipeInfo object created on demand.
  533. Parameters:
  534. mc: The multiconfig, default of '' uses the main configuration.
  535. """
  536. recipecache = self.cooker.recipecaches[mc]
  537. prov = self.find_best_provider(pn)
  538. fn = prov[3]
  539. if fn:
  540. actual_pn = recipecache.pkg_fn[fn]
  541. recipe = TinfoilRecipeInfo(recipecache,
  542. self.config_data,
  543. pn=actual_pn,
  544. fn=fn,
  545. fns=recipecache.pkg_pn[actual_pn])
  546. return recipe
  547. else:
  548. return None
  549. def parse_recipe(self, pn):
  550. """
  551. Parse the specified recipe and return a datastore object
  552. representing the environment for the recipe.
  553. """
  554. fn = self.get_recipe_file(pn)
  555. return self.parse_recipe_file(fn)
  556. def parse_recipe_file(self, fn, appends=True, appendlist=None, config_data=None):
  557. """
  558. Parse the specified recipe file (with or without bbappends)
  559. and return a datastore object representing the environment
  560. for the recipe.
  561. Parameters:
  562. fn: recipe file to parse - can be a file path or virtual
  563. specification
  564. appends: True to apply bbappends, False otherwise
  565. appendlist: optional list of bbappend files to apply, if you
  566. want to filter them
  567. config_data: custom config datastore to use. NOTE: if you
  568. specify config_data then you cannot use a virtual
  569. specification for fn.
  570. """
  571. if self.tracking:
  572. # Enable history tracking just for the parse operation
  573. self.run_command('enableDataTracking')
  574. try:
  575. if appends and appendlist == []:
  576. appends = False
  577. if config_data:
  578. dctr = bb.remotedata.RemoteDatastores.transmit_datastore(config_data)
  579. dscon = self.run_command('parseRecipeFile', fn, appends, appendlist, dctr)
  580. else:
  581. dscon = self.run_command('parseRecipeFile', fn, appends, appendlist)
  582. if dscon:
  583. return self._reconvert_type(dscon, 'DataStoreConnectionHandle')
  584. else:
  585. return None
  586. finally:
  587. if self.tracking:
  588. self.run_command('disableDataTracking')
  589. def build_file(self, buildfile, task, internal=True):
  590. """
  591. Runs the specified task for just a single recipe (i.e. no dependencies).
  592. This is equivalent to bitbake -b, except with the default internal=True
  593. no warning about dependencies will be produced, normal info messages
  594. from the runqueue will be silenced and BuildInit, BuildStarted and
  595. BuildCompleted events will not be fired.
  596. """
  597. return self.run_command('buildFile', buildfile, task, internal)
  598. def build_targets(self, targets, task=None, handle_events=True, extra_events=None, event_callback=None):
  599. """
  600. Builds the specified targets. This is equivalent to a normal invocation
  601. of bitbake. Has built-in event handling which is enabled by default and
  602. can be extended if needed.
  603. Parameters:
  604. targets:
  605. One or more targets to build. Can be a list or a
  606. space-separated string.
  607. task:
  608. The task to run; if None then the value of BB_DEFAULT_TASK
  609. will be used. Default None.
  610. handle_events:
  611. True to handle events in a similar way to normal bitbake
  612. invocation with knotty; False to return immediately (on the
  613. assumption that the caller will handle the events instead).
  614. Default True.
  615. extra_events:
  616. An optional list of events to add to the event mask (if
  617. handle_events=True). If you add events here you also need
  618. to specify a callback function in event_callback that will
  619. handle the additional events. Default None.
  620. event_callback:
  621. An optional function taking a single parameter which
  622. will be called first upon receiving any event (if
  623. handle_events=True) so that the caller can override or
  624. extend the event handling. Default None.
  625. """
  626. if isinstance(targets, str):
  627. targets = targets.split()
  628. if not task:
  629. task = self.config_data.getVar('BB_DEFAULT_TASK')
  630. if handle_events:
  631. # A reasonable set of default events matching up with those we handle below
  632. eventmask = [
  633. 'bb.event.BuildStarted',
  634. 'bb.event.BuildCompleted',
  635. 'logging.LogRecord',
  636. 'bb.event.NoProvider',
  637. 'bb.command.CommandCompleted',
  638. 'bb.command.CommandFailed',
  639. 'bb.build.TaskStarted',
  640. 'bb.build.TaskFailed',
  641. 'bb.build.TaskSucceeded',
  642. 'bb.build.TaskFailedSilent',
  643. 'bb.build.TaskProgress',
  644. 'bb.runqueue.runQueueTaskStarted',
  645. 'bb.runqueue.sceneQueueTaskStarted',
  646. 'bb.event.ProcessStarted',
  647. 'bb.event.ProcessProgress',
  648. 'bb.event.ProcessFinished',
  649. ]
  650. if extra_events:
  651. eventmask.extend(extra_events)
  652. ret = self.set_event_mask(eventmask)
  653. includelogs = self.config_data.getVar('BBINCLUDELOGS')
  654. loglines = self.config_data.getVar('BBINCLUDELOGS_LINES')
  655. ret = self.run_command('buildTargets', targets, task)
  656. if handle_events:
  657. result = False
  658. # Borrowed from knotty, instead somewhat hackily we use the helper
  659. # as the object to store "shutdown" on
  660. helper = bb.ui.uihelper.BBUIHelper()
  661. # We set up logging optionally in the constructor so now we need to
  662. # grab the handlers to pass to TerminalFilter
  663. console = None
  664. errconsole = None
  665. for handler in self.logger.handlers:
  666. if isinstance(handler, logging.StreamHandler):
  667. if handler.stream == sys.stdout:
  668. console = handler
  669. elif handler.stream == sys.stderr:
  670. errconsole = handler
  671. format_str = "%(levelname)s: %(message)s"
  672. format = bb.msg.BBLogFormatter(format_str)
  673. helper.shutdown = 0
  674. parseprogress = None
  675. termfilter = bb.ui.knotty.TerminalFilter(helper, helper, console, errconsole, format, quiet=self.quiet)
  676. try:
  677. while True:
  678. try:
  679. event = self.wait_event(0.25)
  680. if event:
  681. if event_callback and event_callback(event):
  682. continue
  683. if helper.eventHandler(event):
  684. if isinstance(event, bb.build.TaskFailedSilent):
  685. logger.warning("Logfile for failed setscene task is %s" % event.logfile)
  686. elif isinstance(event, bb.build.TaskFailed):
  687. bb.ui.knotty.print_event_log(event, includelogs, loglines, termfilter)
  688. continue
  689. if isinstance(event, bb.event.ProcessStarted):
  690. if self.quiet > 1:
  691. continue
  692. parseprogress = bb.ui.knotty.new_progress(event.processname, event.total)
  693. parseprogress.start(False)
  694. continue
  695. if isinstance(event, bb.event.ProcessProgress):
  696. if self.quiet > 1:
  697. continue
  698. if parseprogress:
  699. parseprogress.update(event.progress)
  700. else:
  701. bb.warn("Got ProcessProgress event for someting that never started?")
  702. continue
  703. if isinstance(event, bb.event.ProcessFinished):
  704. if self.quiet > 1:
  705. continue
  706. if parseprogress:
  707. parseprogress.finish()
  708. parseprogress = None
  709. continue
  710. if isinstance(event, bb.command.CommandCompleted):
  711. result = True
  712. break
  713. if isinstance(event, bb.command.CommandFailed):
  714. self.logger.error(str(event))
  715. result = False
  716. break
  717. if isinstance(event, logging.LogRecord):
  718. if event.taskpid == 0 or event.levelno > logging.INFO:
  719. self.logger.handle(event)
  720. continue
  721. if isinstance(event, bb.event.NoProvider):
  722. self.logger.error(str(event))
  723. result = False
  724. break
  725. elif helper.shutdown > 1:
  726. break
  727. termfilter.updateFooter()
  728. except KeyboardInterrupt:
  729. termfilter.clearFooter()
  730. if helper.shutdown == 1:
  731. print("\nSecond Keyboard Interrupt, stopping...\n")
  732. ret = self.run_command("stateForceShutdown")
  733. if ret and ret[2]:
  734. self.logger.error("Unable to cleanly stop: %s" % ret[2])
  735. elif helper.shutdown == 0:
  736. print("\nKeyboard Interrupt, closing down...\n")
  737. interrupted = True
  738. ret = self.run_command("stateShutdown")
  739. if ret and ret[2]:
  740. self.logger.error("Unable to cleanly shutdown: %s" % ret[2])
  741. helper.shutdown = helper.shutdown + 1
  742. termfilter.clearFooter()
  743. finally:
  744. termfilter.finish()
  745. if helper.failed_tasks:
  746. result = False
  747. return result
  748. else:
  749. return ret
  750. def shutdown(self):
  751. """
  752. Shut down tinfoil. Disconnects from the server and gracefully
  753. releases any associated resources. You must call this function if
  754. prepare() has been called, or use a with... block when you create
  755. the tinfoil object which will ensure that it gets called.
  756. """
  757. if self.server_connection:
  758. self.run_command('clientComplete')
  759. _server_connections.remove(self.server_connection)
  760. bb.event.ui_queue = []
  761. self.server_connection.terminate()
  762. self.server_connection = None
  763. # Restore logging handlers to how it looked when we started
  764. if self.oldhandlers:
  765. for handler in self.logger.handlers:
  766. if handler not in self.oldhandlers:
  767. self.logger.handlers.remove(handler)
  768. def _reconvert_type(self, obj, origtypename):
  769. """
  770. Convert an object back to the right type, in the case
  771. that marshalling has changed it (especially with xmlrpc)
  772. """
  773. supported_types = {
  774. 'set': set,
  775. 'DataStoreConnectionHandle': bb.command.DataStoreConnectionHandle,
  776. }
  777. origtype = supported_types.get(origtypename, None)
  778. if origtype is None:
  779. raise Exception('Unsupported type "%s"' % origtypename)
  780. if type(obj) == origtype:
  781. newobj = obj
  782. elif isinstance(obj, dict):
  783. # New style class
  784. newobj = origtype()
  785. for k,v in obj.items():
  786. setattr(newobj, k, v)
  787. else:
  788. # Assume we can coerce the type
  789. newobj = origtype(obj)
  790. if isinstance(newobj, bb.command.DataStoreConnectionHandle):
  791. connector = TinfoilDataStoreConnector(self, newobj.dsindex)
  792. newobj = bb.data.init()
  793. newobj.setVar('_remote_data', connector)
  794. return newobj
  795. class TinfoilConfigParameters(BitBakeConfigParameters):
  796. def __init__(self, config_only, **options):
  797. self.initial_options = options
  798. # Apply some sane defaults
  799. if not 'parse_only' in options:
  800. self.initial_options['parse_only'] = not config_only
  801. #if not 'status_only' in options:
  802. # self.initial_options['status_only'] = config_only
  803. if not 'ui' in options:
  804. self.initial_options['ui'] = 'knotty'
  805. if not 'argv' in options:
  806. self.initial_options['argv'] = []
  807. super(TinfoilConfigParameters, self).__init__()
  808. def parseCommandLine(self, argv=None):
  809. # We don't want any parameters parsed from the command line
  810. opts = super(TinfoilConfigParameters, self).parseCommandLine([])
  811. for key, val in self.initial_options.items():
  812. setattr(opts[0], key, val)
  813. return opts