blob: ca59eb9af80c9d6f19a021850cd909b415cb6dc8 [file] [log] [blame]
Patrick Williamsc124f4f2015-09-15 14:41:29 -05001#!/usr/bin/env python
Patrick Williamsc124f4f2015-09-15 14:41:29 -05002#
3# Copyright (C) 2003, 2004 Chris Larson
4# Copyright (C) 2003, 2004 Phil Blundell
5# Copyright (C) 2003 - 2005 Michael 'Mickey' Lauer
6# Copyright (C) 2005 Holger Hans Peter Freyther
7# Copyright (C) 2005 ROAD GmbH
8# Copyright (C) 2006 Richard Purdie
9#
Brad Bishopc342db32019-05-15 21:57:59 -040010# SPDX-License-Identifier: GPL-2.0-only
Patrick Williamsc124f4f2015-09-15 14:41:29 -050011#
Patrick Williamsc124f4f2015-09-15 14:41:29 -050012
13import os
14import sys
15import logging
16import optparse
17import warnings
Patrick Williamsc0f7c042017-02-23 20:41:17 -060018import fcntl
Brad Bishopd7bf8c12018-02-25 22:55:05 -050019import time
20import traceback
Patrick Williamsc124f4f2015-09-15 14:41:29 -050021
22import bb
23from bb import event
24import bb.msg
25from bb import cooker
26from bb import ui
27from bb import server
28from bb import cookerdata
29
Brad Bishopd7bf8c12018-02-25 22:55:05 -050030import bb.server.process
31import bb.server.xmlrpcclient
32
Patrick Williamsc124f4f2015-09-15 14:41:29 -050033logger = logging.getLogger("BitBake")
34
35class BBMainException(Exception):
36 pass
37
Brad Bishopd7bf8c12018-02-25 22:55:05 -050038class BBMainFatal(bb.BBHandledException):
39 pass
40
Patrick Williamsc124f4f2015-09-15 14:41:29 -050041def present_options(optionlist):
42 if len(optionlist) > 1:
43 return ' or '.join([', '.join(optionlist[:-1]), optionlist[-1]])
44 else:
45 return optionlist[0]
46
47class BitbakeHelpFormatter(optparse.IndentedHelpFormatter):
48 def format_option(self, option):
49 # We need to do this here rather than in the text we supply to
50 # add_option() because we don't want to call list_extension_modules()
51 # on every execution (since it imports all of the modules)
52 # Note also that we modify option.help rather than the returned text
53 # - this is so that we don't have to re-format the text ourselves
54 if option.dest == 'ui':
55 valid_uis = list_extension_modules(bb.ui, 'main')
56 option.help = option.help.replace('@CHOICES@', present_options(valid_uis))
Patrick Williamsc124f4f2015-09-15 14:41:29 -050057
58 return optparse.IndentedHelpFormatter.format_option(self, option)
59
60def 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
75 modules = []
76 for _, modulename, _ in pkgutil.iter_modules([pkgdir]):
77 if os.path.isdir(os.path.join(pkgdir, modulename)):
78 # ignore directories
79 continue
80 try:
81 module = __import__(pkg.__name__, fromlist=[modulename])
82 except:
83 # If we can't import it, it's not valid
84 continue
85 module_if = getattr(module, modulename)
86 if getattr(module_if, 'hidden_extension', False):
87 continue
88 if not checkattr or hasattr(module_if, checkattr):
89 modules.append(modulename)
90 return modules
91
92def import_extension_module(pkg, modulename, checkattr):
93 try:
94 # Dynamically load the UI based on the ui name. Although we
95 # suggest a fixed set this allows you to have flexibility in which
96 # ones are available.
Patrick Williamsc0f7c042017-02-23 20:41:17 -060097 module = __import__(pkg.__name__, fromlist=[modulename])
Patrick Williamsc124f4f2015-09-15 14:41:29 -050098 return getattr(module, modulename)
99 except AttributeError:
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600100 modules = present_options(list_extension_modules(pkg, checkattr))
101 raise BBMainException('FATAL: Unable to import extension module "%s" from %s. '
102 'Valid extension modules: %s' % (modulename, pkg.__name__, modules))
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500103
104# Display bitbake/OE warnings via the BitBake.Warnings logger, ignoring others"""
105warnlog = logging.getLogger("BitBake.Warnings")
106_warnings_showwarning = warnings.showwarning
107def _showwarning(message, category, filename, lineno, file=None, line=None):
108 if file is not None:
109 if _warnings_showwarning is not None:
110 _warnings_showwarning(message, category, filename, lineno, file, line)
111 else:
112 s = warnings.formatwarning(message, category, filename, lineno)
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600113 warnlog.warning(s)
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500114
115warnings.showwarning = _showwarning
116warnings.filterwarnings("ignore")
117warnings.filterwarnings("default", module="(<string>$|(oe|bb)\.)")
118warnings.filterwarnings("ignore", category=PendingDeprecationWarning)
119warnings.filterwarnings("ignore", category=ImportWarning)
120warnings.filterwarnings("ignore", category=DeprecationWarning, module="<string>$")
121warnings.filterwarnings("ignore", message="With-statements now directly support multiple context managers")
122
123class BitBakeConfigParameters(cookerdata.ConfigParameters):
124
125 def parseCommandLine(self, argv=sys.argv):
126 parser = optparse.OptionParser(
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600127 formatter=BitbakeHelpFormatter(),
128 version="BitBake Build Tool Core version %s" % bb.__version__,
129 usage="""%prog [options] [recipename/target recipe:do_task ...]
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500130
131 Executes the specified task (default is 'build') for a given set of target recipes (.bb files).
132 It is assumed there is a conf/bblayers.conf available in cwd or in BBPATH which
133 will provide the layer, BBFILES and other configuration information.""")
134
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600135 parser.add_option("-b", "--buildfile", action="store", dest="buildfile", default=None,
136 help="Execute tasks from a specific .bb recipe directly. WARNING: Does "
137 "not handle any dependencies from other recipes.")
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500138
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600139 parser.add_option("-k", "--continue", action="store_false", dest="abort", default=True,
140 help="Continue as much as possible after an error. While the target that "
141 "failed and anything depending on it cannot be built, as much as "
142 "possible will be built before stopping.")
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500143
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600144 parser.add_option("-f", "--force", action="store_true", dest="force", default=False,
145 help="Force the specified targets/task to run (invalidating any "
146 "existing stamp file).")
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500147
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600148 parser.add_option("-c", "--cmd", action="store", dest="cmd",
149 help="Specify the task to execute. The exact options available "
150 "depend on the metadata. Some examples might be 'compile'"
151 " or 'populate_sysroot' or 'listtasks' may give a list of "
152 "the tasks available.")
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500153
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600154 parser.add_option("-C", "--clear-stamp", action="store", dest="invalidate_stamp",
155 help="Invalidate the stamp for the specified task such as 'compile' "
156 "and then run the default task for the specified target(s).")
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500157
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600158 parser.add_option("-r", "--read", action="append", dest="prefile", default=[],
159 help="Read the specified file before bitbake.conf.")
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500160
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600161 parser.add_option("-R", "--postread", action="append", dest="postfile", default=[],
162 help="Read the specified file after bitbake.conf.")
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500163
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600164 parser.add_option("-v", "--verbose", action="store_true", dest="verbose", default=False,
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500165 help="Enable tracing of shell tasks (with 'set -x'). "
166 "Also print bb.note(...) messages to stdout (in "
167 "addition to writing them to ${T}/log.do_<task>).")
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500168
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600169 parser.add_option("-D", "--debug", action="count", dest="debug", default=0,
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500170 help="Increase the debug level. You can specify this "
171 "more than once. -D sets the debug level to 1, "
172 "where only bb.debug(1, ...) messages are printed "
173 "to stdout; -DD sets the debug level to 2, where "
174 "both bb.debug(1, ...) and bb.debug(2, ...) "
175 "messages are printed; etc. Without -D, no debug "
176 "messages are printed. Note that -D only affects "
177 "output to stdout. All debug messages are written "
178 "to ${T}/log.do_taskname, regardless of the debug "
179 "level.")
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500180
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500181 parser.add_option("-q", "--quiet", action="count", dest="quiet", default=0,
182 help="Output less log message data to the terminal. You can specify this more than once.")
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500183
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600184 parser.add_option("-n", "--dry-run", action="store_true", dest="dry_run", default=False,
185 help="Don't execute, just go through the motions.")
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500186
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600187 parser.add_option("-S", "--dump-signatures", action="append", dest="dump_signatures",
188 default=[], metavar="SIGNATURE_HANDLER",
189 help="Dump out the signature construction information, with no task "
190 "execution. The SIGNATURE_HANDLER parameter is passed to the "
191 "handler. Two common values are none and printdiff but the handler "
192 "may define more/less. none means only dump the signature, printdiff"
193 " means compare the dumped signature with the cached one.")
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500194
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600195 parser.add_option("-p", "--parse-only", action="store_true",
196 dest="parse_only", default=False,
197 help="Quit after parsing the BB recipes.")
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500198
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600199 parser.add_option("-s", "--show-versions", action="store_true",
200 dest="show_versions", default=False,
201 help="Show current and preferred versions of all recipes.")
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500202
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600203 parser.add_option("-e", "--environment", action="store_true",
204 dest="show_environment", default=False,
205 help="Show the global or per-recipe environment complete with information"
206 " about where variables were set/changed.")
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500207
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600208 parser.add_option("-g", "--graphviz", action="store_true", dest="dot_graph", default=False,
209 help="Save dependency tree information for the specified "
210 "targets in the dot syntax.")
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500211
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600212 parser.add_option("-I", "--ignore-deps", action="append",
213 dest="extra_assume_provided", default=[],
214 help="Assume these dependencies don't exist and are already provided "
215 "(equivalent to ASSUME_PROVIDED). Useful to make dependency "
216 "graphs more appealing")
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500217
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600218 parser.add_option("-l", "--log-domains", action="append", dest="debug_domains", default=[],
219 help="Show debug logging for the specified logging domains")
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500220
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600221 parser.add_option("-P", "--profile", action="store_true", dest="profile", default=False,
222 help="Profile the command and save reports.")
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500223
224 # @CHOICES@ is substituted out by BitbakeHelpFormatter above
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600225 parser.add_option("-u", "--ui", action="store", dest="ui",
226 default=os.environ.get('BITBAKE_UI', 'knotty'),
227 help="The user interface to use (@CHOICES@ - default %default).")
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500228
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600229 parser.add_option("", "--token", action="store", dest="xmlrpctoken",
230 default=os.environ.get("BBTOKEN"),
231 help="Specify the connection token to be used when connecting "
232 "to a remote server.")
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500233
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600234 parser.add_option("", "--revisions-changed", action="store_true",
235 dest="revisions_changed", default=False,
236 help="Set the exit code depending on whether upstream floating "
237 "revisions have changed or not.")
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500238
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600239 parser.add_option("", "--server-only", action="store_true",
240 dest="server_only", default=False,
241 help="Run bitbake without a UI, only starting a server "
242 "(cooker) process.")
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500243
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600244 parser.add_option("-B", "--bind", action="store", dest="bind", default=False,
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500245 help="The name/address for the bitbake xmlrpc server to bind to.")
Patrick Williamsd8c66bc2016-06-20 12:57:21 -0500246
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500247 parser.add_option("-T", "--idle-timeout", type=float, dest="server_timeout",
248 default=os.getenv("BB_SERVER_TIMEOUT"),
249 help="Set timeout to unload bitbake server due to inactivity, "
250 "set to -1 means no unload, "
251 "default: Environment variable BB_SERVER_TIMEOUT.")
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500252
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600253 parser.add_option("", "--no-setscene", action="store_true",
254 dest="nosetscene", default=False,
255 help="Do not run any setscene tasks. sstate will be ignored and "
256 "everything needed, built.")
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500257
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600258 parser.add_option("", "--setscene-only", action="store_true",
259 dest="setsceneonly", default=False,
260 help="Only run setscene tasks, don't run any real tasks.")
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500261
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600262 parser.add_option("", "--remote-server", action="store", dest="remote_server",
263 default=os.environ.get("BBSERVER"),
264 help="Connect to the specified server.")
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500265
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600266 parser.add_option("-m", "--kill-server", action="store_true",
267 dest="kill_server", default=False,
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500268 help="Terminate any running bitbake server.")
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600269
270 parser.add_option("", "--observe-only", action="store_true",
271 dest="observe_only", default=False,
272 help="Connect to a server as an observing-only client.")
273
274 parser.add_option("", "--status-only", action="store_true",
275 dest="status_only", default=False,
276 help="Check the status of the remote bitbake server.")
277
278 parser.add_option("-w", "--write-log", action="store", dest="writeeventlog",
279 default=os.environ.get("BBEVENTLOG"),
280 help="Writes the event log of the build to a bitbake event json file. "
281 "Use '' (empty string) to assign the name automatically.")
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500282
Brad Bishop316dfdd2018-06-25 12:45:53 -0400283 parser.add_option("", "--runall", action="append", dest="runall",
284 help="Run the specified task for any recipe in the taskgraph of the specified target (even if it wouldn't otherwise have run).")
285
286 parser.add_option("", "--runonly", action="append", dest="runonly",
287 help="Run only the specified task within the taskgraph of the specified targets (and any task dependencies those tasks may have).")
288
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500289
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500290 options, targets = parser.parse_args(argv)
291
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600292 if options.quiet and options.verbose:
293 parser.error("options --quiet and --verbose are mutually exclusive")
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500294
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600295 if options.quiet and options.debug:
296 parser.error("options --quiet and --debug are mutually exclusive")
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500297
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600298 # use configuration files from environment variables
299 if "BBPRECONF" in os.environ:
300 options.prefile.append(os.environ["BBPRECONF"])
301
302 if "BBPOSTCONF" in os.environ:
303 options.postfile.append(os.environ["BBPOSTCONF"])
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500304
305 # fill in proper log name if not supplied
306 if options.writeeventlog is not None and len(options.writeeventlog) == 0:
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600307 from datetime import datetime
308 eventlog = "bitbake_eventlog_%s.json" % datetime.now().strftime("%Y%m%d%H%M%S")
309 options.writeeventlog = eventlog
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500310
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500311 if options.bind:
312 try:
313 #Checking that the port is a number and is a ':' delimited value
314 (host, port) = options.bind.split(':')
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600315 port = int(port)
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500316 except (ValueError,IndexError):
317 raise BBMainException("FATAL: Malformed host:port bind parameter")
318 options.xmlrpcinterface = (host, port)
319 else:
320 options.xmlrpcinterface = (None, 0)
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500321
322 return options, targets[1:]
323
324
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500325def bitbake_main(configParams, configuration):
326
327 # Python multiprocessing requires /dev/shm on Linux
328 if sys.platform.startswith('linux') and not os.access('/dev/shm', os.W_OK | os.X_OK):
329 raise BBMainException("FATAL: /dev/shm does not exist or is not writable")
330
331 # Unbuffer stdout to avoid log truncation in the event
332 # of an unorderly exit as well as to provide timely
333 # updates to log files for use with tail
334 try:
335 if sys.stdout.name == '<stdout>':
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600336 # Reopen with O_SYNC (unbuffered)
337 fl = fcntl.fcntl(sys.stdout.fileno(), fcntl.F_GETFL)
338 fl |= os.O_SYNC
339 fcntl.fcntl(sys.stdout.fileno(), fcntl.F_SETFL, fl)
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500340 except:
341 pass
342
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500343 configuration.setConfigParameters(configParams)
344
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500345 if configParams.server_only and configParams.remote_server:
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500346 raise BBMainException("FATAL: The '--server-only' option conflicts with %s.\n" %
347 ("the BBSERVER environment variable" if "BBSERVER" in os.environ \
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600348 else "the '--remote-server' option"))
349
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500350 if configParams.observe_only and not (configParams.remote_server or configParams.bind):
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500351 raise BBMainException("FATAL: '--observe-only' can only be used by UI clients "
352 "connecting to a server.\n")
353
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500354 if "BBDEBUG" in os.environ:
355 level = int(os.environ["BBDEBUG"])
356 if level > configuration.debug:
357 configuration.debug = level
358
359 bb.msg.init_msgconfig(configParams.verbose, configuration.debug,
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600360 configuration.debug_domains)
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500361
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500362 server_connection, ui_module = setup_bitbake(configParams, configuration)
363 # No server connection
364 if server_connection is None:
365 if configParams.status_only:
366 return 1
367 if configParams.kill_server:
368 return 0
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500369
370 if not configParams.server_only:
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500371 if configParams.status_only:
372 server_connection.terminate()
373 return 0
374
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500375 try:
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500376 for event in bb.event.ui_queue:
377 server_connection.events.queue_event(event)
378 bb.event.ui_queue = []
379
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600380 return ui_module.main(server_connection.connection, server_connection.events,
381 configParams)
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500382 finally:
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500383 server_connection.terminate()
384 else:
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500385 return 0
386
387 return 1
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500388
389def setup_bitbake(configParams, configuration, extrafeatures=None):
390 # Ensure logging messages get sent to the UI as events
391 handler = bb.event.LogHandler()
392 if not configParams.status_only:
393 # In status only mode there are no logs and no UI
394 logger.addHandler(handler)
395
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500396 if configParams.server_only:
397 featureset = []
398 ui_module = None
399 else:
400 ui_module = import_extension_module(bb.ui, configParams.ui, 'main')
401 # Collect the feature set for the UI
402 featureset = getattr(ui_module, "featureSet", [])
403
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500404 if extrafeatures:
405 for feature in extrafeatures:
406 if not feature in featureset:
407 featureset.append(feature)
408
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500409 server_connection = None
410
Brad Bishop6ef32652018-10-09 18:59:25 +0100411 # Clear away any spurious environment variables while we stoke up the cooker
412 # (done after import_extension_module() above since for example import gi triggers env var usage)
413 cleanedvars = bb.utils.clean_environment()
414
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500415 if configParams.remote_server:
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500416 # Connect to a remote XMLRPC server
417 server_connection = bb.server.xmlrpcclient.connectXMLRPC(configParams.remote_server, featureset,
418 configParams.observe_only, configParams.xmlrpctoken)
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500419 else:
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500420 retries = 8
421 while retries:
422 try:
423 topdir, lock = lockBitbake()
424 sockname = topdir + "/bitbake.sock"
425 if lock:
426 if configParams.status_only or configParams.kill_server:
427 logger.info("bitbake server is not running.")
428 lock.close()
429 return None, None
430 # we start a server with a given configuration
431 logger.info("Starting bitbake server...")
432 # Clear the event queue since we already displayed messages
433 bb.event.ui_queue = []
434 server = bb.server.process.BitBakeServer(lock, sockname, configuration, featureset)
435
436 else:
437 logger.info("Reconnecting to bitbake server...")
438 if not os.path.exists(sockname):
Brad Bishope2d5b612018-11-23 10:55:50 +1300439 logger.info("Previous bitbake instance shutting down?, waiting to retry...")
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500440 i = 0
441 lock = None
442 # Wait for 5s or until we can get the lock
443 while not lock and i < 50:
444 time.sleep(0.1)
445 _, lock = lockBitbake()
446 i += 1
447 if lock:
448 bb.utils.unlockfile(lock)
449 raise bb.server.process.ProcessTimeout("Bitbake still shutting down as socket exists but no lock?")
450 if not configParams.server_only:
451 try:
452 server_connection = bb.server.process.connectProcessServer(sockname, featureset)
453 except EOFError:
454 # The server may have been shutting down but not closed the socket yet. If that happened,
455 # ignore it.
456 pass
457
458 if server_connection or configParams.server_only:
459 break
460 except BBMainFatal:
461 raise
462 except (Exception, bb.server.process.ProcessTimeout) as e:
463 if not retries:
464 raise
465 retries -= 1
Brad Bishop19323692019-04-05 15:28:33 -0400466 tryno = 8 - retries
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500467 if isinstance(e, (bb.server.process.ProcessTimeout, BrokenPipeError)):
Brad Bishop19323692019-04-05 15:28:33 -0400468 logger.info("Retrying server connection (#%d)..." % tryno)
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500469 else:
Brad Bishop19323692019-04-05 15:28:33 -0400470 logger.info("Retrying server connection (#%d)... (%s)" % (tryno, traceback.format_exc()))
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500471 if not retries:
472 bb.fatal("Unable to connect to bitbake server, or start one")
473 if retries < 5:
474 time.sleep(5)
475
476 if configParams.kill_server:
477 server_connection.connection.terminateServer()
478 server_connection.terminate()
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500479 bb.event.ui_queue = []
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500480 logger.info("Terminated bitbake server.")
481 return None, None
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500482
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500483 # Restore the environment in case the UI needs it
484 for k in cleanedvars:
485 os.environ[k] = cleanedvars[k]
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500486
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500487 logger.removeHandler(handler)
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500488
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500489 return server_connection, ui_module
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500490
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500491def lockBitbake():
492 topdir = bb.cookerdata.findTopdir()
493 if not topdir:
Brad Bishop15ae2502019-06-18 21:44:24 -0400494 bb.error("Unable to find conf/bblayers.conf or conf/bitbake.conf. BBPATH is unset and/or not in a build directory?")
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500495 raise BBMainFatal
496 lockfile = topdir + "/bitbake.lock"
497 return topdir, bb.utils.lockfile(lockfile, False, False)
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500498