toasterui.py 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477
  1. #
  2. # BitBake ToasterUI Implementation
  3. # based on (No)TTY UI Implementation by Richard Purdie
  4. #
  5. # Handling output to TTYs or files (no TTY)
  6. #
  7. # Copyright (C) 2006-2012 Richard Purdie
  8. # Copyright (C) 2013 Intel Corporation
  9. #
  10. # SPDX-License-Identifier: GPL-2.0-only
  11. #
  12. from __future__ import division
  13. import time
  14. import sys
  15. try:
  16. import bb
  17. except RuntimeError as exc:
  18. sys.exit(str(exc))
  19. from bb.ui import uihelper
  20. from bb.ui.buildinfohelper import BuildInfoHelper
  21. import bb.msg
  22. import logging
  23. import os
  24. # pylint: disable=invalid-name
  25. # module properties for UI modules are read by bitbake and the contract should not be broken
  26. featureSet = [bb.cooker.CookerFeatures.HOB_EXTRA_CACHES, bb.cooker.CookerFeatures.BASEDATASTORE_TRACKING, bb.cooker.CookerFeatures.SEND_SANITYEVENTS]
  27. logger = logging.getLogger("ToasterLogger")
  28. interactive = sys.stdout.isatty()
  29. def _log_settings_from_server(server):
  30. # Get values of variables which control our output
  31. includelogs, error = server.runCommand(["getVariable", "BBINCLUDELOGS"])
  32. if error:
  33. logger.error("Unable to get the value of BBINCLUDELOGS variable: %s", error)
  34. raise BaseException(error)
  35. loglines, error = server.runCommand(["getVariable", "BBINCLUDELOGS_LINES"])
  36. if error:
  37. logger.error("Unable to get the value of BBINCLUDELOGS_LINES variable: %s", error)
  38. raise BaseException(error)
  39. consolelogfile, error = server.runCommand(["getVariable", "BB_CONSOLELOG"])
  40. if error:
  41. logger.error("Unable to get the value of BB_CONSOLELOG variable: %s", error)
  42. raise BaseException(error)
  43. return consolelogfile
  44. # create a log file for a single build and direct the logger at it;
  45. # log file name is timestamped to the millisecond (depending
  46. # on system clock accuracy) to ensure it doesn't overlap with
  47. # other log file names
  48. #
  49. # returns (log file, path to log file) for a build
  50. def _open_build_log(log_dir):
  51. format_str = "%(levelname)s: %(message)s"
  52. now = time.time()
  53. now_ms = int((now - int(now)) * 1000)
  54. time_str = time.strftime('build_%Y%m%d_%H%M%S', time.localtime(now))
  55. log_file_name = time_str + ('.%d.log' % now_ms)
  56. build_log_file_path = os.path.join(log_dir, log_file_name)
  57. build_log = logging.FileHandler(build_log_file_path)
  58. logformat = bb.msg.BBLogFormatter(format_str)
  59. build_log.setFormatter(logformat)
  60. bb.msg.addDefaultlogFilter(build_log)
  61. logger.addHandler(build_log)
  62. return (build_log, build_log_file_path)
  63. # stop logging to the build log if it exists
  64. def _close_build_log(build_log):
  65. if build_log:
  66. build_log.flush()
  67. build_log.close()
  68. logger.removeHandler(build_log)
  69. _evt_list = [
  70. "bb.build.TaskBase",
  71. "bb.build.TaskFailed",
  72. "bb.build.TaskFailedSilent",
  73. "bb.build.TaskStarted",
  74. "bb.build.TaskSucceeded",
  75. "bb.command.CommandCompleted",
  76. "bb.command.CommandExit",
  77. "bb.command.CommandFailed",
  78. "bb.cooker.CookerExit",
  79. "bb.event.BuildInit",
  80. "bb.event.BuildCompleted",
  81. "bb.event.BuildStarted",
  82. "bb.event.CacheLoadCompleted",
  83. "bb.event.CacheLoadProgress",
  84. "bb.event.CacheLoadStarted",
  85. "bb.event.ConfigParsed",
  86. "bb.event.DepTreeGenerated",
  87. "bb.event.LogExecTTY",
  88. "bb.event.MetadataEvent",
  89. "bb.event.MultipleProviders",
  90. "bb.event.NoProvider",
  91. "bb.event.ParseCompleted",
  92. "bb.event.ParseProgress",
  93. "bb.event.ParseStarted",
  94. "bb.event.RecipeParsed",
  95. "bb.event.SanityCheck",
  96. "bb.event.SanityCheckPassed",
  97. "bb.event.TreeDataPreparationCompleted",
  98. "bb.event.TreeDataPreparationStarted",
  99. "bb.runqueue.runQueueTaskCompleted",
  100. "bb.runqueue.runQueueTaskFailed",
  101. "bb.runqueue.runQueueTaskSkipped",
  102. "bb.runqueue.runQueueTaskStarted",
  103. "bb.runqueue.sceneQueueTaskCompleted",
  104. "bb.runqueue.sceneQueueTaskFailed",
  105. "bb.runqueue.sceneQueueTaskStarted",
  106. "logging.LogRecord"]
  107. def main(server, eventHandler, params):
  108. # set to a logging.FileHandler instance when a build starts;
  109. # see _open_build_log()
  110. build_log = None
  111. # set to the log path when a build starts
  112. build_log_file_path = None
  113. helper = uihelper.BBUIHelper()
  114. # TODO don't use log output to determine when bitbake has started
  115. #
  116. # WARNING: this log handler cannot be removed, as localhostbecontroller
  117. # relies on output in the toaster_ui.log file to determine whether
  118. # the bitbake server has started, which only happens if
  119. # this logger is setup here (see the TODO in the loop below)
  120. console = logging.StreamHandler(sys.stdout)
  121. format_str = "%(levelname)s: %(message)s"
  122. formatter = bb.msg.BBLogFormatter(format_str)
  123. bb.msg.addDefaultlogFilter(console)
  124. console.setFormatter(formatter)
  125. logger.addHandler(console)
  126. logger.setLevel(logging.INFO)
  127. llevel, debug_domains = bb.msg.constructLogOptions()
  128. result, error = server.runCommand(["setEventMask", server.getEventHandle(), llevel, debug_domains, _evt_list])
  129. if not result or error:
  130. logger.error("can't set event mask: %s", error)
  131. return 1
  132. # verify and warn
  133. build_history_enabled = True
  134. inheritlist, _ = server.runCommand(["getVariable", "INHERIT"])
  135. if not "buildhistory" in inheritlist.split(" "):
  136. logger.warning("buildhistory is not enabled. Please enable INHERIT += \"buildhistory\" to see image details.")
  137. build_history_enabled = False
  138. if not "buildstats" in inheritlist.split(" "):
  139. logger.warning("buildstats is not enabled. Please enable INHERIT += \"buildstats\" to generate build statistics.")
  140. if not params.observe_only:
  141. params.updateFromServer(server)
  142. params.updateToServer(server, os.environ.copy())
  143. cmdline = params.parseActions()
  144. if not cmdline:
  145. print("Nothing to do. Use 'bitbake world' to build everything, or run 'bitbake --help' for usage information.")
  146. return 1
  147. if 'msg' in cmdline and cmdline['msg']:
  148. logger.error(cmdline['msg'])
  149. return 1
  150. ret, error = server.runCommand(cmdline['action'])
  151. if error:
  152. logger.error("Command '%s' failed: %s" % (cmdline, error))
  153. return 1
  154. elif ret != True:
  155. logger.error("Command '%s' failed: returned %s" % (cmdline, ret))
  156. return 1
  157. # set to 1 when toasterui needs to shut down
  158. main.shutdown = 0
  159. interrupted = False
  160. return_value = 0
  161. errors = 0
  162. warnings = 0
  163. taskfailures = []
  164. first = True
  165. buildinfohelper = BuildInfoHelper(server, build_history_enabled,
  166. os.getenv('TOASTER_BRBE'))
  167. # write our own log files into bitbake's log directory;
  168. # we're only interested in the path to the parent directory of
  169. # this file, as we're writing our own logs into the same directory
  170. consolelogfile = _log_settings_from_server(server)
  171. log_dir = os.path.dirname(consolelogfile)
  172. bb.utils.mkdirhier(log_dir)
  173. while True:
  174. try:
  175. event = eventHandler.waitEvent(0.25)
  176. if first:
  177. first = False
  178. # TODO don't use log output to determine when bitbake has started
  179. #
  180. # this is the line localhostbecontroller needs to
  181. # see in toaster_ui.log which it uses to decide whether
  182. # the bitbake server has started...
  183. logger.info("ToasterUI waiting for events")
  184. if event is None:
  185. if main.shutdown > 0:
  186. # if shutting down, close any open build log first
  187. _close_build_log(build_log)
  188. break
  189. continue
  190. helper.eventHandler(event)
  191. # pylint: disable=protected-access
  192. # the code will look into the protected variables of the event; no easy way around this
  193. if isinstance(event, bb.event.HeartbeatEvent):
  194. continue
  195. if isinstance(event, bb.event.ParseStarted):
  196. if not (build_log and build_log_file_path):
  197. build_log, build_log_file_path = _open_build_log(log_dir)
  198. buildinfohelper.store_started_build()
  199. buildinfohelper.save_build_log_file_path(build_log_file_path)
  200. buildinfohelper.set_recipes_to_parse(event.total)
  201. continue
  202. # create a build object in buildinfohelper from either BuildInit
  203. # (if available) or BuildStarted (for jethro and previous versions)
  204. if isinstance(event, (bb.event.BuildStarted, bb.event.BuildInit)):
  205. if not (build_log and build_log_file_path):
  206. build_log, build_log_file_path = _open_build_log(log_dir)
  207. buildinfohelper.save_build_targets(event)
  208. buildinfohelper.save_build_log_file_path(build_log_file_path)
  209. # get additional data from BuildStarted
  210. if isinstance(event, bb.event.BuildStarted):
  211. buildinfohelper.save_build_layers_and_variables()
  212. continue
  213. if isinstance(event, bb.event.ParseProgress):
  214. buildinfohelper.set_recipes_parsed(event.current)
  215. continue
  216. if isinstance(event, bb.event.ParseCompleted):
  217. buildinfohelper.set_recipes_parsed(event.total)
  218. continue
  219. if isinstance(event, (bb.build.TaskStarted, bb.build.TaskSucceeded, bb.build.TaskFailedSilent)):
  220. buildinfohelper.update_and_store_task(event)
  221. logger.info("Logfile for task %s", event.logfile)
  222. continue
  223. if isinstance(event, bb.build.TaskBase):
  224. logger.info(event._message)
  225. if isinstance(event, bb.event.LogExecTTY):
  226. logger.info(event.msg)
  227. continue
  228. if isinstance(event, logging.LogRecord):
  229. if event.levelno == -1:
  230. event.levelno = formatter.ERROR
  231. buildinfohelper.store_log_event(event)
  232. if event.levelno >= formatter.ERROR:
  233. errors = errors + 1
  234. elif event.levelno == formatter.WARNING:
  235. warnings = warnings + 1
  236. # For "normal" logging conditions, don't show note logs from tasks
  237. # but do show them if the user has changed the default log level to
  238. # include verbose/debug messages
  239. if event.taskpid != 0 and event.levelno <= formatter.NOTE:
  240. continue
  241. logger.handle(event)
  242. continue
  243. if isinstance(event, bb.build.TaskFailed):
  244. buildinfohelper.update_and_store_task(event)
  245. logfile = event.logfile
  246. if logfile and os.path.exists(logfile):
  247. bb.error("Logfile of failure stored in: %s" % logfile)
  248. continue
  249. # these events are unprocessed now, but may be used in the future to log
  250. # timing and error informations from the parsing phase in Toaster
  251. if isinstance(event, (bb.event.SanityCheckPassed, bb.event.SanityCheck)):
  252. continue
  253. if isinstance(event, bb.event.CacheLoadStarted):
  254. continue
  255. if isinstance(event, bb.event.CacheLoadProgress):
  256. continue
  257. if isinstance(event, bb.event.CacheLoadCompleted):
  258. continue
  259. if isinstance(event, bb.event.MultipleProviders):
  260. logger.info(str(event))
  261. continue
  262. if isinstance(event, bb.event.NoProvider):
  263. errors = errors + 1
  264. text = str(event)
  265. logger.error(text)
  266. buildinfohelper.store_log_error(text)
  267. continue
  268. if isinstance(event, bb.event.ConfigParsed):
  269. continue
  270. if isinstance(event, bb.event.RecipeParsed):
  271. continue
  272. # end of saved events
  273. if isinstance(event, (bb.runqueue.sceneQueueTaskStarted, bb.runqueue.runQueueTaskStarted, bb.runqueue.runQueueTaskSkipped)):
  274. buildinfohelper.store_started_task(event)
  275. continue
  276. if isinstance(event, bb.runqueue.runQueueTaskCompleted):
  277. buildinfohelper.update_and_store_task(event)
  278. continue
  279. if isinstance(event, bb.runqueue.runQueueTaskFailed):
  280. buildinfohelper.update_and_store_task(event)
  281. taskfailures.append(event.taskstring)
  282. logger.error(str(event))
  283. continue
  284. if isinstance(event, (bb.runqueue.sceneQueueTaskCompleted, bb.runqueue.sceneQueueTaskFailed)):
  285. buildinfohelper.update_and_store_task(event)
  286. continue
  287. if isinstance(event, (bb.event.TreeDataPreparationStarted, bb.event.TreeDataPreparationCompleted)):
  288. continue
  289. if isinstance(event, (bb.event.BuildCompleted, bb.command.CommandFailed)):
  290. errorcode = 0
  291. if isinstance(event, bb.command.CommandFailed):
  292. errors += 1
  293. errorcode = 1
  294. logger.error(str(event))
  295. elif isinstance(event, bb.event.BuildCompleted):
  296. buildinfohelper.scan_image_artifacts()
  297. buildinfohelper.clone_required_sdk_artifacts()
  298. # turn off logging to the current build log
  299. _close_build_log(build_log)
  300. # reset ready for next BuildStarted
  301. build_log = None
  302. # update the build info helper on BuildCompleted, not on CommandXXX
  303. buildinfohelper.update_build_information(event, errors, warnings, taskfailures)
  304. brbe = buildinfohelper.brbe
  305. buildinfohelper.close(errorcode)
  306. # we start a new build info
  307. if params.observe_only:
  308. logger.debug("ToasterUI prepared for new build")
  309. errors = 0
  310. warnings = 0
  311. taskfailures = []
  312. buildinfohelper = BuildInfoHelper(server, build_history_enabled)
  313. else:
  314. main.shutdown = 1
  315. logger.info("ToasterUI build done, brbe: %s", brbe)
  316. continue
  317. if isinstance(event, (bb.command.CommandCompleted,
  318. bb.command.CommandFailed,
  319. bb.command.CommandExit)):
  320. if params.observe_only:
  321. errorcode = 0
  322. else:
  323. main.shutdown = 1
  324. continue
  325. if isinstance(event, bb.event.MetadataEvent):
  326. if event.type == "SinglePackageInfo":
  327. buildinfohelper.store_build_package_information(event)
  328. elif event.type == "LayerInfo":
  329. buildinfohelper.store_layer_info(event)
  330. elif event.type == "BuildStatsList":
  331. buildinfohelper.store_tasks_stats(event)
  332. elif event.type == "ImagePkgList":
  333. buildinfohelper.store_target_package_data(event)
  334. elif event.type == "MissedSstate":
  335. buildinfohelper.store_missed_state_tasks(event)
  336. elif event.type == "SDKArtifactInfo":
  337. buildinfohelper.scan_sdk_artifacts(event)
  338. elif event.type == "SetBRBE":
  339. buildinfohelper.brbe = buildinfohelper._get_data_from_event(event)
  340. elif event.type == "TaskArtifacts":
  341. buildinfohelper.scan_task_artifacts(event)
  342. elif event.type == "OSErrorException":
  343. logger.error(event)
  344. else:
  345. logger.error("Unprocessed MetadataEvent %s", event.type)
  346. continue
  347. if isinstance(event, bb.cooker.CookerExit):
  348. # shutdown when bitbake server shuts down
  349. main.shutdown = 1
  350. continue
  351. if isinstance(event, bb.event.DepTreeGenerated):
  352. buildinfohelper.store_dependency_information(event)
  353. continue
  354. logger.warning("Unknown event: %s", event)
  355. return_value += 1
  356. except EnvironmentError as ioerror:
  357. logger.warning("EnvironmentError: %s" % ioerror)
  358. # ignore interrupted io system calls
  359. if ioerror.args[0] == 4: # errno 4 is EINTR
  360. logger.warning("Skipped EINTR: %s" % ioerror)
  361. else:
  362. raise
  363. except KeyboardInterrupt:
  364. if params.observe_only:
  365. print("\nKeyboard Interrupt, exiting observer...")
  366. main.shutdown = 2
  367. if not params.observe_only and main.shutdown == 1:
  368. print("\nSecond Keyboard Interrupt, stopping...\n")
  369. _, error = server.runCommand(["stateForceShutdown"])
  370. if error:
  371. logger.error("Unable to cleanly stop: %s" % error)
  372. if not params.observe_only and main.shutdown == 0:
  373. print("\nKeyboard Interrupt, closing down...\n")
  374. interrupted = True
  375. _, error = server.runCommand(["stateShutdown"])
  376. if error:
  377. logger.error("Unable to cleanly shutdown: %s" % error)
  378. buildinfohelper.cancel_cli_build()
  379. main.shutdown = main.shutdown + 1
  380. except Exception as e:
  381. # print errors to log
  382. import traceback
  383. from pprint import pformat
  384. exception_data = traceback.format_exc()
  385. logger.error("%s\n%s" , e, exception_data)
  386. # save them to database, if possible; if it fails, we already logged to console.
  387. try:
  388. buildinfohelper.store_log_exception("%s\n%s" % (str(e), exception_data))
  389. except Exception as ce:
  390. logger.error("CRITICAL - Failed to to save toaster exception to the database: %s", str(ce))
  391. # make sure we return with an error
  392. return_value += 1
  393. if interrupted and return_value == 0:
  394. return_value += 1
  395. logger.warning("Return value is %d", return_value)
  396. return return_value