tinfoil.py 37 KB

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