event.py 25 KB

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