blob: 431baa15efea3b8f895c31cd0b4cdb6c09e3e936 [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
Andrew Geisslerc926e172021-05-07 16:11:35 -050024from itertools import groupby
Patrick Williamsc0f7c042017-02-23 20:41:17 -060025
Patrick Williamsc124f4f2015-09-15 14:41:29 -050026from bb.ui import uihelper
27
Andrew Geissler7e0e3c02022-02-25 20:34:39 +000028featureSet = [bb.cooker.CookerFeatures.SEND_SANITYEVENTS, bb.cooker.CookerFeatures.BASEDATASTORE_TRACKING]
Patrick Williamsc124f4f2015-09-15 14:41:29 -050029
30logger = logging.getLogger("BitBake")
31interactive = sys.stdout.isatty()
32
33class BBProgress(progressbar.ProgressBar):
Patrick Williamsc0f7c042017-02-23 20:41:17 -060034 def __init__(self, msg, maxval, widgets=None, extrapos=-1, resize_handler=None):
Patrick Williamsc124f4f2015-09-15 14:41:29 -050035 self.msg = msg
Patrick Williamsc0f7c042017-02-23 20:41:17 -060036 self.extrapos = extrapos
37 if not widgets:
Andrew Geissler82c905d2020-04-13 13:39:40 -050038 widgets = [': ', progressbar.Percentage(), ' ', progressbar.Bar(),
39 ' ', progressbar.ETA()]
40 self.extrapos = 5
Patrick Williamsc124f4f2015-09-15 14:41:29 -050041
Patrick Williamsc0f7c042017-02-23 20:41:17 -060042 if resize_handler:
43 self._resize_default = resize_handler
44 else:
Patrick Williamsc124f4f2015-09-15 14:41:29 -050045 self._resize_default = signal.getsignal(signal.SIGWINCH)
Andrew Geissler82c905d2020-04-13 13:39:40 -050046 progressbar.ProgressBar.__init__(self, maxval, [self.msg] + widgets, fd=sys.stdout)
Patrick Williamsc124f4f2015-09-15 14:41:29 -050047
Patrick Williamsc0f7c042017-02-23 20:41:17 -060048 def _handle_resize(self, signum=None, frame=None):
Patrick Williamsc124f4f2015-09-15 14:41:29 -050049 progressbar.ProgressBar._handle_resize(self, signum, frame)
50 if self._resize_default:
51 self._resize_default(signum, frame)
Patrick Williamsc0f7c042017-02-23 20:41:17 -060052
Patrick Williamsc124f4f2015-09-15 14:41:29 -050053 def finish(self):
54 progressbar.ProgressBar.finish(self)
55 if self._resize_default:
56 signal.signal(signal.SIGWINCH, self._resize_default)
57
Patrick Williamsc0f7c042017-02-23 20:41:17 -060058 def setmessage(self, msg):
59 self.msg = msg
60 self.widgets[0] = msg
61
62 def setextra(self, extra):
63 if self.extrapos > -1:
64 if extra:
65 extrastr = str(extra)
66 if extrastr[0] != ' ':
67 extrastr = ' ' + extrastr
Patrick Williamsc0f7c042017-02-23 20:41:17 -060068 else:
Brad Bishop6e60e8b2018-02-01 10:27:11 -050069 extrastr = ''
Patrick Williamsc0f7c042017-02-23 20:41:17 -060070 self.widgets[self.extrapos] = extrastr
71
72 def _need_update(self):
73 # We always want the bar to print when update() is called
74 return True
75
Patrick Williamsc124f4f2015-09-15 14:41:29 -050076class NonInteractiveProgress(object):
77 fobj = sys.stdout
78
79 def __init__(self, msg, maxval):
80 self.msg = msg
81 self.maxval = maxval
Patrick Williamsc0f7c042017-02-23 20:41:17 -060082 self.finished = False
Patrick Williamsc124f4f2015-09-15 14:41:29 -050083
Patrick Williamsc0f7c042017-02-23 20:41:17 -060084 def start(self, update=True):
Patrick Williamsc124f4f2015-09-15 14:41:29 -050085 self.fobj.write("%s..." % self.msg)
86 self.fobj.flush()
87 return self
88
89 def update(self, value):
90 pass
91
92 def finish(self):
Patrick Williamsc0f7c042017-02-23 20:41:17 -060093 if self.finished:
94 return
Patrick Williamsc124f4f2015-09-15 14:41:29 -050095 self.fobj.write("done.\n")
96 self.fobj.flush()
Patrick Williamsc0f7c042017-02-23 20:41:17 -060097 self.finished = True
Patrick Williamsc124f4f2015-09-15 14:41:29 -050098
99def new_progress(msg, maxval):
100 if interactive:
101 return BBProgress(msg, maxval)
102 else:
103 return NonInteractiveProgress(msg, maxval)
104
105def pluralise(singular, plural, qty):
106 if(qty == 1):
107 return singular % qty
108 else:
109 return plural % qty
110
111
112class InteractConsoleLogFilter(logging.Filter):
Andrew Geissler82c905d2020-04-13 13:39:40 -0500113 def __init__(self, tf):
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500114 self.tf = tf
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500115
116 def filter(self, record):
Andrew Geissler82c905d2020-04-13 13:39:40 -0500117 if record.levelno == bb.msg.BBLogFormatter.NOTE and (record.msg.startswith("Running") or record.msg.startswith("recipe ")):
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500118 return False
119 self.tf.clearFooter()
120 return True
121
122class TerminalFilter(object):
Patrick Williamsd8c66bc2016-06-20 12:57:21 -0500123 rows = 25
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500124 columns = 80
125
126 def sigwinch_handle(self, signum, frame):
Patrick Williamsd8c66bc2016-06-20 12:57:21 -0500127 self.rows, self.columns = self.getTerminalColumns()
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500128 if self._sigwinch_default:
129 self._sigwinch_default(signum, frame)
130
131 def getTerminalColumns(self):
132 def ioctl_GWINSZ(fd):
133 try:
134 cr = struct.unpack('hh', fcntl.ioctl(fd, self.termios.TIOCGWINSZ, '1234'))
135 except:
136 return None
137 return cr
138 cr = ioctl_GWINSZ(sys.stdout.fileno())
139 if not cr:
140 try:
141 fd = os.open(os.ctermid(), os.O_RDONLY)
142 cr = ioctl_GWINSZ(fd)
143 os.close(fd)
144 except:
145 pass
146 if not cr:
147 try:
Andrew Geisslerc9f78652020-09-18 14:11:35 -0500148 cr = (os.environ['LINES'], os.environ['COLUMNS'])
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500149 except:
150 cr = (25, 80)
Patrick Williamsd8c66bc2016-06-20 12:57:21 -0500151 return cr
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500152
Andrew Geissler82c905d2020-04-13 13:39:40 -0500153 def __init__(self, main, helper, handlers, quiet):
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500154 self.main = main
155 self.helper = helper
156 self.cuu = None
157 self.stdinbackup = None
158 self.interactive = sys.stdout.isatty()
159 self.footer_present = False
160 self.lastpids = []
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600161 self.lasttime = None
162 self.quiet = quiet
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500163
164 if not self.interactive:
165 return
166
167 try:
168 import curses
169 except ImportError:
170 sys.exit("FATAL: The knotty ui could not load the required curses python module.")
171
172 import termios
173 self.curses = curses
174 self.termios = termios
175 try:
176 fd = sys.stdin.fileno()
177 self.stdinbackup = termios.tcgetattr(fd)
178 new = copy.deepcopy(self.stdinbackup)
179 new[3] = new[3] & ~termios.ECHO
180 termios.tcsetattr(fd, termios.TCSADRAIN, new)
181 curses.setupterm()
182 if curses.tigetnum("colors") > 2:
Andrew Geissler82c905d2020-04-13 13:39:40 -0500183 for h in handlers:
184 try:
185 h.formatter.enable_color()
186 except AttributeError:
187 pass
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500188 self.ed = curses.tigetstr("ed")
189 if self.ed:
190 self.cuu = curses.tigetstr("cuu")
191 try:
192 self._sigwinch_default = signal.getsignal(signal.SIGWINCH)
193 signal.signal(signal.SIGWINCH, self.sigwinch_handle)
194 except:
195 pass
Patrick Williamsd8c66bc2016-06-20 12:57:21 -0500196 self.rows, self.columns = self.getTerminalColumns()
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500197 except:
198 self.cuu = None
Patrick Williamsd8c66bc2016-06-20 12:57:21 -0500199 if not self.cuu:
200 self.interactive = False
201 bb.note("Unable to use interactive mode for this terminal, using fallback")
202 return
Andrew Geissler82c905d2020-04-13 13:39:40 -0500203
204 for h in handlers:
205 h.addFilter(InteractConsoleLogFilter(self))
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500206
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600207 self.main_progress = None
208
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500209 def clearFooter(self):
210 if self.footer_present:
211 lines = self.footer_present
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600212 sys.stdout.buffer.write(self.curses.tparm(self.cuu, lines))
213 sys.stdout.buffer.write(self.curses.tparm(self.ed))
214 sys.stdout.flush()
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500215 self.footer_present = False
216
Brad Bishopc342db32019-05-15 21:57:59 -0400217 def elapsed(self, sec):
218 hrs = int(sec / 3600.0)
219 sec -= hrs * 3600
220 min = int(sec / 60.0)
221 sec -= min * 60
222 if hrs > 0:
223 return "%dh%dm%ds" % (hrs, min, sec)
224 elif min > 0:
225 return "%dm%ds" % (min, sec)
226 else:
227 return "%ds" % (sec)
228
229 def keepAlive(self, t):
230 if not self.cuu:
Andrew Geissler9aee5002022-03-30 16:27:02 +0000231 print("Bitbake still alive (no events for %ds). Active tasks:" % t)
232 for t in self.helper.running_tasks:
233 print(t)
Brad Bishopc342db32019-05-15 21:57:59 -0400234 sys.stdout.flush()
235
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500236 def updateFooter(self):
237 if not self.cuu:
238 return
239 activetasks = self.helper.running_tasks
240 failedtasks = self.helper.failed_tasks
241 runningpids = self.helper.running_pids
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600242 currenttime = time.time()
243 if not self.lasttime or (currenttime - self.lasttime > 5):
244 self.helper.needUpdate = True
245 self.lasttime = currenttime
246 if self.footer_present and not self.helper.needUpdate:
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500247 return
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600248 self.helper.needUpdate = False
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500249 if self.footer_present:
250 self.clearFooter()
251 if (not self.helper.tasknumber_total or self.helper.tasknumber_current == self.helper.tasknumber_total) and not len(activetasks):
252 return
253 tasks = []
254 for t in runningpids:
Patrick Williamsde0582f2022-04-08 10:23:27 -0500255 start_time = activetasks[t].get("starttime", None)
256 if start_time:
257 msg = "%s - %s (pid %s)" % (activetasks[t]["title"], self.elapsed(currenttime - start_time), activetasks[t]["pid"])
258 else:
259 msg = "%s (pid %s)" % (activetasks[t]["title"], activetasks[t]["pid"])
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600260 progress = activetasks[t].get("progress", None)
261 if progress is not None:
262 pbar = activetasks[t].get("progressbar", None)
263 rate = activetasks[t].get("rate", None)
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600264 if not pbar or pbar.bouncing != (progress < 0):
265 if progress < 0:
Patrick Williamsde0582f2022-04-08 10:23:27 -0500266 pbar = BBProgress("0: %s" % msg, 100, widgets=[' ', progressbar.BouncingSlider(), ''], extrapos=3, resize_handler=self.sigwinch_handle)
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600267 pbar.bouncing = True
268 else:
Patrick Williamsde0582f2022-04-08 10:23:27 -0500269 pbar = BBProgress("0: %s" % msg, 100, widgets=[' ', progressbar.Percentage(), ' ', progressbar.Bar(), ''], extrapos=5, resize_handler=self.sigwinch_handle)
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600270 pbar.bouncing = False
271 activetasks[t]["progressbar"] = pbar
Patrick Williamsde0582f2022-04-08 10:23:27 -0500272 tasks.append((pbar, msg, progress, rate, start_time))
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600273 else:
Patrick Williamsde0582f2022-04-08 10:23:27 -0500274 tasks.append(msg)
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500275
276 if self.main.shutdown:
Andrew Geissler9aee5002022-03-30 16:27:02 +0000277 content = pluralise("Waiting for %s running task to finish",
278 "Waiting for %s running tasks to finish", len(activetasks))
279 if not self.quiet:
280 content += ':'
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500281 print(content)
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600282 else:
Andrew Geissler9aee5002022-03-30 16:27:02 +0000283 scene_tasks = "%s of %s" % (self.helper.setscene_current, self.helper.setscene_total)
284 cur_tasks = "%s of %s" % (self.helper.tasknumber_current, self.helper.tasknumber_total)
285
286 content = ''
287 if not self.quiet:
288 msg = "Setscene tasks: %s" % scene_tasks
289 content += msg + "\n"
290 print(msg)
291
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600292 if self.quiet:
Andrew Geissler9aee5002022-03-30 16:27:02 +0000293 msg = "Running tasks (%s, %s)" % (scene_tasks, cur_tasks)
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600294 elif not len(activetasks):
Andrew Geissler9aee5002022-03-30 16:27:02 +0000295 msg = "No currently running tasks (%s)" % cur_tasks
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600296 else:
Andrew Geissler9aee5002022-03-30 16:27:02 +0000297 msg = "Currently %2s running tasks (%s)" % (len(activetasks), cur_tasks)
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600298 maxtask = self.helper.tasknumber_total
299 if not self.main_progress or self.main_progress.maxval != maxtask:
300 widgets = [' ', progressbar.Percentage(), ' ', progressbar.Bar()]
301 self.main_progress = BBProgress("Running tasks", maxtask, widgets=widgets, resize_handler=self.sigwinch_handle)
302 self.main_progress.start(False)
Andrew Geissler9aee5002022-03-30 16:27:02 +0000303 self.main_progress.setmessage(msg)
304 progress = max(0, self.helper.tasknumber_current - 1)
305 content += self.main_progress.update(progress)
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600306 print('')
Andrew Geissler9aee5002022-03-30 16:27:02 +0000307 lines = self.getlines(content)
308 if not self.quiet:
309 for tasknum, task in enumerate(tasks[:(self.rows - 1 - lines)]):
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600310 if isinstance(task, tuple):
Patrick Williamsde0582f2022-04-08 10:23:27 -0500311 pbar, msg, progress, rate, start_time = task
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600312 if not pbar.start_time:
313 pbar.start(False)
314 if start_time:
315 pbar.start_time = start_time
Patrick Williamsde0582f2022-04-08 10:23:27 -0500316 pbar.setmessage('%s: %s' % (tasknum, msg))
Brad Bishop15ae2502019-06-18 21:44:24 -0400317 pbar.setextra(rate)
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600318 if progress > -1:
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600319 content = pbar.update(progress)
320 else:
321 content = pbar.update(1)
322 print('')
323 else:
324 content = "%s: %s" % (tasknum, task)
325 print(content)
Andrew Geissler9aee5002022-03-30 16:27:02 +0000326 lines = lines + self.getlines(content)
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500327 self.footer_present = lines
328 self.lastpids = runningpids[:]
329 self.lastcount = self.helper.tasknumber_current
330
Andrew Geissler9aee5002022-03-30 16:27:02 +0000331 def getlines(self, content):
332 lines = 0
333 for line in content.split("\n"):
334 lines = lines + 1 + int(len(line) / (self.columns + 1))
335 return lines
336
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500337 def finish(self):
338 if self.stdinbackup:
339 fd = sys.stdin.fileno()
340 self.termios.tcsetattr(fd, self.termios.TCSADRAIN, self.stdinbackup)
341
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500342def print_event_log(event, includelogs, loglines, termfilter):
343 # FIXME refactor this out further
344 logfile = event.logfile
345 if logfile and os.path.exists(logfile):
346 termfilter.clearFooter()
347 bb.error("Logfile of failure stored in: %s" % logfile)
348 if includelogs and not event.errprinted:
349 print("Log data follows:")
350 f = open(logfile, "r")
351 lines = []
352 while True:
353 l = f.readline()
354 if l == '':
355 break
356 l = l.rstrip()
357 if loglines:
358 lines.append(' | %s' % l)
359 if len(lines) > int(loglines):
360 lines.pop(0)
361 else:
362 print('| %s' % l)
363 f.close()
364 if lines:
365 for line in lines:
366 print(line)
367
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500368def _log_settings_from_server(server, observe_only):
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500369 # Get values of variables which control our output
370 includelogs, error = server.runCommand(["getVariable", "BBINCLUDELOGS"])
371 if error:
372 logger.error("Unable to get the value of BBINCLUDELOGS variable: %s" % error)
373 raise BaseException(error)
374 loglines, error = server.runCommand(["getVariable", "BBINCLUDELOGS_LINES"])
375 if error:
376 logger.error("Unable to get the value of BBINCLUDELOGS_LINES variable: %s" % error)
377 raise BaseException(error)
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500378 if observe_only:
379 cmd = 'getVariable'
380 else:
381 cmd = 'getSetVariable'
382 consolelogfile, error = server.runCommand([cmd, "BB_CONSOLELOG"])
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500383 if error:
384 logger.error("Unable to get the value of BB_CONSOLELOG variable: %s" % error)
385 raise BaseException(error)
Andrew Geissler82c905d2020-04-13 13:39:40 -0500386 logconfigfile, error = server.runCommand([cmd, "BB_LOGCONFIG"])
387 if error:
388 logger.error("Unable to get the value of BB_LOGCONFIG variable: %s" % error)
389 raise BaseException(error)
390 return includelogs, loglines, consolelogfile, logconfigfile
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500391
392_evt_list = [ "bb.runqueue.runQueueExitWait", "bb.event.LogExecTTY", "logging.LogRecord",
393 "bb.build.TaskFailed", "bb.build.TaskBase", "bb.event.ParseStarted",
394 "bb.event.ParseProgress", "bb.event.ParseCompleted", "bb.event.CacheLoadStarted",
395 "bb.event.CacheLoadProgress", "bb.event.CacheLoadCompleted", "bb.command.CommandFailed",
396 "bb.command.CommandExit", "bb.command.CommandCompleted", "bb.cooker.CookerExit",
397 "bb.event.MultipleProviders", "bb.event.NoProvider", "bb.runqueue.sceneQueueTaskStarted",
398 "bb.runqueue.runQueueTaskStarted", "bb.runqueue.runQueueTaskFailed", "bb.runqueue.sceneQueueTaskFailed",
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600399 "bb.event.BuildBase", "bb.build.TaskStarted", "bb.build.TaskSucceeded", "bb.build.TaskFailedSilent",
400 "bb.build.TaskProgress", "bb.event.ProcessStarted", "bb.event.ProcessProgress", "bb.event.ProcessFinished"]
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500401
Andrew Geisslerc9f78652020-09-18 14:11:35 -0500402def drain_events_errorhandling(eventHandler):
403 # We don't have logging setup, we do need to show any events we see before exiting
404 event = True
405 logger = bb.msg.logger_create('bitbake', sys.stdout)
406 while event:
407 event = eventHandler.waitEvent(0)
408 if isinstance(event, logging.LogRecord):
409 logger.handle(event)
410
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500411def main(server, eventHandler, params, tf = TerminalFilter):
412
Andrew Geisslerc9f78652020-09-18 14:11:35 -0500413 try:
414 if not params.observe_only:
415 params.updateToServer(server, os.environ.copy())
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500416
Andrew Geisslerc9f78652020-09-18 14:11:35 -0500417 includelogs, loglines, consolelogfile, logconfigfile = _log_settings_from_server(server, params.observe_only)
Andrew Geissler82c905d2020-04-13 13:39:40 -0500418
Andrew Geisslerc9f78652020-09-18 14:11:35 -0500419 loglevel, _ = bb.msg.constructLogOptions()
420 except bb.BBHandledException:
421 drain_events_errorhandling(eventHandler)
422 return 1
Andrew Geissler82c905d2020-04-13 13:39:40 -0500423
424 if params.options.quiet == 0:
425 console_loglevel = loglevel
426 elif params.options.quiet > 2:
427 console_loglevel = bb.msg.BBLogFormatter.ERROR
428 else:
429 console_loglevel = bb.msg.BBLogFormatter.WARNING
430
431 logconfig = {
432 "version": 1,
433 "handlers": {
434 "BitBake.console": {
435 "class": "logging.StreamHandler",
436 "formatter": "BitBake.consoleFormatter",
437 "level": console_loglevel,
438 "stream": "ext://sys.stdout",
439 "filters": ["BitBake.stdoutFilter"],
440 ".": {
441 "is_console": True,
442 },
443 },
444 "BitBake.errconsole": {
445 "class": "logging.StreamHandler",
446 "formatter": "BitBake.consoleFormatter",
447 "level": loglevel,
448 "stream": "ext://sys.stderr",
449 "filters": ["BitBake.stderrFilter"],
450 ".": {
451 "is_console": True,
452 },
453 },
454 # This handler can be used if specific loggers should print on
455 # the console at a lower severity than the default. It will
456 # display any messages sent to it that are lower than then
457 # BitBake.console logging level (so as to prevent duplication of
458 # messages). Nothing is attached to this handler by default
459 "BitBake.verbconsole": {
460 "class": "logging.StreamHandler",
461 "formatter": "BitBake.consoleFormatter",
462 "level": 1,
463 "stream": "ext://sys.stdout",
464 "filters": ["BitBake.verbconsoleFilter"],
465 ".": {
466 "is_console": True,
467 },
468 },
469 },
470 "formatters": {
471 # This format instance will get color output enabled by the
472 # terminal
473 "BitBake.consoleFormatter" : {
474 "()": "bb.msg.BBLogFormatter",
475 "format": "%(levelname)s: %(message)s"
476 },
477 # The file log requires a separate instance so that it doesn't get
478 # color enabled
479 "BitBake.logfileFormatter": {
480 "()": "bb.msg.BBLogFormatter",
481 "format": "%(levelname)s: %(message)s"
482 }
483 },
484 "filters": {
485 "BitBake.stdoutFilter": {
486 "()": "bb.msg.LogFilterLTLevel",
487 "level": "ERROR"
488 },
489 "BitBake.stderrFilter": {
490 "()": "bb.msg.LogFilterGEQLevel",
491 "level": "ERROR"
492 },
493 "BitBake.verbconsoleFilter": {
494 "()": "bb.msg.LogFilterLTLevel",
495 "level": console_loglevel
496 },
497 },
498 "loggers": {
499 "BitBake": {
500 "level": loglevel,
501 "handlers": ["BitBake.console", "BitBake.errconsole"],
502 }
503 },
504 "disable_existing_loggers": False
505 }
506
507 # Enable the console log file if enabled
508 if consolelogfile and not params.options.show_environment and not params.options.show_versions:
509 logconfig = bb.msg.mergeLoggingConfig(logconfig, {
510 "version": 1,
511 "handlers" : {
512 "BitBake.consolelog": {
513 "class": "logging.FileHandler",
514 "formatter": "BitBake.logfileFormatter",
515 "level": loglevel,
516 "filename": consolelogfile,
517 },
518 # Just like verbconsole, anything sent here will go to the
519 # log file, unless it would go to BitBake.consolelog
520 "BitBake.verbconsolelog" : {
521 "class": "logging.FileHandler",
522 "formatter": "BitBake.logfileFormatter",
523 "level": 1,
524 "filename": consolelogfile,
525 "filters": ["BitBake.verbconsolelogFilter"],
526 },
527 },
528 "filters": {
529 "BitBake.verbconsolelogFilter": {
530 "()": "bb.msg.LogFilterLTLevel",
531 "level": loglevel,
532 },
533 },
534 "loggers": {
535 "BitBake": {
536 "handlers": ["BitBake.consolelog"],
537 },
538
539 # Other interesting things that we want to keep an eye on
540 # in the log files in case someone has an issue, but not
541 # necessarily show to the user on the console
542 "BitBake.SigGen.HashEquiv": {
543 "level": "VERBOSE",
544 "handlers": ["BitBake.verbconsolelog"],
545 },
546 "BitBake.RunQueue.HashEquiv": {
547 "level": "VERBOSE",
548 "handlers": ["BitBake.verbconsolelog"],
549 }
550 }
551 })
552
553 bb.utils.mkdirhier(os.path.dirname(consolelogfile))
554 loglink = os.path.join(os.path.dirname(consolelogfile), 'console-latest.log')
555 bb.utils.remove(loglink)
556 try:
557 os.symlink(os.path.basename(consolelogfile), loglink)
558 except OSError:
559 pass
560
Andrew Geisslerc926e172021-05-07 16:11:35 -0500561 # Add the logging domains specified by the user on the command line
562 for (domainarg, iterator) in groupby(params.debug_domains):
563 dlevel = len(tuple(iterator))
564 l = logconfig["loggers"].setdefault("BitBake.%s" % domainarg, {})
565 l["level"] = logging.DEBUG - dlevel + 1
566 l.setdefault("handlers", []).extend(["BitBake.verbconsole"])
567
Andrew Geissler82c905d2020-04-13 13:39:40 -0500568 conf = bb.msg.setLoggingConfig(logconfig, logconfigfile)
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500569
570 if sys.stdin.isatty() and sys.stdout.isatty():
571 log_exec_tty = True
572 else:
573 log_exec_tty = False
574
575 helper = uihelper.BBUIHelper()
576
Andrew Geissler82c905d2020-04-13 13:39:40 -0500577 # Look for the specially designated handlers which need to be passed to the
578 # terminal handler
579 console_handlers = [h for h in conf.config['handlers'].values() if getattr(h, 'is_console', False)]
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500580
Patrick Williamsd8c66bc2016-06-20 12:57:21 -0500581 bb.utils.set_process_name("KnottyUI")
582
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500583 if params.options.remote_server and params.options.kill_server:
584 server.terminateServer()
585 return
586
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500587 llevel, debug_domains = bb.msg.constructLogOptions()
588 server.runCommand(["setEventMask", server.getEventHandle(), llevel, debug_domains, _evt_list])
589
Andrew Geissler82c905d2020-04-13 13:39:40 -0500590 # The logging_tree module is *extremely* helpful in debugging logging
591 # domains. Uncomment here to dump the logging tree when bitbake starts
592 #import logging_tree
593 #logging_tree.printout()
594
Patrick Williamsd8c66bc2016-06-20 12:57:21 -0500595 universe = False
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500596 if not params.observe_only:
597 params.updateFromServer(server)
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500598 cmdline = params.parseActions()
599 if not cmdline:
600 print("Nothing to do. Use 'bitbake world' to build everything, or run 'bitbake --help' for usage information.")
601 return 1
602 if 'msg' in cmdline and cmdline['msg']:
603 logger.error(cmdline['msg'])
604 return 1
Patrick Williamsd8c66bc2016-06-20 12:57:21 -0500605 if cmdline['action'][0] == "buildTargets" and "universe" in cmdline['action'][1]:
606 universe = True
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500607
608 ret, error = server.runCommand(cmdline['action'])
609 if error:
610 logger.error("Command '%s' failed: %s" % (cmdline, error))
611 return 1
Andrew Geissler82c905d2020-04-13 13:39:40 -0500612 elif not ret:
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500613 logger.error("Command '%s' failed: returned %s" % (cmdline, ret))
614 return 1
615
616
617 parseprogress = None
618 cacheprogress = None
619 main.shutdown = 0
620 interrupted = False
621 return_value = 0
622 errors = 0
623 warnings = 0
624 taskfailures = []
625
Andrew Geissler9aee5002022-03-30 16:27:02 +0000626 printintervaldelta = 10 * 60 # 10 minutes
627 printinterval = printintervaldelta
Andrew Geissler517393d2023-01-13 08:55:19 -0600628 pinginterval = 1 * 60 # 1 minute
629 lastevent = lastprint = time.time()
Brad Bishopc342db32019-05-15 21:57:59 -0400630
Andrew Geissler82c905d2020-04-13 13:39:40 -0500631 termfilter = tf(main, helper, console_handlers, params.options.quiet)
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500632 atexit.register(termfilter.finish)
633
Andrew Geissler517393d2023-01-13 08:55:19 -0600634 # shutdown levels
635 # 0 - normal operation
636 # 1 - no new task execution, let current running tasks finish
637 # 2 - interrupting currently executing tasks
638 # 3 - we're done, exit
639 while main.shutdown < 3:
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500640 try:
Brad Bishopc342db32019-05-15 21:57:59 -0400641 if (lastprint + printinterval) <= time.time():
642 termfilter.keepAlive(printinterval)
Andrew Geissler9aee5002022-03-30 16:27:02 +0000643 printinterval += printintervaldelta
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500644 event = eventHandler.waitEvent(0)
645 if event is None:
Andrew Geissler517393d2023-01-13 08:55:19 -0600646 if (lastevent + pinginterval) <= time.time():
647 ret, error = server.runCommand(["ping"])
648 if error or not ret:
649 termfilter.clearFooter()
650 print("No reply after pinging server (%s, %s), exiting." % (str(error), str(ret)))
651 return_value = 3
652 main.shutdown = 3
653 lastevent = time.time()
Andrew Geissler82c905d2020-04-13 13:39:40 -0500654 if not parseprogress:
655 termfilter.updateFooter()
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500656 event = eventHandler.waitEvent(0.25)
657 if event is None:
658 continue
Andrew Geissler517393d2023-01-13 08:55:19 -0600659 lastevent = time.time()
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500660 helper.eventHandler(event)
661 if isinstance(event, bb.runqueue.runQueueExitWait):
662 if not main.shutdown:
663 main.shutdown = 1
664 continue
665 if isinstance(event, bb.event.LogExecTTY):
666 if log_exec_tty:
667 tries = event.retries
668 while tries:
669 print("Trying to run: %s" % event.prog)
670 if os.system(event.prog) == 0:
671 break
672 time.sleep(event.sleep_delay)
673 tries -= 1
674 if tries:
675 continue
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600676 logger.warning(event.msg)
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500677 continue
678
679 if isinstance(event, logging.LogRecord):
Brad Bishopc342db32019-05-15 21:57:59 -0400680 lastprint = time.time()
Andrew Geissler9aee5002022-03-30 16:27:02 +0000681 printinterval = printintervaldelta
Andrew Geissler7e0e3c02022-02-25 20:34:39 +0000682 if event.levelno >= bb.msg.BBLogFormatter.ERRORONCE:
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500683 errors = errors + 1
684 return_value = 1
Andrew Geissler82c905d2020-04-13 13:39:40 -0500685 elif event.levelno == bb.msg.BBLogFormatter.WARNING:
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500686 warnings = warnings + 1
Patrick Williamsd8c66bc2016-06-20 12:57:21 -0500687
688 if event.taskpid != 0:
689 # For "normal" logging conditions, don't show note logs from tasks
690 # but do show them if the user has changed the default log level to
691 # include verbose/debug messages
Andrew Geissler82c905d2020-04-13 13:39:40 -0500692 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 -0500693 continue
694
695 # Prefix task messages with recipe/task
Andrew Geissler7e0e3c02022-02-25 20:34:39 +0000696 if event.taskpid in helper.pidmap and event.levelno not in [bb.msg.BBLogFormatter.PLAIN, bb.msg.BBLogFormatter.WARNONCE, bb.msg.BBLogFormatter.ERRORONCE]:
Andrew Geissler82c905d2020-04-13 13:39:40 -0500697 taskinfo = helper.running_tasks[helper.pidmap[event.taskpid]]
Patrick Williamsd8c66bc2016-06-20 12:57:21 -0500698 event.msg = taskinfo['title'] + ': ' + event.msg
Andrew Geissler7e0e3c02022-02-25 20:34:39 +0000699 if hasattr(event, 'fn') and event.levelno not in [bb.msg.BBLogFormatter.WARNONCE, bb.msg.BBLogFormatter.ERRORONCE]:
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500700 event.msg = event.fn + ': ' + event.msg
Andrew Geissler82c905d2020-04-13 13:39:40 -0500701 logging.getLogger(event.name).handle(event)
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500702 continue
703
704 if isinstance(event, bb.build.TaskFailedSilent):
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600705 logger.warning("Logfile for failed setscene task is %s" % event.logfile)
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500706 continue
707 if isinstance(event, bb.build.TaskFailed):
708 return_value = 1
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500709 print_event_log(event, includelogs, loglines, termfilter)
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500710 if isinstance(event, bb.build.TaskBase):
711 logger.info(event._message)
712 continue
713 if isinstance(event, bb.event.ParseStarted):
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500714 if params.options.quiet > 1:
715 continue
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500716 if event.total == 0:
717 continue
Andrew Geissler82c905d2020-04-13 13:39:40 -0500718 termfilter.clearFooter()
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500719 parseprogress = new_progress("Parsing recipes", event.total).start()
720 continue
721 if isinstance(event, bb.event.ParseProgress):
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500722 if params.options.quiet > 1:
723 continue
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600724 if parseprogress:
725 parseprogress.update(event.current)
726 else:
727 bb.warn("Got ParseProgress event for parsing that never started?")
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500728 continue
729 if isinstance(event, bb.event.ParseCompleted):
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500730 if params.options.quiet > 1:
731 continue
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500732 if not parseprogress:
733 continue
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500734 parseprogress.finish()
Andrew Geissler4c19ea12020-10-27 13:52:24 -0500735 parseprogress = None
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500736 if params.options.quiet == 0:
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600737 print(("Parsing of %d .bb files complete (%d cached, %d parsed). %d targets, %d skipped, %d masked, %d errors."
738 % ( event.total, event.cached, event.parsed, event.virtuals, event.skipped, event.masked, event.errors)))
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500739 continue
740
741 if isinstance(event, bb.event.CacheLoadStarted):
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500742 if params.options.quiet > 1:
743 continue
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500744 cacheprogress = new_progress("Loading cache", event.total).start()
745 continue
746 if isinstance(event, bb.event.CacheLoadProgress):
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500747 if params.options.quiet > 1:
748 continue
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500749 cacheprogress.update(event.current)
750 continue
751 if isinstance(event, bb.event.CacheLoadCompleted):
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500752 if params.options.quiet > 1:
753 continue
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500754 cacheprogress.finish()
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500755 if params.options.quiet == 0:
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600756 print("Loaded %d entries from dependency cache." % event.num_entries)
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500757 continue
758
759 if isinstance(event, bb.command.CommandFailed):
760 return_value = event.exitcode
761 if event.error:
762 errors = errors + 1
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500763 logger.error(str(event))
Andrew Geissler517393d2023-01-13 08:55:19 -0600764 main.shutdown = 3
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500765 continue
766 if isinstance(event, bb.command.CommandExit):
767 if not return_value:
768 return_value = event.exitcode
Andrew Geissler517393d2023-01-13 08:55:19 -0600769 main.shutdown = 3
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500770 continue
771 if isinstance(event, (bb.command.CommandCompleted, bb.cooker.CookerExit)):
Andrew Geissler517393d2023-01-13 08:55:19 -0600772 main.shutdown = 3
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500773 continue
774 if isinstance(event, bb.event.MultipleProviders):
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500775 logger.info(str(event))
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500776 continue
777 if isinstance(event, bb.event.NoProvider):
Patrick Williamsd8c66bc2016-06-20 12:57:21 -0500778 # For universe builds, only show these as warnings, not errors
Patrick Williamsd8c66bc2016-06-20 12:57:21 -0500779 if not universe:
780 return_value = 1
781 errors = errors + 1
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500782 logger.error(str(event))
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500783 else:
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500784 logger.warning(str(event))
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500785 continue
786
787 if isinstance(event, bb.runqueue.sceneQueueTaskStarted):
Andrew Geissler5199d832021-09-24 16:47:35 -0500788 logger.info("Running setscene task %d of %d (%s)" % (event.stats.setscene_covered + event.stats.setscene_active + event.stats.setscene_notcovered + 1, event.stats.setscene_total, event.taskstring))
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500789 continue
790
791 if isinstance(event, bb.runqueue.runQueueTaskStarted):
792 if event.noexec:
793 tasktype = 'noexec task'
794 else:
795 tasktype = 'task'
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600796 logger.info("Running %s %d of %d (%s)",
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500797 tasktype,
798 event.stats.completed + event.stats.active +
799 event.stats.failed + 1,
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600800 event.stats.total, event.taskstring)
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500801 continue
802
803 if isinstance(event, bb.runqueue.runQueueTaskFailed):
Patrick Williamsd8c66bc2016-06-20 12:57:21 -0500804 return_value = 1
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500805 taskfailures.append(event.taskstring)
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500806 logger.error(str(event))
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500807 continue
808
809 if isinstance(event, bb.runqueue.sceneQueueTaskFailed):
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500810 logger.warning(str(event))
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500811 continue
812
813 if isinstance(event, bb.event.DepTreeGenerated):
814 continue
815
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600816 if isinstance(event, bb.event.ProcessStarted):
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500817 if params.options.quiet > 1:
818 continue
Andrew Geissler82c905d2020-04-13 13:39:40 -0500819 termfilter.clearFooter()
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600820 parseprogress = new_progress(event.processname, event.total)
821 parseprogress.start(False)
822 continue
823 if isinstance(event, bb.event.ProcessProgress):
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500824 if params.options.quiet > 1:
825 continue
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600826 if parseprogress:
827 parseprogress.update(event.progress)
828 else:
829 bb.warn("Got ProcessProgress event for someting that never started?")
830 continue
831 if isinstance(event, bb.event.ProcessFinished):
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500832 if params.options.quiet > 1:
833 continue
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600834 if parseprogress:
835 parseprogress.finish()
836 parseprogress = None
837 continue
838
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500839 # ignore
840 if isinstance(event, (bb.event.BuildBase,
841 bb.event.MetadataEvent,
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500842 bb.event.ConfigParsed,
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500843 bb.event.MultiConfigParsed,
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500844 bb.event.RecipeParsed,
845 bb.event.RecipePreFinalise,
846 bb.runqueue.runQueueEvent,
847 bb.event.OperationStarted,
848 bb.event.OperationCompleted,
849 bb.event.OperationProgress,
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600850 bb.event.DiskFull,
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500851 bb.event.HeartbeatEvent,
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600852 bb.build.TaskProgress)):
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500853 continue
854
855 logger.error("Unknown event: %s", event)
856
857 except EnvironmentError as ioerror:
858 termfilter.clearFooter()
859 # ignore interrupted io
860 if ioerror.args[0] == 4:
861 continue
862 sys.stderr.write(str(ioerror))
863 if not params.observe_only:
864 _, error = server.runCommand(["stateForceShutdown"])
865 main.shutdown = 2
866 except KeyboardInterrupt:
867 termfilter.clearFooter()
868 if params.observe_only:
869 print("\nKeyboard Interrupt, exiting observer...")
870 main.shutdown = 2
Brad Bishop08902b02019-08-20 09:16:51 -0400871
872 def state_force_shutdown():
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500873 print("\nSecond Keyboard Interrupt, stopping...\n")
874 _, error = server.runCommand(["stateForceShutdown"])
875 if error:
876 logger.error("Unable to cleanly stop: %s" % error)
Brad Bishop08902b02019-08-20 09:16:51 -0400877
878 if not params.observe_only and main.shutdown == 1:
879 state_force_shutdown()
880
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500881 if not params.observe_only and main.shutdown == 0:
882 print("\nKeyboard Interrupt, closing down...\n")
883 interrupted = True
Brad Bishop08902b02019-08-20 09:16:51 -0400884 # Capture the second KeyboardInterrupt during stateShutdown is running
885 try:
886 _, error = server.runCommand(["stateShutdown"])
887 if error:
888 logger.error("Unable to cleanly shutdown: %s" % error)
889 except KeyboardInterrupt:
890 state_force_shutdown()
891
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500892 main.shutdown = main.shutdown + 1
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500893 except Exception as e:
Patrick Williamsd8c66bc2016-06-20 12:57:21 -0500894 import traceback
895 sys.stderr.write(traceback.format_exc())
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500896 if not params.observe_only:
897 _, error = server.runCommand(["stateForceShutdown"])
898 main.shutdown = 2
Patrick Williamsd8c66bc2016-06-20 12:57:21 -0500899 return_value = 1
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500900 try:
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600901 termfilter.clearFooter()
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500902 summary = ""
903 if taskfailures:
904 summary += pluralise("\nSummary: %s task failed:",
905 "\nSummary: %s tasks failed:", len(taskfailures))
906 for failure in taskfailures:
907 summary += "\n %s" % failure
908 if warnings:
Andrew Geissler7e0e3c02022-02-25 20:34:39 +0000909 summary += pluralise("\nSummary: There was %s WARNING message.",
910 "\nSummary: There were %s WARNING messages.", warnings)
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500911 if return_value and errors:
Andrew Geissler7e0e3c02022-02-25 20:34:39 +0000912 summary += pluralise("\nSummary: There was %s ERROR message, returning a non-zero exit code.",
913 "\nSummary: There were %s ERROR messages, returning a non-zero exit code.", errors)
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500914 if summary and params.options.quiet == 0:
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500915 print(summary)
916
917 if interrupted:
918 print("Execution was interrupted, returning a non-zero exit code.")
919 if return_value == 0:
920 return_value = 1
921 except IOError as e:
922 import errno
923 if e.errno == errno.EPIPE:
924 pass
925
Andrew Geissler82c905d2020-04-13 13:39:40 -0500926 logging.shutdown()
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600927
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500928 return return_value