blob: 8c948c2c154cd1785151ecd8a2e630465268bebf [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,
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500177 help="Enable tracing of shell tasks (with 'set -x'). "
178 "Also print bb.note(...) messages to stdout (in "
179 "addition to writing them to ${T}/log.do_<task>).")
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500180
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600181 parser.add_option("-D", "--debug", action="count", dest="debug", default=0,
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500182 help="Increase the debug level. You can specify this "
183 "more than once. -D sets the debug level to 1, "
184 "where only bb.debug(1, ...) messages are printed "
185 "to stdout; -DD sets the debug level to 2, where "
186 "both bb.debug(1, ...) and bb.debug(2, ...) "
187 "messages are printed; etc. Without -D, no debug "
188 "messages are printed. Note that -D only affects "
189 "output to stdout. All debug messages are written "
190 "to ${T}/log.do_taskname, regardless of the debug "
191 "level.")
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500192
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500193 parser.add_option("-q", "--quiet", action="count", dest="quiet", default=0,
194 help="Output less log message data to the terminal. You can specify this more than once.")
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500195
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600196 parser.add_option("-n", "--dry-run", action="store_true", dest="dry_run", default=False,
197 help="Don't execute, just go through the motions.")
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500198
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600199 parser.add_option("-S", "--dump-signatures", action="append", dest="dump_signatures",
200 default=[], metavar="SIGNATURE_HANDLER",
201 help="Dump out the signature construction information, with no task "
202 "execution. The SIGNATURE_HANDLER parameter is passed to the "
203 "handler. Two common values are none and printdiff but the handler "
204 "may define more/less. none means only dump the signature, printdiff"
205 " means compare the dumped signature with the cached one.")
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500206
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600207 parser.add_option("-p", "--parse-only", action="store_true",
208 dest="parse_only", default=False,
209 help="Quit after parsing the BB recipes.")
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500210
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600211 parser.add_option("-s", "--show-versions", action="store_true",
212 dest="show_versions", default=False,
213 help="Show current and preferred versions of all recipes.")
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500214
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600215 parser.add_option("-e", "--environment", action="store_true",
216 dest="show_environment", default=False,
217 help="Show the global or per-recipe environment complete with information"
218 " about where variables were set/changed.")
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500219
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600220 parser.add_option("-g", "--graphviz", action="store_true", dest="dot_graph", default=False,
221 help="Save dependency tree information for the specified "
222 "targets in the dot syntax.")
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500223
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600224 parser.add_option("-I", "--ignore-deps", action="append",
225 dest="extra_assume_provided", default=[],
226 help="Assume these dependencies don't exist and are already provided "
227 "(equivalent to ASSUME_PROVIDED). Useful to make dependency "
228 "graphs more appealing")
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500229
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600230 parser.add_option("-l", "--log-domains", action="append", dest="debug_domains", default=[],
231 help="Show debug logging for the specified logging domains")
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500232
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600233 parser.add_option("-P", "--profile", action="store_true", dest="profile", default=False,
234 help="Profile the command and save reports.")
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500235
236 # @CHOICES@ is substituted out by BitbakeHelpFormatter above
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600237 parser.add_option("-u", "--ui", action="store", dest="ui",
238 default=os.environ.get('BITBAKE_UI', 'knotty'),
239 help="The user interface to use (@CHOICES@ - default %default).")
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500240
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600241 # @CHOICES@ is substituted out by BitbakeHelpFormatter above
242 parser.add_option("-t", "--servertype", action="store", dest="servertype",
243 default=["process", "xmlrpc"]["BBSERVER" in os.environ],
244 help="Choose which server type to use (@CHOICES@ - default %default).")
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500245
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600246 parser.add_option("", "--token", action="store", dest="xmlrpctoken",
247 default=os.environ.get("BBTOKEN"),
248 help="Specify the connection token to be used when connecting "
249 "to a remote server.")
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500250
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600251 parser.add_option("", "--revisions-changed", action="store_true",
252 dest="revisions_changed", default=False,
253 help="Set the exit code depending on whether upstream floating "
254 "revisions have changed or not.")
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500255
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600256 parser.add_option("", "--server-only", action="store_true",
257 dest="server_only", default=False,
258 help="Run bitbake without a UI, only starting a server "
259 "(cooker) process.")
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500260
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600261 parser.add_option("", "--foreground", action="store_true",
262 help="Run bitbake server in foreground.")
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500263
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600264 parser.add_option("-B", "--bind", action="store", dest="bind", default=False,
265 help="The name/address for the bitbake server to bind to.")
Patrick Williamsd8c66bc2016-06-20 12:57:21 -0500266
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600267 parser.add_option("-T", "--idle-timeout", type=int,
268 default=int(os.environ.get("BBTIMEOUT", "0")),
269 help="Set timeout to unload bitbake server due to inactivity")
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500270
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600271 parser.add_option("", "--no-setscene", action="store_true",
272 dest="nosetscene", default=False,
273 help="Do not run any setscene tasks. sstate will be ignored and "
274 "everything needed, built.")
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500275
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600276 parser.add_option("", "--setscene-only", action="store_true",
277 dest="setsceneonly", default=False,
278 help="Only run setscene tasks, don't run any real tasks.")
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500279
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600280 parser.add_option("", "--remote-server", action="store", dest="remote_server",
281 default=os.environ.get("BBSERVER"),
282 help="Connect to the specified server.")
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500283
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600284 parser.add_option("-m", "--kill-server", action="store_true",
285 dest="kill_server", default=False,
286 help="Terminate the remote server.")
287
288 parser.add_option("", "--observe-only", action="store_true",
289 dest="observe_only", default=False,
290 help="Connect to a server as an observing-only client.")
291
292 parser.add_option("", "--status-only", action="store_true",
293 dest="status_only", default=False,
294 help="Check the status of the remote bitbake server.")
295
296 parser.add_option("-w", "--write-log", action="store", dest="writeeventlog",
297 default=os.environ.get("BBEVENTLOG"),
298 help="Writes the event log of the build to a bitbake event json file. "
299 "Use '' (empty string) to assign the name automatically.")
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500300
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500301 parser.add_option("", "--runall", action="store", dest="runall",
302 help="Run the specified task for all build targets and their dependencies.")
303
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500304 options, targets = parser.parse_args(argv)
305
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600306 if options.quiet and options.verbose:
307 parser.error("options --quiet and --verbose are mutually exclusive")
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500308
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600309 if options.quiet and options.debug:
310 parser.error("options --quiet and --debug are mutually exclusive")
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500311
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600312 # use configuration files from environment variables
313 if "BBPRECONF" in os.environ:
314 options.prefile.append(os.environ["BBPRECONF"])
315
316 if "BBPOSTCONF" in os.environ:
317 options.postfile.append(os.environ["BBPOSTCONF"])
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500318
319 # fill in proper log name if not supplied
320 if options.writeeventlog is not None and len(options.writeeventlog) == 0:
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600321 from datetime import datetime
322 eventlog = "bitbake_eventlog_%s.json" % datetime.now().strftime("%Y%m%d%H%M%S")
323 options.writeeventlog = eventlog
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500324
325 # if BBSERVER says to autodetect, let's do that
326 if options.remote_server:
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600327 port = -1
328 if options.remote_server != 'autostart':
329 host, port = options.remote_server.split(":", 2)
330 port = int(port)
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500331 # use automatic port if port set to -1, means read it from
332 # the bitbake.lock file; this is a bit tricky, but we always expect
333 # to be in the base of the build directory if we need to have a
334 # chance to start the server later, anyway
335 if port == -1:
336 lock_location = "./bitbake.lock"
337 # we try to read the address at all times; if the server is not started,
338 # we'll try to start it after the first connect fails, below
339 try:
340 lf = open(lock_location, 'r')
341 remotedef = lf.readline()
342 [host, port] = remotedef.split(":")
343 port = int(port)
344 lf.close()
345 options.remote_server = remotedef
346 except Exception as e:
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600347 if options.remote_server != 'autostart':
348 raise BBMainException("Failed to read bitbake.lock (%s), invalid port" % str(e))
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500349
350 return options, targets[1:]
351
352
353def start_server(servermodule, configParams, configuration, features):
354 server = servermodule.BitBakeServer()
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600355 single_use = not configParams.server_only and os.getenv('BBSERVER') != 'autostart'
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500356 if configParams.bind:
357 (host, port) = configParams.bind.split(':')
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600358 server.initServer((host, int(port)), single_use=single_use,
359 idle_timeout=configParams.idle_timeout)
360 configuration.interface = [server.serverImpl.host, server.serverImpl.port]
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500361 else:
Patrick Williamsd8c66bc2016-06-20 12:57:21 -0500362 server.initServer(single_use=single_use)
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500363 configuration.interface = []
364
365 try:
366 configuration.setServerRegIdleCallback(server.getServerIdleCB())
367
368 cooker = bb.cooker.BBCooker(configuration, features)
369
370 server.addcooker(cooker)
371 server.saveConnectionDetails()
372 except Exception as e:
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500373 while hasattr(server, "event_queue"):
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600374 import queue
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500375 try:
376 event = server.event_queue.get(block=False)
377 except (queue.Empty, IOError):
378 break
379 if isinstance(event, logging.LogRecord):
380 logger.handle(event)
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600381 raise
382 if not configParams.foreground:
383 server.detach()
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500384 cooker.shutdown()
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500385 cooker.lock.close()
386 return server
387
388
389def bitbake_main(configParams, configuration):
390
391 # Python multiprocessing requires /dev/shm on Linux
392 if sys.platform.startswith('linux') and not os.access('/dev/shm', os.W_OK | os.X_OK):
393 raise BBMainException("FATAL: /dev/shm does not exist or is not writable")
394
395 # Unbuffer stdout to avoid log truncation in the event
396 # of an unorderly exit as well as to provide timely
397 # updates to log files for use with tail
398 try:
399 if sys.stdout.name == '<stdout>':
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600400 # Reopen with O_SYNC (unbuffered)
401 fl = fcntl.fcntl(sys.stdout.fileno(), fcntl.F_GETFL)
402 fl |= os.O_SYNC
403 fcntl.fcntl(sys.stdout.fileno(), fcntl.F_SETFL, fl)
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500404 except:
405 pass
406
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500407 configuration.setConfigParameters(configParams)
408
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500409 if configParams.server_only:
410 if configParams.servertype != "xmlrpc":
411 raise BBMainException("FATAL: If '--server-only' is defined, we must set the "
412 "servertype as 'xmlrpc'.\n")
413 if not configParams.bind:
414 raise BBMainException("FATAL: The '--server-only' option requires a name/address "
415 "to bind to with the -B option.\n")
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600416 else:
417 try:
418 #Checking that the port is a number
419 int(configParams.bind.split(":")[1])
420 except (ValueError,IndexError):
421 raise BBMainException(
422 "FATAL: Malformed host:port bind parameter")
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500423 if configParams.remote_server:
424 raise BBMainException("FATAL: The '--server-only' option conflicts with %s.\n" %
425 ("the BBSERVER environment variable" if "BBSERVER" in os.environ \
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600426 else "the '--remote-server' option"))
427
428 elif configParams.foreground:
429 raise BBMainException("FATAL: The '--foreground' option can only be used "
430 "with --server-only.\n")
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500431
432 if configParams.bind and configParams.servertype != "xmlrpc":
433 raise BBMainException("FATAL: If '-B' or '--bind' is defined, we must "
434 "set the servertype as 'xmlrpc'.\n")
435
436 if configParams.remote_server and configParams.servertype != "xmlrpc":
437 raise BBMainException("FATAL: If '--remote-server' is defined, we must "
438 "set the servertype as 'xmlrpc'.\n")
439
440 if configParams.observe_only and (not configParams.remote_server or configParams.bind):
441 raise BBMainException("FATAL: '--observe-only' can only be used by UI clients "
442 "connecting to a server.\n")
443
444 if configParams.kill_server and not configParams.remote_server:
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600445 raise BBMainException("FATAL: '--kill-server' can only be used to "
446 "terminate a remote server")
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500447
448 if "BBDEBUG" in os.environ:
449 level = int(os.environ["BBDEBUG"])
450 if level > configuration.debug:
451 configuration.debug = level
452
453 bb.msg.init_msgconfig(configParams.verbose, configuration.debug,
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600454 configuration.debug_domains)
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500455
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500456 server, server_connection, ui_module = setup_bitbake(configParams, configuration)
457 if server_connection is None and configParams.kill_server:
458 return 0
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500459
460 if not configParams.server_only:
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500461 if configParams.status_only:
462 server_connection.terminate()
463 return 0
464
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500465 try:
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600466 return ui_module.main(server_connection.connection, server_connection.events,
467 configParams)
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500468 finally:
469 bb.event.ui_queue = []
470 server_connection.terminate()
471 else:
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600472 print("Bitbake server address: %s, server port: %s" % (server.serverImpl.host,
473 server.serverImpl.port))
474 if configParams.foreground:
475 server.serverImpl.serve_forever()
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500476 return 0
477
478 return 1
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500479
480def setup_bitbake(configParams, configuration, extrafeatures=None):
481 # Ensure logging messages get sent to the UI as events
482 handler = bb.event.LogHandler()
483 if not configParams.status_only:
484 # In status only mode there are no logs and no UI
485 logger.addHandler(handler)
486
487 # Clear away any spurious environment variables while we stoke up the cooker
488 cleanedvars = bb.utils.clean_environment()
489
490 if configParams.server_only:
491 featureset = []
492 ui_module = None
493 else:
494 ui_module = import_extension_module(bb.ui, configParams.ui, 'main')
495 # Collect the feature set for the UI
496 featureset = getattr(ui_module, "featureSet", [])
497
498 if configParams.server_only:
499 for param in ('prefile', 'postfile'):
500 value = getattr(configParams, param)
501 if value:
502 setattr(configuration, "%s_server" % param, value)
503 param = "%s_server" % param
504
505 if extrafeatures:
506 for feature in extrafeatures:
507 if not feature in featureset:
508 featureset.append(feature)
509
510 servermodule = import_extension_module(bb.server,
511 configParams.servertype,
512 'BitBakeServer')
513 if configParams.remote_server:
514 if os.getenv('BBSERVER') == 'autostart':
515 if configParams.remote_server == 'autostart' or \
516 not servermodule.check_connection(configParams.remote_server, timeout=2):
517 configParams.bind = 'localhost:0'
518 srv = start_server(servermodule, configParams, configuration, featureset)
519 configParams.remote_server = '%s:%d' % tuple(configuration.interface)
520 bb.event.ui_queue = []
521 # we start a stub server that is actually a XMLRPClient that connects to a real server
522 from bb.server.xmlrpc import BitBakeXMLRPCClient
523 server = servermodule.BitBakeXMLRPCClient(configParams.observe_only,
524 configParams.xmlrpctoken)
525 server.saveConnectionDetails(configParams.remote_server)
526 else:
527 # we start a server with a given configuration
528 server = start_server(servermodule, configParams, configuration, featureset)
529 bb.event.ui_queue = []
530
531 if configParams.server_only:
532 server_connection = None
533 else:
534 try:
535 server_connection = server.establishConnection(featureset)
536 except Exception as e:
537 bb.fatal("Could not connect to server %s: %s" % (configParams.remote_server, str(e)))
538
539 if configParams.kill_server:
540 server_connection.connection.terminateServer()
541 bb.event.ui_queue = []
542 return None, None, None
543
544 server_connection.setupEventQueue()
545
546 # Restore the environment in case the UI needs it
547 for k in cleanedvars:
548 os.environ[k] = cleanedvars[k]
549
550 logger.removeHandler(handler)
551
552 return server, server_connection, ui_module