blob: f2f59f670afaaaad82a2438884b48f6478870992 [file] [log] [blame]
Patrick Williamsc124f4f2015-09-15 14:41:29 -05001#!/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
25import os
26import sys
27import logging
28import optparse
29import warnings
Patrick Williamsc0f7c042017-02-23 20:41:17 -060030import fcntl
Patrick Williamsc124f4f2015-09-15 14:41:29 -050031
32import bb
33from bb import event
34import bb.msg
35from bb import cooker
36from bb import ui
37from bb import server
38from bb import cookerdata
39
40logger = logging.getLogger("BitBake")
41
42class BBMainException(Exception):
43 pass
44
45def present_options(optionlist):
46 if len(optionlist) > 1:
47 return ' or '.join([', '.join(optionlist[:-1]), optionlist[-1]])
48 else:
49 return optionlist[0]
50
51class BitbakeHelpFormatter(optparse.IndentedHelpFormatter):
52 def format_option(self, option):
53 # We need to do this here rather than in the text we supply to
54 # add_option() because we don't want to call list_extension_modules()
55 # on every execution (since it imports all of the modules)
56 # Note also that we modify option.help rather than the returned text
57 # - this is so that we don't have to re-format the text ourselves
58 if option.dest == 'ui':
59 valid_uis = list_extension_modules(bb.ui, 'main')
60 option.help = option.help.replace('@CHOICES@', present_options(valid_uis))
61 elif option.dest == 'servertype':
62 valid_server_types = list_extension_modules(bb.server, 'BitBakeServer')
63 option.help = option.help.replace('@CHOICES@', present_options(valid_server_types))
64
65 return optparse.IndentedHelpFormatter.format_option(self, option)
66
67def list_extension_modules(pkg, checkattr):
68 """
69 Lists extension modules in a specific Python package
70 (e.g. UIs, servers). NOTE: Calling this function will import all of the
71 submodules of the specified module in order to check for the specified
72 attribute; this can have unusual side-effects. As a result, this should
73 only be called when displaying help text or error messages.
74 Parameters:
75 pkg: previously imported Python package to list
76 checkattr: attribute to look for in module to determine if it's valid
77 as the type of extension you are looking for
78 """
79 import pkgutil
80 pkgdir = os.path.dirname(pkg.__file__)
81
82 modules = []
83 for _, modulename, _ in pkgutil.iter_modules([pkgdir]):
84 if os.path.isdir(os.path.join(pkgdir, modulename)):
85 # ignore directories
86 continue
87 try:
88 module = __import__(pkg.__name__, fromlist=[modulename])
89 except:
90 # If we can't import it, it's not valid
91 continue
92 module_if = getattr(module, modulename)
93 if getattr(module_if, 'hidden_extension', False):
94 continue
95 if not checkattr or hasattr(module_if, checkattr):
96 modules.append(modulename)
97 return modules
98
99def import_extension_module(pkg, modulename, checkattr):
100 try:
101 # Dynamically load the UI based on the ui name. Although we
102 # suggest a fixed set this allows you to have flexibility in which
103 # ones are available.
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600104 module = __import__(pkg.__name__, fromlist=[modulename])
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500105 return getattr(module, modulename)
106 except AttributeError:
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600107 modules = present_options(list_extension_modules(pkg, checkattr))
108 raise BBMainException('FATAL: Unable to import extension module "%s" from %s. '
109 'Valid extension modules: %s' % (modulename, pkg.__name__, modules))
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500110
111# Display bitbake/OE warnings via the BitBake.Warnings logger, ignoring others"""
112warnlog = logging.getLogger("BitBake.Warnings")
113_warnings_showwarning = warnings.showwarning
114def _showwarning(message, category, filename, lineno, file=None, line=None):
115 if file is not None:
116 if _warnings_showwarning is not None:
117 _warnings_showwarning(message, category, filename, lineno, file, line)
118 else:
119 s = warnings.formatwarning(message, category, filename, lineno)
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600120 warnlog.warning(s)
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500121
122warnings.showwarning = _showwarning
123warnings.filterwarnings("ignore")
124warnings.filterwarnings("default", module="(<string>$|(oe|bb)\.)")
125warnings.filterwarnings("ignore", category=PendingDeprecationWarning)
126warnings.filterwarnings("ignore", category=ImportWarning)
127warnings.filterwarnings("ignore", category=DeprecationWarning, module="<string>$")
128warnings.filterwarnings("ignore", message="With-statements now directly support multiple context managers")
129
130class BitBakeConfigParameters(cookerdata.ConfigParameters):
131
132 def parseCommandLine(self, argv=sys.argv):
133 parser = optparse.OptionParser(
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600134 formatter=BitbakeHelpFormatter(),
135 version="BitBake Build Tool Core version %s" % bb.__version__,
136 usage="""%prog [options] [recipename/target recipe:do_task ...]
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500137
138 Executes the specified task (default is 'build') for a given set of target recipes (.bb files).
139 It is assumed there is a conf/bblayers.conf available in cwd or in BBPATH which
140 will provide the layer, BBFILES and other configuration information.""")
141
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600142 parser.add_option("-b", "--buildfile", action="store", dest="buildfile", default=None,
143 help="Execute tasks from a specific .bb recipe directly. WARNING: Does "
144 "not handle any dependencies from other recipes.")
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500145
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600146 parser.add_option("-k", "--continue", action="store_false", dest="abort", default=True,
147 help="Continue as much as possible after an error. While the target that "
148 "failed and anything depending on it cannot be built, as much as "
149 "possible will be built before stopping.")
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500150
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600151 parser.add_option("-a", "--tryaltconfigs", action="store_true",
152 dest="tryaltconfigs", default=False,
153 help="Continue with builds by trying to use alternative providers "
154 "where possible.")
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500155
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600156 parser.add_option("-f", "--force", action="store_true", dest="force", default=False,
157 help="Force the specified targets/task to run (invalidating any "
158 "existing stamp file).")
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500159
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600160 parser.add_option("-c", "--cmd", action="store", dest="cmd",
161 help="Specify the task to execute. The exact options available "
162 "depend on the metadata. Some examples might be 'compile'"
163 " or 'populate_sysroot' or 'listtasks' may give a list of "
164 "the tasks available.")
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500165
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600166 parser.add_option("-C", "--clear-stamp", action="store", dest="invalidate_stamp",
167 help="Invalidate the stamp for the specified task such as 'compile' "
168 "and then run the default task for the specified target(s).")
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500169
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600170 parser.add_option("-r", "--read", action="append", dest="prefile", default=[],
171 help="Read the specified file before bitbake.conf.")
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500172
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600173 parser.add_option("-R", "--postread", action="append", dest="postfile", default=[],
174 help="Read the specified file after bitbake.conf.")
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500175
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600176 parser.add_option("-v", "--verbose", action="store_true", dest="verbose", default=False,
177 help="Output more log message data to the terminal.")
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500178
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600179 parser.add_option("-D", "--debug", action="count", dest="debug", default=0,
180 help="Increase the debug level. You can specify this more than once.")
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500181
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600182 parser.add_option("-q", "--quiet", action="store_true", dest="quiet", default=False,
183 help="Output less log message data to the terminal.")
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500184
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600185 parser.add_option("-n", "--dry-run", action="store_true", dest="dry_run", default=False,
186 help="Don't execute, just go through the motions.")
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500187
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600188 parser.add_option("-S", "--dump-signatures", action="append", dest="dump_signatures",
189 default=[], metavar="SIGNATURE_HANDLER",
190 help="Dump out the signature construction information, with no task "
191 "execution. The SIGNATURE_HANDLER parameter is passed to the "
192 "handler. Two common values are none and printdiff but the handler "
193 "may define more/less. none means only dump the signature, printdiff"
194 " means compare the dumped signature with the cached one.")
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500195
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600196 parser.add_option("-p", "--parse-only", action="store_true",
197 dest="parse_only", default=False,
198 help="Quit after parsing the BB recipes.")
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500199
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600200 parser.add_option("-s", "--show-versions", action="store_true",
201 dest="show_versions", default=False,
202 help="Show current and preferred versions of all recipes.")
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500203
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600204 parser.add_option("-e", "--environment", action="store_true",
205 dest="show_environment", default=False,
206 help="Show the global or per-recipe environment complete with information"
207 " about where variables were set/changed.")
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500208
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600209 parser.add_option("-g", "--graphviz", action="store_true", dest="dot_graph", default=False,
210 help="Save dependency tree information for the specified "
211 "targets in the dot syntax.")
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500212
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600213 parser.add_option("-I", "--ignore-deps", action="append",
214 dest="extra_assume_provided", default=[],
215 help="Assume these dependencies don't exist and are already provided "
216 "(equivalent to ASSUME_PROVIDED). Useful to make dependency "
217 "graphs more appealing")
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500218
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600219 parser.add_option("-l", "--log-domains", action="append", dest="debug_domains", default=[],
220 help="Show debug logging for the specified logging domains")
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500221
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600222 parser.add_option("-P", "--profile", action="store_true", dest="profile", default=False,
223 help="Profile the command and save reports.")
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500224
225 # @CHOICES@ is substituted out by BitbakeHelpFormatter above
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600226 parser.add_option("-u", "--ui", action="store", dest="ui",
227 default=os.environ.get('BITBAKE_UI', 'knotty'),
228 help="The user interface to use (@CHOICES@ - default %default).")
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500229
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600230 # @CHOICES@ is substituted out by BitbakeHelpFormatter above
231 parser.add_option("-t", "--servertype", action="store", dest="servertype",
232 default=["process", "xmlrpc"]["BBSERVER" in os.environ],
233 help="Choose which server type to use (@CHOICES@ - default %default).")
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500234
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600235 parser.add_option("", "--token", action="store", dest="xmlrpctoken",
236 default=os.environ.get("BBTOKEN"),
237 help="Specify the connection token to be used when connecting "
238 "to a remote server.")
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500239
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600240 parser.add_option("", "--revisions-changed", action="store_true",
241 dest="revisions_changed", default=False,
242 help="Set the exit code depending on whether upstream floating "
243 "revisions have changed or not.")
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500244
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600245 parser.add_option("", "--server-only", action="store_true",
246 dest="server_only", default=False,
247 help="Run bitbake without a UI, only starting a server "
248 "(cooker) process.")
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500249
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600250 parser.add_option("", "--foreground", action="store_true",
251 help="Run bitbake server in foreground.")
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500252
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600253 parser.add_option("-B", "--bind", action="store", dest="bind", default=False,
254 help="The name/address for the bitbake server to bind to.")
Patrick Williamsd8c66bc2016-06-20 12:57:21 -0500255
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600256 parser.add_option("-T", "--idle-timeout", type=int,
257 default=int(os.environ.get("BBTIMEOUT", "0")),
258 help="Set timeout to unload bitbake server due to inactivity")
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500259
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600260 parser.add_option("", "--no-setscene", action="store_true",
261 dest="nosetscene", default=False,
262 help="Do not run any setscene tasks. sstate will be ignored and "
263 "everything needed, built.")
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500264
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600265 parser.add_option("", "--setscene-only", action="store_true",
266 dest="setsceneonly", default=False,
267 help="Only run setscene tasks, don't run any real tasks.")
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500268
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600269 parser.add_option("", "--remote-server", action="store", dest="remote_server",
270 default=os.environ.get("BBSERVER"),
271 help="Connect to the specified server.")
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500272
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600273 parser.add_option("-m", "--kill-server", action="store_true",
274 dest="kill_server", default=False,
275 help="Terminate the remote server.")
276
277 parser.add_option("", "--observe-only", action="store_true",
278 dest="observe_only", default=False,
279 help="Connect to a server as an observing-only client.")
280
281 parser.add_option("", "--status-only", action="store_true",
282 dest="status_only", default=False,
283 help="Check the status of the remote bitbake server.")
284
285 parser.add_option("-w", "--write-log", action="store", dest="writeeventlog",
286 default=os.environ.get("BBEVENTLOG"),
287 help="Writes the event log of the build to a bitbake event json file. "
288 "Use '' (empty string) to assign the name automatically.")
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500289
290 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
311 # if BBSERVER says to autodetect, let's do that
312 if options.remote_server:
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600313 port = -1
314 if options.remote_server != 'autostart':
315 host, port = options.remote_server.split(":", 2)
316 port = int(port)
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500317 # use automatic port if port set to -1, means read it from
318 # the bitbake.lock file; this is a bit tricky, but we always expect
319 # to be in the base of the build directory if we need to have a
320 # chance to start the server later, anyway
321 if port == -1:
322 lock_location = "./bitbake.lock"
323 # we try to read the address at all times; if the server is not started,
324 # we'll try to start it after the first connect fails, below
325 try:
326 lf = open(lock_location, 'r')
327 remotedef = lf.readline()
328 [host, port] = remotedef.split(":")
329 port = int(port)
330 lf.close()
331 options.remote_server = remotedef
332 except Exception as e:
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600333 if options.remote_server != 'autostart':
334 raise BBMainException("Failed to read bitbake.lock (%s), invalid port" % str(e))
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500335
336 return options, targets[1:]
337
338
339def start_server(servermodule, configParams, configuration, features):
340 server = servermodule.BitBakeServer()
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600341 single_use = not configParams.server_only and os.getenv('BBSERVER') != 'autostart'
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500342 if configParams.bind:
343 (host, port) = configParams.bind.split(':')
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600344 server.initServer((host, int(port)), single_use=single_use,
345 idle_timeout=configParams.idle_timeout)
346 configuration.interface = [server.serverImpl.host, server.serverImpl.port]
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500347 else:
Patrick Williamsd8c66bc2016-06-20 12:57:21 -0500348 server.initServer(single_use=single_use)
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500349 configuration.interface = []
350
351 try:
352 configuration.setServerRegIdleCallback(server.getServerIdleCB())
353
354 cooker = bb.cooker.BBCooker(configuration, features)
355
356 server.addcooker(cooker)
357 server.saveConnectionDetails()
358 except Exception as e:
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500359 while hasattr(server, "event_queue"):
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600360 import queue
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500361 try:
362 event = server.event_queue.get(block=False)
363 except (queue.Empty, IOError):
364 break
365 if isinstance(event, logging.LogRecord):
366 logger.handle(event)
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600367 raise
368 if not configParams.foreground:
369 server.detach()
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500370 cooker.lock.close()
371 return server
372
373
374def bitbake_main(configParams, configuration):
375
376 # Python multiprocessing requires /dev/shm on Linux
377 if sys.platform.startswith('linux') and not os.access('/dev/shm', os.W_OK | os.X_OK):
378 raise BBMainException("FATAL: /dev/shm does not exist or is not writable")
379
380 # Unbuffer stdout to avoid log truncation in the event
381 # of an unorderly exit as well as to provide timely
382 # updates to log files for use with tail
383 try:
384 if sys.stdout.name == '<stdout>':
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600385 # Reopen with O_SYNC (unbuffered)
386 fl = fcntl.fcntl(sys.stdout.fileno(), fcntl.F_GETFL)
387 fl |= os.O_SYNC
388 fcntl.fcntl(sys.stdout.fileno(), fcntl.F_SETFL, fl)
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500389 except:
390 pass
391
392
393 configuration.setConfigParameters(configParams)
394
395 ui_module = import_extension_module(bb.ui, configParams.ui, 'main')
396 servermodule = import_extension_module(bb.server, configParams.servertype, 'BitBakeServer')
397
398 if configParams.server_only:
399 if configParams.servertype != "xmlrpc":
400 raise BBMainException("FATAL: If '--server-only' is defined, we must set the "
401 "servertype as 'xmlrpc'.\n")
402 if not configParams.bind:
403 raise BBMainException("FATAL: The '--server-only' option requires a name/address "
404 "to bind to with the -B option.\n")
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600405 else:
406 try:
407 #Checking that the port is a number
408 int(configParams.bind.split(":")[1])
409 except (ValueError,IndexError):
410 raise BBMainException(
411 "FATAL: Malformed host:port bind parameter")
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500412 if configParams.remote_server:
413 raise BBMainException("FATAL: The '--server-only' option conflicts with %s.\n" %
414 ("the BBSERVER environment variable" if "BBSERVER" in os.environ \
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600415 else "the '--remote-server' option"))
416
417 elif configParams.foreground:
418 raise BBMainException("FATAL: The '--foreground' option can only be used "
419 "with --server-only.\n")
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500420
421 if configParams.bind and configParams.servertype != "xmlrpc":
422 raise BBMainException("FATAL: If '-B' or '--bind' is defined, we must "
423 "set the servertype as 'xmlrpc'.\n")
424
425 if configParams.remote_server and configParams.servertype != "xmlrpc":
426 raise BBMainException("FATAL: If '--remote-server' is defined, we must "
427 "set the servertype as 'xmlrpc'.\n")
428
429 if configParams.observe_only and (not configParams.remote_server or configParams.bind):
430 raise BBMainException("FATAL: '--observe-only' can only be used by UI clients "
431 "connecting to a server.\n")
432
433 if configParams.kill_server and not configParams.remote_server:
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600434 raise BBMainException("FATAL: '--kill-server' can only be used to "
435 "terminate a remote server")
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500436
437 if "BBDEBUG" in os.environ:
438 level = int(os.environ["BBDEBUG"])
439 if level > configuration.debug:
440 configuration.debug = level
441
442 bb.msg.init_msgconfig(configParams.verbose, configuration.debug,
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600443 configuration.debug_domains)
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500444
445 # Ensure logging messages get sent to the UI as events
446 handler = bb.event.LogHandler()
447 if not configParams.status_only:
448 # In status only mode there are no logs and no UI
449 logger.addHandler(handler)
450
451 # Clear away any spurious environment variables while we stoke up the cooker
452 cleanedvars = bb.utils.clean_environment()
453
454 featureset = []
455 if not configParams.server_only:
456 # Collect the feature set for the UI
457 featureset = getattr(ui_module, "featureSet", [])
458
Patrick Williamsf1e5d692016-03-30 15:21:19 -0500459 if configParams.server_only:
460 for param in ('prefile', 'postfile'):
461 value = getattr(configParams, param)
462 if value:
463 setattr(configuration, "%s_server" % param, value)
464 param = "%s_server" % param
465
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500466 if not configParams.remote_server:
467 # we start a server with a given configuration
468 server = start_server(servermodule, configParams, configuration, featureset)
469 bb.event.ui_queue = []
470 else:
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600471 if os.getenv('BBSERVER') == 'autostart':
472 if configParams.remote_server == 'autostart' or \
473 not servermodule.check_connection(configParams.remote_server, timeout=2):
474 configParams.bind = 'localhost:0'
475 srv = start_server(servermodule, configParams, configuration, featureset)
476 configParams.remote_server = '%s:%d' % tuple(configuration.interface)
477 bb.event.ui_queue = []
478
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500479 # we start a stub server that is actually a XMLRPClient that connects to a real server
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600480 server = servermodule.BitBakeXMLRPCClient(configParams.observe_only,
481 configParams.xmlrpctoken)
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500482 server.saveConnectionDetails(configParams.remote_server)
483
484
485 if not configParams.server_only:
486 try:
487 server_connection = server.establishConnection(featureset)
488 except Exception as e:
489 bb.fatal("Could not connect to server %s: %s" % (configParams.remote_server, str(e)))
490
Patrick Williamsd8c66bc2016-06-20 12:57:21 -0500491 if configParams.kill_server:
492 server_connection.connection.terminateServer()
493 bb.event.ui_queue = []
494 return 0
495
496 server_connection.setupEventQueue()
497
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500498 # Restore the environment in case the UI needs it
499 for k in cleanedvars:
500 os.environ[k] = cleanedvars[k]
501
502 logger.removeHandler(handler)
503
504
505 if configParams.status_only:
506 server_connection.terminate()
507 return 0
508
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500509 try:
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600510 return ui_module.main(server_connection.connection, server_connection.events,
511 configParams)
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500512 finally:
513 bb.event.ui_queue = []
514 server_connection.terminate()
515 else:
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600516 print("Bitbake server address: %s, server port: %s" % (server.serverImpl.host,
517 server.serverImpl.port))
518 if configParams.foreground:
519 server.serverImpl.serve_forever()
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500520 return 0
521
522 return 1