main.py 22 KB

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