tinfoil.py 39 KB

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