main.py 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500
  1. #!/usr/bin/env python
  2. # ex:ts=4:sw=4:sts=4:et
  3. # -*- tab-width: 4; c-basic-offset: 4; indent-tabs-mode: nil -*-
  4. #
  5. # Copyright (C) 2003, 2004 Chris Larson
  6. # Copyright (C) 2003, 2004 Phil Blundell
  7. # Copyright (C) 2003 - 2005 Michael 'Mickey' Lauer
  8. # Copyright (C) 2005 Holger Hans Peter Freyther
  9. # Copyright (C) 2005 ROAD GmbH
  10. # Copyright (C) 2006 Richard Purdie
  11. #
  12. # SPDX-License-Identifier: GPL-2.0-only
  13. #
  14. import os
  15. import sys
  16. import logging
  17. import optparse
  18. import warnings
  19. import fcntl
  20. import time
  21. import traceback
  22. import bb
  23. from bb import event
  24. import bb.msg
  25. from bb import cooker
  26. from bb import ui
  27. from bb import server
  28. from bb import cookerdata
  29. import bb.server.process
  30. import bb.server.xmlrpcclient
  31. logger = logging.getLogger("BitBake")
  32. class BBMainException(Exception):
  33. pass
  34. class BBMainFatal(bb.BBHandledException):
  35. pass
  36. def present_options(optionlist):
  37. if len(optionlist) > 1:
  38. return ' or '.join([', '.join(optionlist[:-1]), optionlist[-1]])
  39. else:
  40. return optionlist[0]
  41. class BitbakeHelpFormatter(optparse.IndentedHelpFormatter):
  42. def format_option(self, option):
  43. # We need to do this here rather than in the text we supply to
  44. # add_option() because we don't want to call list_extension_modules()
  45. # on every execution (since it imports all of the modules)
  46. # Note also that we modify option.help rather than the returned text
  47. # - this is so that we don't have to re-format the text ourselves
  48. if option.dest == 'ui':
  49. valid_uis = list_extension_modules(bb.ui, 'main')
  50. option.help = option.help.replace('@CHOICES@', present_options(valid_uis))
  51. return optparse.IndentedHelpFormatter.format_option(self, option)
  52. def list_extension_modules(pkg, checkattr):
  53. """
  54. Lists extension modules in a specific Python package
  55. (e.g. UIs, servers). NOTE: Calling this function will import all of the
  56. submodules of the specified module in order to check for the specified
  57. attribute; this can have unusual side-effects. As a result, this should
  58. only be called when displaying help text or error messages.
  59. Parameters:
  60. pkg: previously imported Python package to list
  61. checkattr: attribute to look for in module to determine if it's valid
  62. as the type of extension you are looking for
  63. """
  64. import pkgutil
  65. pkgdir = os.path.dirname(pkg.__file__)
  66. modules = []
  67. for _, modulename, _ in pkgutil.iter_modules([pkgdir]):
  68. if os.path.isdir(os.path.join(pkgdir, modulename)):
  69. # ignore directories
  70. continue
  71. try:
  72. module = __import__(pkg.__name__, fromlist=[modulename])
  73. except:
  74. # If we can't import it, it's not valid
  75. continue
  76. module_if = getattr(module, modulename)
  77. if getattr(module_if, 'hidden_extension', False):
  78. continue
  79. if not checkattr or hasattr(module_if, checkattr):
  80. modules.append(modulename)
  81. return modules
  82. def import_extension_module(pkg, modulename, checkattr):
  83. try:
  84. # Dynamically load the UI based on the ui name. Although we
  85. # suggest a fixed set this allows you to have flexibility in which
  86. # ones are available.
  87. module = __import__(pkg.__name__, fromlist=[modulename])
  88. return getattr(module, modulename)
  89. except AttributeError:
  90. modules = present_options(list_extension_modules(pkg, checkattr))
  91. raise BBMainException('FATAL: Unable to import extension module "%s" from %s. '
  92. 'Valid extension modules: %s' % (modulename, pkg.__name__, modules))
  93. # Display bitbake/OE warnings via the BitBake.Warnings logger, ignoring others"""
  94. warnlog = logging.getLogger("BitBake.Warnings")
  95. _warnings_showwarning = warnings.showwarning
  96. def _showwarning(message, category, filename, lineno, file=None, line=None):
  97. if file is not None:
  98. if _warnings_showwarning is not None:
  99. _warnings_showwarning(message, category, filename, lineno, file, line)
  100. else:
  101. s = warnings.formatwarning(message, category, filename, lineno)
  102. warnlog.warning(s)
  103. warnings.showwarning = _showwarning
  104. warnings.filterwarnings("ignore")
  105. warnings.filterwarnings("default", module="(<string>$|(oe|bb)\.)")
  106. warnings.filterwarnings("ignore", category=PendingDeprecationWarning)
  107. warnings.filterwarnings("ignore", category=ImportWarning)
  108. warnings.filterwarnings("ignore", category=DeprecationWarning, module="<string>$")
  109. warnings.filterwarnings("ignore", message="With-statements now directly support multiple context managers")
  110. class BitBakeConfigParameters(cookerdata.ConfigParameters):
  111. def parseCommandLine(self, argv=sys.argv):
  112. parser = optparse.OptionParser(
  113. formatter=BitbakeHelpFormatter(),
  114. version="BitBake Build Tool Core version %s" % bb.__version__,
  115. usage="""%prog [options] [recipename/target recipe:do_task ...]
  116. Executes the specified task (default is 'build') for a given set of target recipes (.bb files).
  117. It is assumed there is a conf/bblayers.conf available in cwd or in BBPATH which
  118. will provide the layer, BBFILES and other configuration information.""")
  119. parser.add_option("-b", "--buildfile", action="store", dest="buildfile", default=None,
  120. help="Execute tasks from a specific .bb recipe directly. WARNING: Does "
  121. "not handle any dependencies from other recipes.")
  122. parser.add_option("-k", "--continue", action="store_false", dest="abort", default=True,
  123. help="Continue as much as possible after an error. While the target that "
  124. "failed and anything depending on it cannot be built, as much as "
  125. "possible will be built before stopping.")
  126. parser.add_option("-f", "--force", action="store_true", dest="force", default=False,
  127. help="Force the specified targets/task to run (invalidating any "
  128. "existing stamp file).")
  129. parser.add_option("-c", "--cmd", action="store", dest="cmd",
  130. help="Specify the task to execute. The exact options available "
  131. "depend on the metadata. Some examples might be 'compile'"
  132. " or 'populate_sysroot' or 'listtasks' may give a list of "
  133. "the tasks available.")
  134. parser.add_option("-C", "--clear-stamp", action="store", dest="invalidate_stamp",
  135. help="Invalidate the stamp for the specified task such as 'compile' "
  136. "and then run the default task for the specified target(s).")
  137. parser.add_option("-r", "--read", action="append", dest="prefile", default=[],
  138. help="Read the specified file before bitbake.conf.")
  139. parser.add_option("-R", "--postread", action="append", dest="postfile", default=[],
  140. help="Read the specified file after bitbake.conf.")
  141. parser.add_option("-v", "--verbose", action="store_true", dest="verbose", default=False,
  142. help="Enable tracing of shell tasks (with 'set -x'). "
  143. "Also print bb.note(...) messages to stdout (in "
  144. "addition to writing them to ${T}/log.do_<task>).")
  145. parser.add_option("-D", "--debug", action="count", dest="debug", default=0,
  146. help="Increase the debug level. You can specify this "
  147. "more than once. -D sets the debug level to 1, "
  148. "where only bb.debug(1, ...) messages are printed "
  149. "to stdout; -DD sets the debug level to 2, where "
  150. "both bb.debug(1, ...) and bb.debug(2, ...) "
  151. "messages are printed; etc. Without -D, no debug "
  152. "messages are printed. Note that -D only affects "
  153. "output to stdout. All debug messages are written "
  154. "to ${T}/log.do_taskname, regardless of the debug "
  155. "level.")
  156. parser.add_option("-q", "--quiet", action="count", dest="quiet", default=0,
  157. help="Output less log message data to the terminal. You can specify this more than once.")
  158. parser.add_option("-n", "--dry-run", action="store_true", dest="dry_run", default=False,
  159. help="Don't execute, just go through the motions.")
  160. parser.add_option("-S", "--dump-signatures", action="append", dest="dump_signatures",
  161. default=[], metavar="SIGNATURE_HANDLER",
  162. help="Dump out the signature construction information, with no task "
  163. "execution. The SIGNATURE_HANDLER parameter is passed to the "
  164. "handler. Two common values are none and printdiff but the handler "
  165. "may define more/less. none means only dump the signature, printdiff"
  166. " means compare the dumped signature with the cached one.")
  167. parser.add_option("-p", "--parse-only", action="store_true",
  168. dest="parse_only", default=False,
  169. help="Quit after parsing the BB recipes.")
  170. parser.add_option("-s", "--show-versions", action="store_true",
  171. dest="show_versions", default=False,
  172. help="Show current and preferred versions of all recipes.")
  173. parser.add_option("-e", "--environment", action="store_true",
  174. dest="show_environment", default=False,
  175. help="Show the global or per-recipe environment complete with information"
  176. " about where variables were set/changed.")
  177. parser.add_option("-g", "--graphviz", action="store_true", dest="dot_graph", default=False,
  178. help="Save dependency tree information for the specified "
  179. "targets in the dot syntax.")
  180. parser.add_option("-I", "--ignore-deps", action="append",
  181. dest="extra_assume_provided", default=[],
  182. help="Assume these dependencies don't exist and are already provided "
  183. "(equivalent to ASSUME_PROVIDED). Useful to make dependency "
  184. "graphs more appealing")
  185. parser.add_option("-l", "--log-domains", action="append", dest="debug_domains", default=[],
  186. help="Show debug logging for the specified logging domains")
  187. parser.add_option("-P", "--profile", action="store_true", dest="profile", default=False,
  188. help="Profile the command and save reports.")
  189. # @CHOICES@ is substituted out by BitbakeHelpFormatter above
  190. parser.add_option("-u", "--ui", action="store", dest="ui",
  191. default=os.environ.get('BITBAKE_UI', 'knotty'),
  192. help="The user interface to use (@CHOICES@ - default %default).")
  193. parser.add_option("", "--token", action="store", dest="xmlrpctoken",
  194. default=os.environ.get("BBTOKEN"),
  195. help="Specify the connection token to be used when connecting "
  196. "to a remote server.")
  197. parser.add_option("", "--revisions-changed", action="store_true",
  198. dest="revisions_changed", default=False,
  199. help="Set the exit code depending on whether upstream floating "
  200. "revisions have changed or not.")
  201. parser.add_option("", "--server-only", action="store_true",
  202. dest="server_only", default=False,
  203. help="Run bitbake without a UI, only starting a server "
  204. "(cooker) process.")
  205. parser.add_option("-B", "--bind", action="store", dest="bind", default=False,
  206. help="The name/address for the bitbake xmlrpc server to bind to.")
  207. parser.add_option("-T", "--idle-timeout", type=float, dest="server_timeout",
  208. default=os.getenv("BB_SERVER_TIMEOUT"),
  209. help="Set timeout to unload bitbake server due to inactivity, "
  210. "set to -1 means no unload, "
  211. "default: Environment variable BB_SERVER_TIMEOUT.")
  212. parser.add_option("", "--no-setscene", action="store_true",
  213. dest="nosetscene", default=False,
  214. help="Do not run any setscene tasks. sstate will be ignored and "
  215. "everything needed, built.")
  216. parser.add_option("", "--setscene-only", action="store_true",
  217. dest="setsceneonly", default=False,
  218. help="Only run setscene tasks, don't run any real tasks.")
  219. parser.add_option("", "--remote-server", action="store", dest="remote_server",
  220. default=os.environ.get("BBSERVER"),
  221. help="Connect to the specified server.")
  222. parser.add_option("-m", "--kill-server", action="store_true",
  223. dest="kill_server", default=False,
  224. help="Terminate any running bitbake server.")
  225. parser.add_option("", "--observe-only", action="store_true",
  226. dest="observe_only", default=False,
  227. help="Connect to a server as an observing-only client.")
  228. parser.add_option("", "--status-only", action="store_true",
  229. dest="status_only", default=False,
  230. help="Check the status of the remote bitbake server.")
  231. parser.add_option("-w", "--write-log", action="store", dest="writeeventlog",
  232. default=os.environ.get("BBEVENTLOG"),
  233. help="Writes the event log of the build to a bitbake event json file. "
  234. "Use '' (empty string) to assign the name automatically.")
  235. parser.add_option("", "--runall", action="append", dest="runall",
  236. help="Run the specified task for any recipe in the taskgraph of the specified target (even if it wouldn't otherwise have run).")
  237. parser.add_option("", "--runonly", action="append", dest="runonly",
  238. help="Run only the specified task within the taskgraph of the specified targets (and any task dependencies those tasks may have).")
  239. options, targets = parser.parse_args(argv)
  240. if options.quiet and options.verbose:
  241. parser.error("options --quiet and --verbose are mutually exclusive")
  242. if options.quiet and options.debug:
  243. parser.error("options --quiet and --debug are mutually exclusive")
  244. # use configuration files from environment variables
  245. if "BBPRECONF" in os.environ:
  246. options.prefile.append(os.environ["BBPRECONF"])
  247. if "BBPOSTCONF" in os.environ:
  248. options.postfile.append(os.environ["BBPOSTCONF"])
  249. # fill in proper log name if not supplied
  250. if options.writeeventlog is not None and len(options.writeeventlog) == 0:
  251. from datetime import datetime
  252. eventlog = "bitbake_eventlog_%s.json" % datetime.now().strftime("%Y%m%d%H%M%S")
  253. options.writeeventlog = eventlog
  254. if options.bind:
  255. try:
  256. #Checking that the port is a number and is a ':' delimited value
  257. (host, port) = options.bind.split(':')
  258. port = int(port)
  259. except (ValueError,IndexError):
  260. raise BBMainException("FATAL: Malformed host:port bind parameter")
  261. options.xmlrpcinterface = (host, port)
  262. else:
  263. options.xmlrpcinterface = (None, 0)
  264. return options, targets[1:]
  265. def bitbake_main(configParams, configuration):
  266. # Python multiprocessing requires /dev/shm on Linux
  267. if sys.platform.startswith('linux') and not os.access('/dev/shm', os.W_OK | os.X_OK):
  268. raise BBMainException("FATAL: /dev/shm does not exist or is not writable")
  269. # Unbuffer stdout to avoid log truncation in the event
  270. # of an unorderly exit as well as to provide timely
  271. # updates to log files for use with tail
  272. try:
  273. if sys.stdout.name == '<stdout>':
  274. # Reopen with O_SYNC (unbuffered)
  275. fl = fcntl.fcntl(sys.stdout.fileno(), fcntl.F_GETFL)
  276. fl |= os.O_SYNC
  277. fcntl.fcntl(sys.stdout.fileno(), fcntl.F_SETFL, fl)
  278. except:
  279. pass
  280. configuration.setConfigParameters(configParams)
  281. if configParams.server_only and configParams.remote_server:
  282. raise BBMainException("FATAL: The '--server-only' option conflicts with %s.\n" %
  283. ("the BBSERVER environment variable" if "BBSERVER" in os.environ \
  284. else "the '--remote-server' option"))
  285. if configParams.observe_only and not (configParams.remote_server or configParams.bind):
  286. raise BBMainException("FATAL: '--observe-only' can only be used by UI clients "
  287. "connecting to a server.\n")
  288. if "BBDEBUG" in os.environ:
  289. level = int(os.environ["BBDEBUG"])
  290. if level > configuration.debug:
  291. configuration.debug = level
  292. bb.msg.init_msgconfig(configParams.verbose, configuration.debug,
  293. configuration.debug_domains)
  294. server_connection, ui_module = setup_bitbake(configParams, configuration)
  295. # No server connection
  296. if server_connection is None:
  297. if configParams.status_only:
  298. return 1
  299. if configParams.kill_server:
  300. return 0
  301. if not configParams.server_only:
  302. if configParams.status_only:
  303. server_connection.terminate()
  304. return 0
  305. try:
  306. for event in bb.event.ui_queue:
  307. server_connection.events.queue_event(event)
  308. bb.event.ui_queue = []
  309. return ui_module.main(server_connection.connection, server_connection.events,
  310. configParams)
  311. finally:
  312. server_connection.terminate()
  313. else:
  314. return 0
  315. return 1
  316. def setup_bitbake(configParams, configuration, extrafeatures=None):
  317. # Ensure logging messages get sent to the UI as events
  318. handler = bb.event.LogHandler()
  319. if not configParams.status_only:
  320. # In status only mode there are no logs and no UI
  321. logger.addHandler(handler)
  322. if configParams.server_only:
  323. featureset = []
  324. ui_module = None
  325. else:
  326. ui_module = import_extension_module(bb.ui, configParams.ui, 'main')
  327. # Collect the feature set for the UI
  328. featureset = getattr(ui_module, "featureSet", [])
  329. if extrafeatures:
  330. for feature in extrafeatures:
  331. if not feature in featureset:
  332. featureset.append(feature)
  333. server_connection = None
  334. # Clear away any spurious environment variables while we stoke up the cooker
  335. # (done after import_extension_module() above since for example import gi triggers env var usage)
  336. cleanedvars = bb.utils.clean_environment()
  337. if configParams.remote_server:
  338. # Connect to a remote XMLRPC server
  339. server_connection = bb.server.xmlrpcclient.connectXMLRPC(configParams.remote_server, featureset,
  340. configParams.observe_only, configParams.xmlrpctoken)
  341. else:
  342. retries = 8
  343. while retries:
  344. try:
  345. topdir, lock = lockBitbake()
  346. sockname = topdir + "/bitbake.sock"
  347. if lock:
  348. if configParams.status_only or configParams.kill_server:
  349. logger.info("bitbake server is not running.")
  350. lock.close()
  351. return None, None
  352. # we start a server with a given configuration
  353. logger.info("Starting bitbake server...")
  354. # Clear the event queue since we already displayed messages
  355. bb.event.ui_queue = []
  356. server = bb.server.process.BitBakeServer(lock, sockname, configuration, featureset)
  357. else:
  358. logger.info("Reconnecting to bitbake server...")
  359. if not os.path.exists(sockname):
  360. logger.info("Previous bitbake instance shutting down?, waiting to retry...")
  361. i = 0
  362. lock = None
  363. # Wait for 5s or until we can get the lock
  364. while not lock and i < 50:
  365. time.sleep(0.1)
  366. _, lock = lockBitbake()
  367. i += 1
  368. if lock:
  369. bb.utils.unlockfile(lock)
  370. raise bb.server.process.ProcessTimeout("Bitbake still shutting down as socket exists but no lock?")
  371. if not configParams.server_only:
  372. try:
  373. server_connection = bb.server.process.connectProcessServer(sockname, featureset)
  374. except EOFError:
  375. # The server may have been shutting down but not closed the socket yet. If that happened,
  376. # ignore it.
  377. pass
  378. if server_connection or configParams.server_only:
  379. break
  380. except BBMainFatal:
  381. raise
  382. except (Exception, bb.server.process.ProcessTimeout) as e:
  383. if not retries:
  384. raise
  385. retries -= 1
  386. tryno = 8 - retries
  387. if isinstance(e, (bb.server.process.ProcessTimeout, BrokenPipeError)):
  388. logger.info("Retrying server connection (#%d)..." % tryno)
  389. else:
  390. logger.info("Retrying server connection (#%d)... (%s)" % (tryno, traceback.format_exc()))
  391. if not retries:
  392. bb.fatal("Unable to connect to bitbake server, or start one")
  393. if retries < 5:
  394. time.sleep(5)
  395. if configParams.kill_server:
  396. server_connection.connection.terminateServer()
  397. server_connection.terminate()
  398. bb.event.ui_queue = []
  399. logger.info("Terminated bitbake server.")
  400. return None, None
  401. # Restore the environment in case the UI needs it
  402. for k in cleanedvars:
  403. os.environ[k] = cleanedvars[k]
  404. logger.removeHandler(handler)
  405. return server_connection, ui_module
  406. def lockBitbake():
  407. topdir = bb.cookerdata.findTopdir()
  408. if not topdir:
  409. bb.error("Unable to find conf/bblayers.conf or conf/bitbake.conf. BBAPTH is unset and/or not in a build directory?")
  410. raise BBMainFatal
  411. lockfile = topdir + "/bitbake.lock"
  412. return topdir, bb.utils.lockfile(lockfile, False, False)