event.py 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821
  1. # ex:ts=4:sw=4:sts=4:et
  2. # -*- tab-width: 4; c-basic-offset: 4; indent-tabs-mode: nil -*-
  3. """
  4. BitBake 'Event' implementation
  5. Classes and functions for manipulating 'events' in the
  6. BitBake build tools.
  7. """
  8. # Copyright (C) 2003, 2004 Chris Larson
  9. #
  10. # This program is free software; you can redistribute it and/or modify
  11. # it under the terms of the GNU General Public License version 2 as
  12. # published by the Free Software Foundation.
  13. #
  14. # This program is distributed in the hope that it will be useful,
  15. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  16. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  17. # GNU General Public License for more details.
  18. #
  19. # You should have received a copy of the GNU General Public License along
  20. # with this program; if not, write to the Free Software Foundation, Inc.,
  21. # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
  22. import os, sys
  23. import warnings
  24. import pickle
  25. import logging
  26. import atexit
  27. import traceback
  28. import ast
  29. import threading
  30. import bb.utils
  31. import bb.compat
  32. import bb.exceptions
  33. # This is the pid for which we should generate the event. This is set when
  34. # the runqueue forks off.
  35. worker_pid = 0
  36. worker_fire = None
  37. logger = logging.getLogger('BitBake.Event')
  38. class Event(object):
  39. """Base class for events"""
  40. def __init__(self):
  41. self.pid = worker_pid
  42. class HeartbeatEvent(Event):
  43. """Triggered at regular time intervals of 10 seconds. Other events can fire much more often
  44. (runQueueTaskStarted when there are many short tasks) or not at all for long periods
  45. of time (again runQueueTaskStarted, when there is just one long-running task), so this
  46. event is more suitable for doing some task-independent work occassionally."""
  47. def __init__(self, time):
  48. Event.__init__(self)
  49. self.time = time
  50. Registered = 10
  51. AlreadyRegistered = 14
  52. def get_class_handlers():
  53. return _handlers
  54. def set_class_handlers(h):
  55. global _handlers
  56. _handlers = h
  57. def clean_class_handlers():
  58. return bb.compat.OrderedDict()
  59. # Internal
  60. _handlers = clean_class_handlers()
  61. _ui_handlers = {}
  62. _ui_logfilters = {}
  63. _ui_handler_seq = 0
  64. _event_handler_map = {}
  65. _catchall_handlers = {}
  66. _eventfilter = None
  67. _uiready = False
  68. _thread_lock = threading.Lock()
  69. _thread_lock_enabled = False
  70. if hasattr(__builtins__, '__setitem__'):
  71. builtins = __builtins__
  72. else:
  73. builtins = __builtins__.__dict__
  74. def enable_threadlock():
  75. global _thread_lock_enabled
  76. _thread_lock_enabled = True
  77. def disable_threadlock():
  78. global _thread_lock_enabled
  79. _thread_lock_enabled = False
  80. def execute_handler(name, handler, event, d):
  81. event.data = d
  82. addedd = False
  83. if 'd' not in builtins:
  84. builtins['d'] = d
  85. addedd = True
  86. try:
  87. ret = handler(event)
  88. except (bb.parse.SkipRecipe, bb.BBHandledException):
  89. raise
  90. except Exception:
  91. etype, value, tb = sys.exc_info()
  92. logger.error("Execution of event handler '%s' failed" % name,
  93. exc_info=(etype, value, tb.tb_next))
  94. raise
  95. except SystemExit as exc:
  96. if exc.code != 0:
  97. logger.error("Execution of event handler '%s' failed" % name)
  98. raise
  99. finally:
  100. del event.data
  101. if addedd:
  102. del builtins['d']
  103. def fire_class_handlers(event, d):
  104. if isinstance(event, logging.LogRecord):
  105. return
  106. eid = str(event.__class__)[8:-2]
  107. evt_hmap = _event_handler_map.get(eid, {})
  108. for name, handler in list(_handlers.items()):
  109. if name in _catchall_handlers or name in evt_hmap:
  110. if _eventfilter:
  111. if not _eventfilter(name, handler, event, d):
  112. continue
  113. execute_handler(name, handler, event, d)
  114. ui_queue = []
  115. @atexit.register
  116. def print_ui_queue():
  117. """If we're exiting before a UI has been spawned, display any queued
  118. LogRecords to the console."""
  119. logger = logging.getLogger("BitBake")
  120. if not _uiready:
  121. from bb.msg import BBLogFormatter
  122. stdout = logging.StreamHandler(sys.stdout)
  123. stderr = logging.StreamHandler(sys.stderr)
  124. formatter = BBLogFormatter("%(levelname)s: %(message)s")
  125. stdout.setFormatter(formatter)
  126. stderr.setFormatter(formatter)
  127. # First check to see if we have any proper messages
  128. msgprint = False
  129. for event in ui_queue[:]:
  130. if isinstance(event, logging.LogRecord):
  131. if event.levelno > logging.DEBUG:
  132. if event.levelno >= logging.WARNING:
  133. logger.addHandler(stderr)
  134. else:
  135. logger.addHandler(stdout)
  136. logger.handle(event)
  137. msgprint = True
  138. if msgprint:
  139. return
  140. # Nope, so just print all of the messages we have (including debug messages)
  141. logger.addHandler(stdout)
  142. for event in ui_queue[:]:
  143. if isinstance(event, logging.LogRecord):
  144. logger.handle(event)
  145. def fire_ui_handlers(event, d):
  146. global _thread_lock
  147. global _thread_lock_enabled
  148. if not _uiready:
  149. # No UI handlers registered yet, queue up the messages
  150. ui_queue.append(event)
  151. return
  152. if _thread_lock_enabled:
  153. _thread_lock.acquire()
  154. errors = []
  155. for h in _ui_handlers:
  156. #print "Sending event %s" % event
  157. try:
  158. if not _ui_logfilters[h].filter(event):
  159. continue
  160. # We use pickle here since it better handles object instances
  161. # which xmlrpc's marshaller does not. Events *must* be serializable
  162. # by pickle.
  163. if hasattr(_ui_handlers[h].event, "sendpickle"):
  164. _ui_handlers[h].event.sendpickle((pickle.dumps(event)))
  165. else:
  166. _ui_handlers[h].event.send(event)
  167. except:
  168. errors.append(h)
  169. for h in errors:
  170. del _ui_handlers[h]
  171. if _thread_lock_enabled:
  172. _thread_lock.release()
  173. def fire(event, d):
  174. """Fire off an Event"""
  175. # We can fire class handlers in the worker process context and this is
  176. # desired so they get the task based datastore.
  177. # UI handlers need to be fired in the server context so we defer this. They
  178. # don't have a datastore so the datastore context isn't a problem.
  179. fire_class_handlers(event, d)
  180. if worker_fire:
  181. worker_fire(event, d)
  182. else:
  183. # If messages have been queued up, clear the queue
  184. global _uiready, ui_queue
  185. if _uiready and ui_queue:
  186. for queue_event in ui_queue:
  187. fire_ui_handlers(queue_event, d)
  188. ui_queue = []
  189. fire_ui_handlers(event, d)
  190. def fire_from_worker(event, d):
  191. fire_ui_handlers(event, d)
  192. noop = lambda _: None
  193. def register(name, handler, mask=None, filename=None, lineno=None):
  194. """Register an Event handler"""
  195. # already registered
  196. if name in _handlers:
  197. return AlreadyRegistered
  198. if handler is not None:
  199. # handle string containing python code
  200. if isinstance(handler, str):
  201. tmp = "def %s(e):\n%s" % (name, handler)
  202. try:
  203. code = bb.methodpool.compile_cache(tmp)
  204. if not code:
  205. if filename is None:
  206. filename = "%s(e)" % name
  207. code = compile(tmp, filename, "exec", ast.PyCF_ONLY_AST)
  208. if lineno is not None:
  209. ast.increment_lineno(code, lineno-1)
  210. code = compile(code, filename, "exec")
  211. bb.methodpool.compile_cache_add(tmp, code)
  212. except SyntaxError:
  213. logger.error("Unable to register event handler '%s':\n%s", name,
  214. ''.join(traceback.format_exc(limit=0)))
  215. _handlers[name] = noop
  216. return
  217. env = {}
  218. bb.utils.better_exec(code, env)
  219. func = bb.utils.better_eval(name, env)
  220. _handlers[name] = func
  221. else:
  222. _handlers[name] = handler
  223. if not mask or '*' in mask:
  224. _catchall_handlers[name] = True
  225. else:
  226. for m in mask:
  227. if _event_handler_map.get(m, None) is None:
  228. _event_handler_map[m] = {}
  229. _event_handler_map[m][name] = True
  230. return Registered
  231. def remove(name, handler):
  232. """Remove an Event handler"""
  233. _handlers.pop(name)
  234. if name in _catchall_handlers:
  235. _catchall_handlers.pop(name)
  236. for event in _event_handler_map.keys():
  237. if name in _event_handler_map[event]:
  238. _event_handler_map[event].pop(name)
  239. def get_handlers():
  240. return _handlers
  241. def set_handlers(handlers):
  242. global _handlers
  243. _handlers = handlers
  244. def set_eventfilter(func):
  245. global _eventfilter
  246. _eventfilter = func
  247. def register_UIHhandler(handler, mainui=False):
  248. bb.event._ui_handler_seq = bb.event._ui_handler_seq + 1
  249. _ui_handlers[_ui_handler_seq] = handler
  250. level, debug_domains = bb.msg.constructLogOptions()
  251. _ui_logfilters[_ui_handler_seq] = UIEventFilter(level, debug_domains)
  252. if mainui:
  253. global _uiready
  254. _uiready = _ui_handler_seq
  255. return _ui_handler_seq
  256. def unregister_UIHhandler(handlerNum, mainui=False):
  257. if mainui:
  258. global _uiready
  259. _uiready = False
  260. if handlerNum in _ui_handlers:
  261. del _ui_handlers[handlerNum]
  262. return
  263. def get_uihandler():
  264. if _uiready is False:
  265. return None
  266. return _uiready
  267. # Class to allow filtering of events and specific filtering of LogRecords *before* we put them over the IPC
  268. class UIEventFilter(object):
  269. def __init__(self, level, debug_domains):
  270. self.update(None, level, debug_domains)
  271. def update(self, eventmask, level, debug_domains):
  272. self.eventmask = eventmask
  273. self.stdlevel = level
  274. self.debug_domains = debug_domains
  275. def filter(self, event):
  276. if isinstance(event, logging.LogRecord):
  277. if event.levelno >= self.stdlevel:
  278. return True
  279. if event.name in self.debug_domains and event.levelno >= self.debug_domains[event.name]:
  280. return True
  281. return False
  282. eid = str(event.__class__)[8:-2]
  283. if self.eventmask and eid not in self.eventmask:
  284. return False
  285. return True
  286. def set_UIHmask(handlerNum, level, debug_domains, mask):
  287. if not handlerNum in _ui_handlers:
  288. return False
  289. if '*' in mask:
  290. _ui_logfilters[handlerNum].update(None, level, debug_domains)
  291. else:
  292. _ui_logfilters[handlerNum].update(mask, level, debug_domains)
  293. return True
  294. def getName(e):
  295. """Returns the name of a class or class instance"""
  296. if getattr(e, "__name__", None) == None:
  297. return e.__class__.__name__
  298. else:
  299. return e.__name__
  300. class OperationStarted(Event):
  301. """An operation has begun"""
  302. def __init__(self, msg = "Operation Started"):
  303. Event.__init__(self)
  304. self.msg = msg
  305. class OperationCompleted(Event):
  306. """An operation has completed"""
  307. def __init__(self, total, msg = "Operation Completed"):
  308. Event.__init__(self)
  309. self.total = total
  310. self.msg = msg
  311. class OperationProgress(Event):
  312. """An operation is in progress"""
  313. def __init__(self, current, total, msg = "Operation in Progress"):
  314. Event.__init__(self)
  315. self.current = current
  316. self.total = total
  317. self.msg = msg + ": %s/%s" % (current, total);
  318. class ConfigParsed(Event):
  319. """Configuration Parsing Complete"""
  320. class MultiConfigParsed(Event):
  321. """Multi-Config Parsing Complete"""
  322. def __init__(self, mcdata):
  323. self.mcdata = mcdata
  324. Event.__init__(self)
  325. class RecipeEvent(Event):
  326. def __init__(self, fn):
  327. self.fn = fn
  328. Event.__init__(self)
  329. class RecipePreFinalise(RecipeEvent):
  330. """ Recipe Parsing Complete but not yet finialised"""
  331. class RecipeTaskPreProcess(RecipeEvent):
  332. """
  333. Recipe Tasks about to be finalised
  334. The list of tasks should be final at this point and handlers
  335. are only able to change interdependencies
  336. """
  337. def __init__(self, fn, tasklist):
  338. self.fn = fn
  339. self.tasklist = tasklist
  340. Event.__init__(self)
  341. class RecipeParsed(RecipeEvent):
  342. """ Recipe Parsing Complete """
  343. class StampUpdate(Event):
  344. """Trigger for any adjustment of the stamp files to happen"""
  345. def __init__(self, targets, stampfns):
  346. self._targets = targets
  347. self._stampfns = stampfns
  348. Event.__init__(self)
  349. def getStampPrefix(self):
  350. return self._stampfns
  351. def getTargets(self):
  352. return self._targets
  353. stampPrefix = property(getStampPrefix)
  354. targets = property(getTargets)
  355. class BuildBase(Event):
  356. """Base class for bitbake build events"""
  357. def __init__(self, n, p, failures = 0):
  358. self._name = n
  359. self._pkgs = p
  360. Event.__init__(self)
  361. self._failures = failures
  362. def getPkgs(self):
  363. return self._pkgs
  364. def setPkgs(self, pkgs):
  365. self._pkgs = pkgs
  366. def getName(self):
  367. return self._name
  368. def setName(self, name):
  369. self._name = name
  370. def getCfg(self):
  371. return self.data
  372. def setCfg(self, cfg):
  373. self.data = cfg
  374. def getFailures(self):
  375. """
  376. Return the number of failed packages
  377. """
  378. return self._failures
  379. pkgs = property(getPkgs, setPkgs, None, "pkgs property")
  380. name = property(getName, setName, None, "name property")
  381. cfg = property(getCfg, setCfg, None, "cfg property")
  382. class BuildInit(BuildBase):
  383. """buildFile or buildTargets was invoked"""
  384. def __init__(self, p=[]):
  385. name = None
  386. BuildBase.__init__(self, name, p)
  387. class BuildStarted(BuildBase, OperationStarted):
  388. """Event when builds start"""
  389. def __init__(self, n, p, failures = 0):
  390. OperationStarted.__init__(self, "Building Started")
  391. BuildBase.__init__(self, n, p, failures)
  392. class BuildCompleted(BuildBase, OperationCompleted):
  393. """Event when builds have completed"""
  394. def __init__(self, total, n, p, failures=0, interrupted=0):
  395. if not failures:
  396. OperationCompleted.__init__(self, total, "Building Succeeded")
  397. else:
  398. OperationCompleted.__init__(self, total, "Building Failed")
  399. self._interrupted = interrupted
  400. BuildBase.__init__(self, n, p, failures)
  401. class DiskFull(Event):
  402. """Disk full case build aborted"""
  403. def __init__(self, dev, type, freespace, mountpoint):
  404. Event.__init__(self)
  405. self._dev = dev
  406. self._type = type
  407. self._free = freespace
  408. self._mountpoint = mountpoint
  409. class DiskUsageSample:
  410. def __init__(self, available_bytes, free_bytes, total_bytes):
  411. # Number of bytes available to non-root processes.
  412. self.available_bytes = available_bytes
  413. # Number of bytes available to root processes.
  414. self.free_bytes = free_bytes
  415. # Total capacity of the volume.
  416. self.total_bytes = total_bytes
  417. class MonitorDiskEvent(Event):
  418. """If BB_DISKMON_DIRS is set, then this event gets triggered each time disk space is checked.
  419. Provides information about devices that are getting monitored."""
  420. def __init__(self, disk_usage):
  421. Event.__init__(self)
  422. # hash of device root path -> DiskUsageSample
  423. self.disk_usage = disk_usage
  424. class NoProvider(Event):
  425. """No Provider for an Event"""
  426. def __init__(self, item, runtime=False, dependees=None, reasons=None, close_matches=None):
  427. Event.__init__(self)
  428. self._item = item
  429. self._runtime = runtime
  430. self._dependees = dependees
  431. self._reasons = reasons
  432. self._close_matches = close_matches
  433. def getItem(self):
  434. return self._item
  435. def isRuntime(self):
  436. return self._runtime
  437. def __str__(self):
  438. msg = ''
  439. if self._runtime:
  440. r = "R"
  441. else:
  442. r = ""
  443. extra = ''
  444. if not self._reasons:
  445. if self._close_matches:
  446. extra = ". Close matches:\n %s" % '\n '.join(self._close_matches)
  447. if self._dependees:
  448. msg = "Nothing %sPROVIDES '%s' (but %s %sDEPENDS on or otherwise requires it)%s" % (r, self._item, ", ".join(self._dependees), r, extra)
  449. else:
  450. msg = "Nothing %sPROVIDES '%s'%s" % (r, self._item, extra)
  451. if self._reasons:
  452. for reason in self._reasons:
  453. msg += '\n' + reason
  454. return msg
  455. class MultipleProviders(Event):
  456. """Multiple Providers"""
  457. def __init__(self, item, candidates, runtime = False):
  458. Event.__init__(self)
  459. self._item = item
  460. self._candidates = candidates
  461. self._is_runtime = runtime
  462. def isRuntime(self):
  463. """
  464. Is this a runtime issue?
  465. """
  466. return self._is_runtime
  467. def getItem(self):
  468. """
  469. The name for the to be build item
  470. """
  471. return self._item
  472. def getCandidates(self):
  473. """
  474. Get the possible Candidates for a PROVIDER.
  475. """
  476. return self._candidates
  477. def __str__(self):
  478. msg = "Multiple providers are available for %s%s (%s)" % (self._is_runtime and "runtime " or "",
  479. self._item,
  480. ", ".join(self._candidates))
  481. rtime = ""
  482. if self._is_runtime:
  483. rtime = "R"
  484. msg += "\nConsider defining a PREFERRED_%sPROVIDER entry to match %s" % (rtime, self._item)
  485. return msg
  486. class ParseStarted(OperationStarted):
  487. """Recipe parsing for the runqueue has begun"""
  488. def __init__(self, total):
  489. OperationStarted.__init__(self, "Recipe parsing Started")
  490. self.total = total
  491. class ParseCompleted(OperationCompleted):
  492. """Recipe parsing for the runqueue has completed"""
  493. def __init__(self, cached, parsed, skipped, masked, virtuals, errors, total):
  494. OperationCompleted.__init__(self, total, "Recipe parsing Completed")
  495. self.cached = cached
  496. self.parsed = parsed
  497. self.skipped = skipped
  498. self.virtuals = virtuals
  499. self.masked = masked
  500. self.errors = errors
  501. self.sofar = cached + parsed
  502. class ParseProgress(OperationProgress):
  503. """Recipe parsing progress"""
  504. def __init__(self, current, total):
  505. OperationProgress.__init__(self, current, total, "Recipe parsing")
  506. class CacheLoadStarted(OperationStarted):
  507. """Loading of the dependency cache has begun"""
  508. def __init__(self, total):
  509. OperationStarted.__init__(self, "Loading cache Started")
  510. self.total = total
  511. class CacheLoadProgress(OperationProgress):
  512. """Cache loading progress"""
  513. def __init__(self, current, total):
  514. OperationProgress.__init__(self, current, total, "Loading cache")
  515. class CacheLoadCompleted(OperationCompleted):
  516. """Cache loading is complete"""
  517. def __init__(self, total, num_entries):
  518. OperationCompleted.__init__(self, total, "Loading cache Completed")
  519. self.num_entries = num_entries
  520. class TreeDataPreparationStarted(OperationStarted):
  521. """Tree data preparation started"""
  522. def __init__(self):
  523. OperationStarted.__init__(self, "Preparing tree data Started")
  524. class TreeDataPreparationProgress(OperationProgress):
  525. """Tree data preparation is in progress"""
  526. def __init__(self, current, total):
  527. OperationProgress.__init__(self, current, total, "Preparing tree data")
  528. class TreeDataPreparationCompleted(OperationCompleted):
  529. """Tree data preparation completed"""
  530. def __init__(self, total):
  531. OperationCompleted.__init__(self, total, "Preparing tree data Completed")
  532. class DepTreeGenerated(Event):
  533. """
  534. Event when a dependency tree has been generated
  535. """
  536. def __init__(self, depgraph):
  537. Event.__init__(self)
  538. self._depgraph = depgraph
  539. class TargetsTreeGenerated(Event):
  540. """
  541. Event when a set of buildable targets has been generated
  542. """
  543. def __init__(self, model):
  544. Event.__init__(self)
  545. self._model = model
  546. class ReachableStamps(Event):
  547. """
  548. An event listing all stamps reachable after parsing
  549. which the metadata may use to clean up stale data
  550. """
  551. def __init__(self, stamps):
  552. Event.__init__(self)
  553. self.stamps = stamps
  554. class FilesMatchingFound(Event):
  555. """
  556. Event when a list of files matching the supplied pattern has
  557. been generated
  558. """
  559. def __init__(self, pattern, matches):
  560. Event.__init__(self)
  561. self._pattern = pattern
  562. self._matches = matches
  563. class ConfigFilesFound(Event):
  564. """
  565. Event when a list of appropriate config files has been generated
  566. """
  567. def __init__(self, variable, values):
  568. Event.__init__(self)
  569. self._variable = variable
  570. self._values = values
  571. class ConfigFilePathFound(Event):
  572. """
  573. Event when a path for a config file has been found
  574. """
  575. def __init__(self, path):
  576. Event.__init__(self)
  577. self._path = path
  578. class MsgBase(Event):
  579. """Base class for messages"""
  580. def __init__(self, msg):
  581. self._message = msg
  582. Event.__init__(self)
  583. class MsgDebug(MsgBase):
  584. """Debug Message"""
  585. class MsgNote(MsgBase):
  586. """Note Message"""
  587. class MsgWarn(MsgBase):
  588. """Warning Message"""
  589. class MsgError(MsgBase):
  590. """Error Message"""
  591. class MsgFatal(MsgBase):
  592. """Fatal Message"""
  593. class MsgPlain(MsgBase):
  594. """General output"""
  595. class LogExecTTY(Event):
  596. """Send event containing program to spawn on tty of the logger"""
  597. def __init__(self, msg, prog, sleep_delay, retries):
  598. Event.__init__(self)
  599. self.msg = msg
  600. self.prog = prog
  601. self.sleep_delay = sleep_delay
  602. self.retries = retries
  603. class LogHandler(logging.Handler):
  604. """Dispatch logging messages as bitbake events"""
  605. def emit(self, record):
  606. if record.exc_info:
  607. etype, value, tb = record.exc_info
  608. if hasattr(tb, 'tb_next'):
  609. tb = list(bb.exceptions.extract_traceback(tb, context=3))
  610. # Need to turn the value into something the logging system can pickle
  611. record.bb_exc_info = (etype, value, tb)
  612. record.bb_exc_formatted = bb.exceptions.format_exception(etype, value, tb, limit=5)
  613. value = str(value)
  614. record.exc_info = None
  615. fire(record, None)
  616. def filter(self, record):
  617. record.taskpid = worker_pid
  618. return True
  619. class MetadataEvent(Event):
  620. """
  621. Generic event that target for OE-Core classes
  622. to report information during asynchrous execution
  623. """
  624. def __init__(self, eventtype, eventdata):
  625. Event.__init__(self)
  626. self.type = eventtype
  627. self._localdata = eventdata
  628. class ProcessStarted(Event):
  629. """
  630. Generic process started event (usually part of the initial startup)
  631. where further progress events will be delivered
  632. """
  633. def __init__(self, processname, total):
  634. Event.__init__(self)
  635. self.processname = processname
  636. self.total = total
  637. class ProcessProgress(Event):
  638. """
  639. Generic process progress event (usually part of the initial startup)
  640. """
  641. def __init__(self, processname, progress):
  642. Event.__init__(self)
  643. self.processname = processname
  644. self.progress = progress
  645. class ProcessFinished(Event):
  646. """
  647. Generic process finished event (usually part of the initial startup)
  648. """
  649. def __init__(self, processname):
  650. Event.__init__(self)
  651. self.processname = processname
  652. class SanityCheck(Event):
  653. """
  654. Event to run sanity checks, either raise errors or generate events as return status.
  655. """
  656. def __init__(self, generateevents = True):
  657. Event.__init__(self)
  658. self.generateevents = generateevents
  659. class SanityCheckPassed(Event):
  660. """
  661. Event to indicate sanity check has passed
  662. """
  663. class SanityCheckFailed(Event):
  664. """
  665. Event to indicate sanity check has failed
  666. """
  667. def __init__(self, msg, network_error=False):
  668. Event.__init__(self)
  669. self._msg = msg
  670. self._network_error = network_error
  671. class NetworkTest(Event):
  672. """
  673. Event to run network connectivity tests, either raise errors or generate events as return status.
  674. """
  675. def __init__(self, generateevents = True):
  676. Event.__init__(self)
  677. self.generateevents = generateevents
  678. class NetworkTestPassed(Event):
  679. """
  680. Event to indicate network test has passed
  681. """
  682. class NetworkTestFailed(Event):
  683. """
  684. Event to indicate network test has failed
  685. """