main.py 22 KB

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