blob: a91e4fd15c54c187401d5d629b52bb4ffb05bca4 [file] [log] [blame]
Patrick Williamsc124f4f2015-09-15 14:41:29 -05001#
2# BitBake (No)TTY UI Implementation
3#
4# Handling output to TTYs or files (no TTY)
5#
6# Copyright (C) 2006-2012 Richard Purdie
7#
Brad Bishopc342db32019-05-15 21:57:59 -04008# SPDX-License-Identifier: GPL-2.0-only
Patrick Williamsc124f4f2015-09-15 14:41:29 -05009#
Patrick Williamsc124f4f2015-09-15 14:41:29 -050010
11from __future__ import division
12
13import os
14import sys
Patrick Williamsc124f4f2015-09-15 14:41:29 -050015import logging
16import progressbar
17import signal
18import bb.msg
19import time
20import fcntl
21import struct
22import copy
23import atexit
Patrick Williamsc0f7c042017-02-23 20:41:17 -060024
Patrick Williamsc124f4f2015-09-15 14:41:29 -050025from bb.ui import uihelper
26
27featureSet = [bb.cooker.CookerFeatures.SEND_SANITYEVENTS]
28
29logger = logging.getLogger("BitBake")
30interactive = sys.stdout.isatty()
31
32class BBProgress(progressbar.ProgressBar):
Patrick Williamsc0f7c042017-02-23 20:41:17 -060033 def __init__(self, msg, maxval, widgets=None, extrapos=-1, resize_handler=None):
Patrick Williamsc124f4f2015-09-15 14:41:29 -050034 self.msg = msg
Patrick Williamsc0f7c042017-02-23 20:41:17 -060035 self.extrapos = extrapos
36 if not widgets:
Andrew Geissler82c905d2020-04-13 13:39:40 -050037 widgets = [': ', progressbar.Percentage(), ' ', progressbar.Bar(),
38 ' ', progressbar.ETA()]
39 self.extrapos = 5
Patrick Williamsc124f4f2015-09-15 14:41:29 -050040
Patrick Williamsc0f7c042017-02-23 20:41:17 -060041 if resize_handler:
42 self._resize_default = resize_handler
43 else:
Patrick Williamsc124f4f2015-09-15 14:41:29 -050044 self._resize_default = signal.getsignal(signal.SIGWINCH)
Andrew Geissler82c905d2020-04-13 13:39:40 -050045 progressbar.ProgressBar.__init__(self, maxval, [self.msg] + widgets, fd=sys.stdout)
Patrick Williamsc124f4f2015-09-15 14:41:29 -050046
Patrick Williamsc0f7c042017-02-23 20:41:17 -060047 def _handle_resize(self, signum=None, frame=None):
Patrick Williamsc124f4f2015-09-15 14:41:29 -050048 progressbar.ProgressBar._handle_resize(self, signum, frame)
49 if self._resize_default:
50 self._resize_default(signum, frame)
Patrick Williamsc0f7c042017-02-23 20:41:17 -060051
Patrick Williamsc124f4f2015-09-15 14:41:29 -050052 def finish(self):
53 progressbar.ProgressBar.finish(self)
54 if self._resize_default:
55 signal.signal(signal.SIGWINCH, self._resize_default)
56
Patrick Williamsc0f7c042017-02-23 20:41:17 -060057 def setmessage(self, msg):
58 self.msg = msg
59 self.widgets[0] = msg
60
61 def setextra(self, extra):
62 if self.extrapos > -1:
63 if extra:
64 extrastr = str(extra)
65 if extrastr[0] != ' ':
66 extrastr = ' ' + extrastr
Patrick Williamsc0f7c042017-02-23 20:41:17 -060067 else:
Brad Bishop6e60e8b2018-02-01 10:27:11 -050068 extrastr = ''
Patrick Williamsc0f7c042017-02-23 20:41:17 -060069 self.widgets[self.extrapos] = extrastr
70
71 def _need_update(self):
72 # We always want the bar to print when update() is called
73 return True
74
Patrick Williamsc124f4f2015-09-15 14:41:29 -050075class NonInteractiveProgress(object):
76 fobj = sys.stdout
77
78 def __init__(self, msg, maxval):
79 self.msg = msg
80 self.maxval = maxval
Patrick Williamsc0f7c042017-02-23 20:41:17 -060081 self.finished = False
Patrick Williamsc124f4f2015-09-15 14:41:29 -050082
Patrick Williamsc0f7c042017-02-23 20:41:17 -060083 def start(self, update=True):
Patrick Williamsc124f4f2015-09-15 14:41:29 -050084 self.fobj.write("%s..." % self.msg)
85 self.fobj.flush()
86 return self
87
88 def update(self, value):
89 pass
90
91 def finish(self):
Patrick Williamsc0f7c042017-02-23 20:41:17 -060092 if self.finished:
93 return
Patrick Williamsc124f4f2015-09-15 14:41:29 -050094 self.fobj.write("done.\n")
95 self.fobj.flush()
Patrick Williamsc0f7c042017-02-23 20:41:17 -060096 self.finished = True
Patrick Williamsc124f4f2015-09-15 14:41:29 -050097
98def new_progress(msg, maxval):
99 if interactive:
100 return BBProgress(msg, maxval)
101 else:
102 return NonInteractiveProgress(msg, maxval)
103
104def pluralise(singular, plural, qty):
105 if(qty == 1):
106 return singular % qty
107 else:
108 return plural % qty
109
110
111class InteractConsoleLogFilter(logging.Filter):
Andrew Geissler82c905d2020-04-13 13:39:40 -0500112 def __init__(self, tf):
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500113 self.tf = tf
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500114
115 def filter(self, record):
Andrew Geissler82c905d2020-04-13 13:39:40 -0500116 if record.levelno == bb.msg.BBLogFormatter.NOTE and (record.msg.startswith("Running") or record.msg.startswith("recipe ")):
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500117 return False
118 self.tf.clearFooter()
119 return True
120
121class TerminalFilter(object):
Patrick Williamsd8c66bc2016-06-20 12:57:21 -0500122 rows = 25
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500123 columns = 80
124
125 def sigwinch_handle(self, signum, frame):
Patrick Williamsd8c66bc2016-06-20 12:57:21 -0500126 self.rows, self.columns = self.getTerminalColumns()
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500127 if self._sigwinch_default:
128 self._sigwinch_default(signum, frame)
129
130 def getTerminalColumns(self):
131 def ioctl_GWINSZ(fd):
132 try:
133 cr = struct.unpack('hh', fcntl.ioctl(fd, self.termios.TIOCGWINSZ, '1234'))
134 except:
135 return None
136 return cr
137 cr = ioctl_GWINSZ(sys.stdout.fileno())
138 if not cr:
139 try:
140 fd = os.open(os.ctermid(), os.O_RDONLY)
141 cr = ioctl_GWINSZ(fd)
142 os.close(fd)
143 except:
144 pass
145 if not cr:
146 try:
Andrew Geisslerc9f78652020-09-18 14:11:35 -0500147 cr = (os.environ['LINES'], os.environ['COLUMNS'])
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500148 except:
149 cr = (25, 80)
Patrick Williamsd8c66bc2016-06-20 12:57:21 -0500150 return cr
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500151
Andrew Geissler82c905d2020-04-13 13:39:40 -0500152 def __init__(self, main, helper, handlers, quiet):
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500153 self.main = main
154 self.helper = helper
155 self.cuu = None
156 self.stdinbackup = None
157 self.interactive = sys.stdout.isatty()
158 self.footer_present = False
159 self.lastpids = []
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600160 self.lasttime = None
161 self.quiet = quiet
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500162
163 if not self.interactive:
164 return
165
166 try:
167 import curses
168 except ImportError:
169 sys.exit("FATAL: The knotty ui could not load the required curses python module.")
170
171 import termios
172 self.curses = curses
173 self.termios = termios
174 try:
175 fd = sys.stdin.fileno()
176 self.stdinbackup = termios.tcgetattr(fd)
177 new = copy.deepcopy(self.stdinbackup)
178 new[3] = new[3] & ~termios.ECHO
179 termios.tcsetattr(fd, termios.TCSADRAIN, new)
180 curses.setupterm()
181 if curses.tigetnum("colors") > 2:
Andrew Geissler82c905d2020-04-13 13:39:40 -0500182 for h in handlers:
183 try:
184 h.formatter.enable_color()
185 except AttributeError:
186 pass
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500187 self.ed = curses.tigetstr("ed")
188 if self.ed:
189 self.cuu = curses.tigetstr("cuu")
190 try:
191 self._sigwinch_default = signal.getsignal(signal.SIGWINCH)
192 signal.signal(signal.SIGWINCH, self.sigwinch_handle)
193 except:
194 pass
Patrick Williamsd8c66bc2016-06-20 12:57:21 -0500195 self.rows, self.columns = self.getTerminalColumns()
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500196 except:
197 self.cuu = None
Patrick Williamsd8c66bc2016-06-20 12:57:21 -0500198 if not self.cuu:
199 self.interactive = False
200 bb.note("Unable to use interactive mode for this terminal, using fallback")
201 return
Andrew Geissler82c905d2020-04-13 13:39:40 -0500202
203 for h in handlers:
204 h.addFilter(InteractConsoleLogFilter(self))
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500205
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600206 self.main_progress = None
207
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500208 def clearFooter(self):
209 if self.footer_present:
210 lines = self.footer_present
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600211 sys.stdout.buffer.write(self.curses.tparm(self.cuu, lines))
212 sys.stdout.buffer.write(self.curses.tparm(self.ed))
213 sys.stdout.flush()
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500214 self.footer_present = False
215
Brad Bishopc342db32019-05-15 21:57:59 -0400216 def elapsed(self, sec):
217 hrs = int(sec / 3600.0)
218 sec -= hrs * 3600
219 min = int(sec / 60.0)
220 sec -= min * 60
221 if hrs > 0:
222 return "%dh%dm%ds" % (hrs, min, sec)
223 elif min > 0:
224 return "%dm%ds" % (min, sec)
225 else:
226 return "%ds" % (sec)
227
228 def keepAlive(self, t):
229 if not self.cuu:
230 print("Bitbake still alive (%ds)" % t)
231 sys.stdout.flush()
232
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500233 def updateFooter(self):
234 if not self.cuu:
235 return
236 activetasks = self.helper.running_tasks
237 failedtasks = self.helper.failed_tasks
238 runningpids = self.helper.running_pids
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600239 currenttime = time.time()
240 if not self.lasttime or (currenttime - self.lasttime > 5):
241 self.helper.needUpdate = True
242 self.lasttime = currenttime
243 if self.footer_present and not self.helper.needUpdate:
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500244 return
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600245 self.helper.needUpdate = False
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500246 if self.footer_present:
247 self.clearFooter()
248 if (not self.helper.tasknumber_total or self.helper.tasknumber_current == self.helper.tasknumber_total) and not len(activetasks):
249 return
250 tasks = []
251 for t in runningpids:
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600252 progress = activetasks[t].get("progress", None)
253 if progress is not None:
254 pbar = activetasks[t].get("progressbar", None)
255 rate = activetasks[t].get("rate", None)
256 start_time = activetasks[t].get("starttime", None)
257 if not pbar or pbar.bouncing != (progress < 0):
258 if progress < 0:
Andrew Geissler82c905d2020-04-13 13:39:40 -0500259 pbar = BBProgress("0: %s (pid %s)" % (activetasks[t]["title"], activetasks[t]["pid"]), 100, widgets=[' ', progressbar.BouncingSlider(), ''], extrapos=3, resize_handler=self.sigwinch_handle)
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600260 pbar.bouncing = True
261 else:
Andrew Geissler82c905d2020-04-13 13:39:40 -0500262 pbar = BBProgress("0: %s (pid %s)" % (activetasks[t]["title"], activetasks[t]["pid"]), 100, widgets=[' ', progressbar.Percentage(), ' ', progressbar.Bar(), ''], extrapos=5, resize_handler=self.sigwinch_handle)
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600263 pbar.bouncing = False
264 activetasks[t]["progressbar"] = pbar
265 tasks.append((pbar, progress, rate, start_time))
266 else:
267 start_time = activetasks[t].get("starttime", None)
268 if start_time:
Andrew Geissler82c905d2020-04-13 13:39:40 -0500269 tasks.append("%s - %s (pid %s)" % (activetasks[t]["title"], self.elapsed(currenttime - start_time), activetasks[t]["pid"]))
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600270 else:
Andrew Geissler82c905d2020-04-13 13:39:40 -0500271 tasks.append("%s (pid %s)" % (activetasks[t]["title"], activetasks[t]["pid"]))
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500272
273 if self.main.shutdown:
274 content = "Waiting for %s running tasks to finish:" % len(activetasks)
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500275 print(content)
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600276 else:
277 if self.quiet:
278 content = "Running tasks (%s of %s)" % (self.helper.tasknumber_current, self.helper.tasknumber_total)
279 elif not len(activetasks):
280 content = "No currently running tasks (%s of %s)" % (self.helper.tasknumber_current, self.helper.tasknumber_total)
281 else:
282 content = "Currently %2s running tasks (%s of %s)" % (len(activetasks), self.helper.tasknumber_current, self.helper.tasknumber_total)
283 maxtask = self.helper.tasknumber_total
284 if not self.main_progress or self.main_progress.maxval != maxtask:
285 widgets = [' ', progressbar.Percentage(), ' ', progressbar.Bar()]
286 self.main_progress = BBProgress("Running tasks", maxtask, widgets=widgets, resize_handler=self.sigwinch_handle)
287 self.main_progress.start(False)
288 self.main_progress.setmessage(content)
289 progress = self.helper.tasknumber_current - 1
290 if progress < 0:
291 progress = 0
292 content = self.main_progress.update(progress)
293 print('')
294 lines = 1 + int(len(content) / (self.columns + 1))
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500295 if self.quiet == 0:
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600296 for tasknum, task in enumerate(tasks[:(self.rows - 2)]):
297 if isinstance(task, tuple):
298 pbar, progress, rate, start_time = task
299 if not pbar.start_time:
300 pbar.start(False)
301 if start_time:
302 pbar.start_time = start_time
303 pbar.setmessage('%s:%s' % (tasknum, pbar.msg.split(':', 1)[1]))
Brad Bishop15ae2502019-06-18 21:44:24 -0400304 pbar.setextra(rate)
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600305 if progress > -1:
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600306 content = pbar.update(progress)
307 else:
308 content = pbar.update(1)
309 print('')
310 else:
311 content = "%s: %s" % (tasknum, task)
312 print(content)
313 lines = lines + 1 + int(len(content) / (self.columns + 1))
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500314 self.footer_present = lines
315 self.lastpids = runningpids[:]
316 self.lastcount = self.helper.tasknumber_current
317
318 def finish(self):
319 if self.stdinbackup:
320 fd = sys.stdin.fileno()
321 self.termios.tcsetattr(fd, self.termios.TCSADRAIN, self.stdinbackup)
322
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500323def print_event_log(event, includelogs, loglines, termfilter):
324 # FIXME refactor this out further
325 logfile = event.logfile
326 if logfile and os.path.exists(logfile):
327 termfilter.clearFooter()
328 bb.error("Logfile of failure stored in: %s" % logfile)
329 if includelogs and not event.errprinted:
330 print("Log data follows:")
331 f = open(logfile, "r")
332 lines = []
333 while True:
334 l = f.readline()
335 if l == '':
336 break
337 l = l.rstrip()
338 if loglines:
339 lines.append(' | %s' % l)
340 if len(lines) > int(loglines):
341 lines.pop(0)
342 else:
343 print('| %s' % l)
344 f.close()
345 if lines:
346 for line in lines:
347 print(line)
348
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500349def _log_settings_from_server(server, observe_only):
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500350 # Get values of variables which control our output
351 includelogs, error = server.runCommand(["getVariable", "BBINCLUDELOGS"])
352 if error:
353 logger.error("Unable to get the value of BBINCLUDELOGS variable: %s" % error)
354 raise BaseException(error)
355 loglines, error = server.runCommand(["getVariable", "BBINCLUDELOGS_LINES"])
356 if error:
357 logger.error("Unable to get the value of BBINCLUDELOGS_LINES variable: %s" % error)
358 raise BaseException(error)
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500359 if observe_only:
360 cmd = 'getVariable'
361 else:
362 cmd = 'getSetVariable'
363 consolelogfile, error = server.runCommand([cmd, "BB_CONSOLELOG"])
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500364 if error:
365 logger.error("Unable to get the value of BB_CONSOLELOG variable: %s" % error)
366 raise BaseException(error)
Andrew Geissler82c905d2020-04-13 13:39:40 -0500367 logconfigfile, error = server.runCommand([cmd, "BB_LOGCONFIG"])
368 if error:
369 logger.error("Unable to get the value of BB_LOGCONFIG variable: %s" % error)
370 raise BaseException(error)
371 return includelogs, loglines, consolelogfile, logconfigfile
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500372
373_evt_list = [ "bb.runqueue.runQueueExitWait", "bb.event.LogExecTTY", "logging.LogRecord",
374 "bb.build.TaskFailed", "bb.build.TaskBase", "bb.event.ParseStarted",
375 "bb.event.ParseProgress", "bb.event.ParseCompleted", "bb.event.CacheLoadStarted",
376 "bb.event.CacheLoadProgress", "bb.event.CacheLoadCompleted", "bb.command.CommandFailed",
377 "bb.command.CommandExit", "bb.command.CommandCompleted", "bb.cooker.CookerExit",
378 "bb.event.MultipleProviders", "bb.event.NoProvider", "bb.runqueue.sceneQueueTaskStarted",
379 "bb.runqueue.runQueueTaskStarted", "bb.runqueue.runQueueTaskFailed", "bb.runqueue.sceneQueueTaskFailed",
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600380 "bb.event.BuildBase", "bb.build.TaskStarted", "bb.build.TaskSucceeded", "bb.build.TaskFailedSilent",
381 "bb.build.TaskProgress", "bb.event.ProcessStarted", "bb.event.ProcessProgress", "bb.event.ProcessFinished"]
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500382
Andrew Geisslerc9f78652020-09-18 14:11:35 -0500383def drain_events_errorhandling(eventHandler):
384 # We don't have logging setup, we do need to show any events we see before exiting
385 event = True
386 logger = bb.msg.logger_create('bitbake', sys.stdout)
387 while event:
388 event = eventHandler.waitEvent(0)
389 if isinstance(event, logging.LogRecord):
390 logger.handle(event)
391
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500392def main(server, eventHandler, params, tf = TerminalFilter):
393
Andrew Geisslerc9f78652020-09-18 14:11:35 -0500394 try:
395 if not params.observe_only:
396 params.updateToServer(server, os.environ.copy())
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500397
Andrew Geisslerc9f78652020-09-18 14:11:35 -0500398 includelogs, loglines, consolelogfile, logconfigfile = _log_settings_from_server(server, params.observe_only)
Andrew Geissler82c905d2020-04-13 13:39:40 -0500399
Andrew Geisslerc9f78652020-09-18 14:11:35 -0500400 loglevel, _ = bb.msg.constructLogOptions()
401 except bb.BBHandledException:
402 drain_events_errorhandling(eventHandler)
403 return 1
Andrew Geissler82c905d2020-04-13 13:39:40 -0500404
405 if params.options.quiet == 0:
406 console_loglevel = loglevel
407 elif params.options.quiet > 2:
408 console_loglevel = bb.msg.BBLogFormatter.ERROR
409 else:
410 console_loglevel = bb.msg.BBLogFormatter.WARNING
411
412 logconfig = {
413 "version": 1,
414 "handlers": {
415 "BitBake.console": {
416 "class": "logging.StreamHandler",
417 "formatter": "BitBake.consoleFormatter",
418 "level": console_loglevel,
419 "stream": "ext://sys.stdout",
420 "filters": ["BitBake.stdoutFilter"],
421 ".": {
422 "is_console": True,
423 },
424 },
425 "BitBake.errconsole": {
426 "class": "logging.StreamHandler",
427 "formatter": "BitBake.consoleFormatter",
428 "level": loglevel,
429 "stream": "ext://sys.stderr",
430 "filters": ["BitBake.stderrFilter"],
431 ".": {
432 "is_console": True,
433 },
434 },
435 # This handler can be used if specific loggers should print on
436 # the console at a lower severity than the default. It will
437 # display any messages sent to it that are lower than then
438 # BitBake.console logging level (so as to prevent duplication of
439 # messages). Nothing is attached to this handler by default
440 "BitBake.verbconsole": {
441 "class": "logging.StreamHandler",
442 "formatter": "BitBake.consoleFormatter",
443 "level": 1,
444 "stream": "ext://sys.stdout",
445 "filters": ["BitBake.verbconsoleFilter"],
446 ".": {
447 "is_console": True,
448 },
449 },
450 },
451 "formatters": {
452 # This format instance will get color output enabled by the
453 # terminal
454 "BitBake.consoleFormatter" : {
455 "()": "bb.msg.BBLogFormatter",
456 "format": "%(levelname)s: %(message)s"
457 },
458 # The file log requires a separate instance so that it doesn't get
459 # color enabled
460 "BitBake.logfileFormatter": {
461 "()": "bb.msg.BBLogFormatter",
462 "format": "%(levelname)s: %(message)s"
463 }
464 },
465 "filters": {
466 "BitBake.stdoutFilter": {
467 "()": "bb.msg.LogFilterLTLevel",
468 "level": "ERROR"
469 },
470 "BitBake.stderrFilter": {
471 "()": "bb.msg.LogFilterGEQLevel",
472 "level": "ERROR"
473 },
474 "BitBake.verbconsoleFilter": {
475 "()": "bb.msg.LogFilterLTLevel",
476 "level": console_loglevel
477 },
478 },
479 "loggers": {
480 "BitBake": {
481 "level": loglevel,
482 "handlers": ["BitBake.console", "BitBake.errconsole"],
483 }
484 },
485 "disable_existing_loggers": False
486 }
487
488 # Enable the console log file if enabled
489 if consolelogfile and not params.options.show_environment and not params.options.show_versions:
490 logconfig = bb.msg.mergeLoggingConfig(logconfig, {
491 "version": 1,
492 "handlers" : {
493 "BitBake.consolelog": {
494 "class": "logging.FileHandler",
495 "formatter": "BitBake.logfileFormatter",
496 "level": loglevel,
497 "filename": consolelogfile,
498 },
499 # Just like verbconsole, anything sent here will go to the
500 # log file, unless it would go to BitBake.consolelog
501 "BitBake.verbconsolelog" : {
502 "class": "logging.FileHandler",
503 "formatter": "BitBake.logfileFormatter",
504 "level": 1,
505 "filename": consolelogfile,
506 "filters": ["BitBake.verbconsolelogFilter"],
507 },
508 },
509 "filters": {
510 "BitBake.verbconsolelogFilter": {
511 "()": "bb.msg.LogFilterLTLevel",
512 "level": loglevel,
513 },
514 },
515 "loggers": {
516 "BitBake": {
517 "handlers": ["BitBake.consolelog"],
518 },
519
520 # Other interesting things that we want to keep an eye on
521 # in the log files in case someone has an issue, but not
522 # necessarily show to the user on the console
523 "BitBake.SigGen.HashEquiv": {
524 "level": "VERBOSE",
525 "handlers": ["BitBake.verbconsolelog"],
526 },
527 "BitBake.RunQueue.HashEquiv": {
528 "level": "VERBOSE",
529 "handlers": ["BitBake.verbconsolelog"],
530 }
531 }
532 })
533
534 bb.utils.mkdirhier(os.path.dirname(consolelogfile))
535 loglink = os.path.join(os.path.dirname(consolelogfile), 'console-latest.log')
536 bb.utils.remove(loglink)
537 try:
538 os.symlink(os.path.basename(consolelogfile), loglink)
539 except OSError:
540 pass
541
542 conf = bb.msg.setLoggingConfig(logconfig, logconfigfile)
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500543
544 if sys.stdin.isatty() and sys.stdout.isatty():
545 log_exec_tty = True
546 else:
547 log_exec_tty = False
548
549 helper = uihelper.BBUIHelper()
550
Andrew Geissler82c905d2020-04-13 13:39:40 -0500551 # Look for the specially designated handlers which need to be passed to the
552 # terminal handler
553 console_handlers = [h for h in conf.config['handlers'].values() if getattr(h, 'is_console', False)]
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500554
Patrick Williamsd8c66bc2016-06-20 12:57:21 -0500555 bb.utils.set_process_name("KnottyUI")
556
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500557 if params.options.remote_server and params.options.kill_server:
558 server.terminateServer()
559 return
560
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500561 llevel, debug_domains = bb.msg.constructLogOptions()
562 server.runCommand(["setEventMask", server.getEventHandle(), llevel, debug_domains, _evt_list])
563
Andrew Geissler82c905d2020-04-13 13:39:40 -0500564 # The logging_tree module is *extremely* helpful in debugging logging
565 # domains. Uncomment here to dump the logging tree when bitbake starts
566 #import logging_tree
567 #logging_tree.printout()
568
Patrick Williamsd8c66bc2016-06-20 12:57:21 -0500569 universe = False
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500570 if not params.observe_only:
571 params.updateFromServer(server)
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500572 cmdline = params.parseActions()
573 if not cmdline:
574 print("Nothing to do. Use 'bitbake world' to build everything, or run 'bitbake --help' for usage information.")
575 return 1
576 if 'msg' in cmdline and cmdline['msg']:
577 logger.error(cmdline['msg'])
578 return 1
Patrick Williamsd8c66bc2016-06-20 12:57:21 -0500579 if cmdline['action'][0] == "buildTargets" and "universe" in cmdline['action'][1]:
580 universe = True
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500581
582 ret, error = server.runCommand(cmdline['action'])
583 if error:
584 logger.error("Command '%s' failed: %s" % (cmdline, error))
585 return 1
Andrew Geissler82c905d2020-04-13 13:39:40 -0500586 elif not ret:
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500587 logger.error("Command '%s' failed: returned %s" % (cmdline, ret))
588 return 1
589
590
591 parseprogress = None
592 cacheprogress = None
593 main.shutdown = 0
594 interrupted = False
595 return_value = 0
596 errors = 0
597 warnings = 0
598 taskfailures = []
599
Brad Bishopc342db32019-05-15 21:57:59 -0400600 printinterval = 5000
601 lastprint = time.time()
602
Andrew Geissler82c905d2020-04-13 13:39:40 -0500603 termfilter = tf(main, helper, console_handlers, params.options.quiet)
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500604 atexit.register(termfilter.finish)
605
606 while True:
607 try:
Brad Bishopc342db32019-05-15 21:57:59 -0400608 if (lastprint + printinterval) <= time.time():
609 termfilter.keepAlive(printinterval)
610 printinterval += 5000
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500611 event = eventHandler.waitEvent(0)
612 if event is None:
613 if main.shutdown > 1:
614 break
Andrew Geissler82c905d2020-04-13 13:39:40 -0500615 if not parseprogress:
616 termfilter.updateFooter()
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500617 event = eventHandler.waitEvent(0.25)
618 if event is None:
619 continue
620 helper.eventHandler(event)
621 if isinstance(event, bb.runqueue.runQueueExitWait):
622 if not main.shutdown:
623 main.shutdown = 1
624 continue
625 if isinstance(event, bb.event.LogExecTTY):
626 if log_exec_tty:
627 tries = event.retries
628 while tries:
629 print("Trying to run: %s" % event.prog)
630 if os.system(event.prog) == 0:
631 break
632 time.sleep(event.sleep_delay)
633 tries -= 1
634 if tries:
635 continue
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600636 logger.warning(event.msg)
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500637 continue
638
639 if isinstance(event, logging.LogRecord):
Brad Bishopc342db32019-05-15 21:57:59 -0400640 lastprint = time.time()
641 printinterval = 5000
Andrew Geissler82c905d2020-04-13 13:39:40 -0500642 if event.levelno >= bb.msg.BBLogFormatter.ERROR:
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500643 errors = errors + 1
644 return_value = 1
Andrew Geissler82c905d2020-04-13 13:39:40 -0500645 elif event.levelno == bb.msg.BBLogFormatter.WARNING:
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500646 warnings = warnings + 1
Patrick Williamsd8c66bc2016-06-20 12:57:21 -0500647
648 if event.taskpid != 0:
649 # For "normal" logging conditions, don't show note logs from tasks
650 # but do show them if the user has changed the default log level to
651 # include verbose/debug messages
Andrew Geissler82c905d2020-04-13 13:39:40 -0500652 if event.levelno <= bb.msg.BBLogFormatter.NOTE and (event.levelno < llevel or (event.levelno == bb.msg.BBLogFormatter.NOTE and llevel != bb.msg.BBLogFormatter.VERBOSE)):
Patrick Williamsd8c66bc2016-06-20 12:57:21 -0500653 continue
654
655 # Prefix task messages with recipe/task
Andrew Geissler82c905d2020-04-13 13:39:40 -0500656 if event.taskpid in helper.pidmap and event.levelno != bb.msg.BBLogFormatter.PLAIN:
657 taskinfo = helper.running_tasks[helper.pidmap[event.taskpid]]
Patrick Williamsd8c66bc2016-06-20 12:57:21 -0500658 event.msg = taskinfo['title'] + ': ' + event.msg
659 if hasattr(event, 'fn'):
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500660 event.msg = event.fn + ': ' + event.msg
Andrew Geissler82c905d2020-04-13 13:39:40 -0500661 logging.getLogger(event.name).handle(event)
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500662 continue
663
664 if isinstance(event, bb.build.TaskFailedSilent):
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600665 logger.warning("Logfile for failed setscene task is %s" % event.logfile)
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500666 continue
667 if isinstance(event, bb.build.TaskFailed):
668 return_value = 1
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500669 print_event_log(event, includelogs, loglines, termfilter)
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500670 if isinstance(event, bb.build.TaskBase):
671 logger.info(event._message)
672 continue
673 if isinstance(event, bb.event.ParseStarted):
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500674 if params.options.quiet > 1:
675 continue
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500676 if event.total == 0:
677 continue
Andrew Geissler82c905d2020-04-13 13:39:40 -0500678 termfilter.clearFooter()
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500679 parseprogress = new_progress("Parsing recipes", event.total).start()
680 continue
681 if isinstance(event, bb.event.ParseProgress):
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500682 if params.options.quiet > 1:
683 continue
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600684 if parseprogress:
685 parseprogress.update(event.current)
686 else:
687 bb.warn("Got ParseProgress event for parsing that never started?")
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500688 continue
689 if isinstance(event, bb.event.ParseCompleted):
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500690 if params.options.quiet > 1:
691 continue
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500692 if not parseprogress:
693 continue
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500694 parseprogress.finish()
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600695 pasreprogress = None
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500696 if params.options.quiet == 0:
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600697 print(("Parsing of %d .bb files complete (%d cached, %d parsed). %d targets, %d skipped, %d masked, %d errors."
698 % ( event.total, event.cached, event.parsed, event.virtuals, event.skipped, event.masked, event.errors)))
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500699 continue
700
701 if isinstance(event, bb.event.CacheLoadStarted):
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500702 if params.options.quiet > 1:
703 continue
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500704 cacheprogress = new_progress("Loading cache", event.total).start()
705 continue
706 if isinstance(event, bb.event.CacheLoadProgress):
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500707 if params.options.quiet > 1:
708 continue
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500709 cacheprogress.update(event.current)
710 continue
711 if isinstance(event, bb.event.CacheLoadCompleted):
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500712 if params.options.quiet > 1:
713 continue
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500714 cacheprogress.finish()
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500715 if params.options.quiet == 0:
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600716 print("Loaded %d entries from dependency cache." % event.num_entries)
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500717 continue
718
719 if isinstance(event, bb.command.CommandFailed):
720 return_value = event.exitcode
721 if event.error:
722 errors = errors + 1
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500723 logger.error(str(event))
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500724 main.shutdown = 2
725 continue
726 if isinstance(event, bb.command.CommandExit):
727 if not return_value:
728 return_value = event.exitcode
Andrew Geissler82c905d2020-04-13 13:39:40 -0500729 main.shutdown = 2
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500730 continue
731 if isinstance(event, (bb.command.CommandCompleted, bb.cooker.CookerExit)):
732 main.shutdown = 2
733 continue
734 if isinstance(event, bb.event.MultipleProviders):
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500735 logger.info(str(event))
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500736 continue
737 if isinstance(event, bb.event.NoProvider):
Patrick Williamsd8c66bc2016-06-20 12:57:21 -0500738 # For universe builds, only show these as warnings, not errors
Patrick Williamsd8c66bc2016-06-20 12:57:21 -0500739 if not universe:
740 return_value = 1
741 errors = errors + 1
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500742 logger.error(str(event))
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500743 else:
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500744 logger.warning(str(event))
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500745 continue
746
747 if isinstance(event, bb.runqueue.sceneQueueTaskStarted):
748 logger.info("Running setscene task %d of %d (%s)" % (event.stats.completed + event.stats.active + event.stats.failed + 1, event.stats.total, event.taskstring))
749 continue
750
751 if isinstance(event, bb.runqueue.runQueueTaskStarted):
752 if event.noexec:
753 tasktype = 'noexec task'
754 else:
755 tasktype = 'task'
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600756 logger.info("Running %s %d of %d (%s)",
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500757 tasktype,
758 event.stats.completed + event.stats.active +
759 event.stats.failed + 1,
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600760 event.stats.total, event.taskstring)
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500761 continue
762
763 if isinstance(event, bb.runqueue.runQueueTaskFailed):
Patrick Williamsd8c66bc2016-06-20 12:57:21 -0500764 return_value = 1
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500765 taskfailures.append(event.taskstring)
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500766 logger.error(str(event))
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500767 continue
768
769 if isinstance(event, bb.runqueue.sceneQueueTaskFailed):
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500770 logger.warning(str(event))
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500771 continue
772
773 if isinstance(event, bb.event.DepTreeGenerated):
774 continue
775
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600776 if isinstance(event, bb.event.ProcessStarted):
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500777 if params.options.quiet > 1:
778 continue
Andrew Geissler82c905d2020-04-13 13:39:40 -0500779 termfilter.clearFooter()
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600780 parseprogress = new_progress(event.processname, event.total)
781 parseprogress.start(False)
782 continue
783 if isinstance(event, bb.event.ProcessProgress):
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500784 if params.options.quiet > 1:
785 continue
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600786 if parseprogress:
787 parseprogress.update(event.progress)
788 else:
789 bb.warn("Got ProcessProgress event for someting that never started?")
790 continue
791 if isinstance(event, bb.event.ProcessFinished):
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500792 if params.options.quiet > 1:
793 continue
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600794 if parseprogress:
795 parseprogress.finish()
796 parseprogress = None
797 continue
798
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500799 # ignore
800 if isinstance(event, (bb.event.BuildBase,
801 bb.event.MetadataEvent,
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500802 bb.event.ConfigParsed,
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500803 bb.event.MultiConfigParsed,
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500804 bb.event.RecipeParsed,
805 bb.event.RecipePreFinalise,
806 bb.runqueue.runQueueEvent,
807 bb.event.OperationStarted,
808 bb.event.OperationCompleted,
809 bb.event.OperationProgress,
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600810 bb.event.DiskFull,
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500811 bb.event.HeartbeatEvent,
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600812 bb.build.TaskProgress)):
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500813 continue
814
815 logger.error("Unknown event: %s", event)
816
817 except EnvironmentError as ioerror:
818 termfilter.clearFooter()
819 # ignore interrupted io
820 if ioerror.args[0] == 4:
821 continue
822 sys.stderr.write(str(ioerror))
823 if not params.observe_only:
824 _, error = server.runCommand(["stateForceShutdown"])
825 main.shutdown = 2
826 except KeyboardInterrupt:
827 termfilter.clearFooter()
828 if params.observe_only:
829 print("\nKeyboard Interrupt, exiting observer...")
830 main.shutdown = 2
Brad Bishop08902b02019-08-20 09:16:51 -0400831
832 def state_force_shutdown():
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500833 print("\nSecond Keyboard Interrupt, stopping...\n")
834 _, error = server.runCommand(["stateForceShutdown"])
835 if error:
836 logger.error("Unable to cleanly stop: %s" % error)
Brad Bishop08902b02019-08-20 09:16:51 -0400837
838 if not params.observe_only and main.shutdown == 1:
839 state_force_shutdown()
840
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500841 if not params.observe_only and main.shutdown == 0:
842 print("\nKeyboard Interrupt, closing down...\n")
843 interrupted = True
Brad Bishop08902b02019-08-20 09:16:51 -0400844 # Capture the second KeyboardInterrupt during stateShutdown is running
845 try:
846 _, error = server.runCommand(["stateShutdown"])
847 if error:
848 logger.error("Unable to cleanly shutdown: %s" % error)
849 except KeyboardInterrupt:
850 state_force_shutdown()
851
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500852 main.shutdown = main.shutdown + 1
853 pass
854 except Exception as e:
Patrick Williamsd8c66bc2016-06-20 12:57:21 -0500855 import traceback
856 sys.stderr.write(traceback.format_exc())
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500857 if not params.observe_only:
858 _, error = server.runCommand(["stateForceShutdown"])
859 main.shutdown = 2
Patrick Williamsd8c66bc2016-06-20 12:57:21 -0500860 return_value = 1
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500861 try:
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600862 termfilter.clearFooter()
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500863 summary = ""
864 if taskfailures:
865 summary += pluralise("\nSummary: %s task failed:",
866 "\nSummary: %s tasks failed:", len(taskfailures))
867 for failure in taskfailures:
868 summary += "\n %s" % failure
869 if warnings:
870 summary += pluralise("\nSummary: There was %s WARNING message shown.",
871 "\nSummary: There were %s WARNING messages shown.", warnings)
872 if return_value and errors:
873 summary += pluralise("\nSummary: There was %s ERROR message shown, returning a non-zero exit code.",
874 "\nSummary: There were %s ERROR messages shown, returning a non-zero exit code.", errors)
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500875 if summary and params.options.quiet == 0:
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500876 print(summary)
877
878 if interrupted:
879 print("Execution was interrupted, returning a non-zero exit code.")
880 if return_value == 0:
881 return_value = 1
882 except IOError as e:
883 import errno
884 if e.errno == errno.EPIPE:
885 pass
886
Andrew Geissler82c905d2020-04-13 13:39:40 -0500887 logging.shutdown()
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600888
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500889 return return_value