proc.py 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724
  1. import warnings
  2. warnings.warn("The proc module is deprecated! Please use the greenthread "
  3. "module, or any of the many other Eventlet cross-coroutine "
  4. "primitives, instead.",
  5. DeprecationWarning, stacklevel=2)
  6. """
  7. This module provides means to spawn, kill and link coroutines. Linking means
  8. subscribing to the coroutine's result, either in form of return value or
  9. unhandled exception.
  10. To create a linkable coroutine use spawn function provided by this module:
  11. >>> def demofunc(x, y):
  12. ... return x / y
  13. >>> p = spawn(demofunc, 6, 2)
  14. The return value of :func:`spawn` is an instance of :class:`Proc` class that
  15. you can "link":
  16. * ``p.link(obj)`` - notify *obj* when the coroutine is finished
  17. What "notify" means here depends on the type of *obj*: a callable is simply
  18. called, an :class:`~eventlet.coros.Event` or a :class:`~eventlet.coros.queue`
  19. is notified using ``send``/``send_exception`` methods and if *obj* is another
  20. greenlet it's killed with :class:`LinkedExited` exception.
  21. Here's an example:
  22. >>> event = coros.Event()
  23. >>> _ = p.link(event)
  24. >>> event.wait()
  25. 3
  26. Now, even though *p* is finished it's still possible to link it. In this
  27. case the notification is performed immediatelly:
  28. >>> try:
  29. ... p.link()
  30. ... except LinkedCompleted:
  31. ... print 'LinkedCompleted'
  32. LinkedCompleted
  33. (Without an argument, the link is created to the current greenlet)
  34. There are also :meth:`~eventlet.proc.Source.link_value` and
  35. :func:`link_exception` methods that only deliver a return value and an
  36. unhandled exception respectively (plain :meth:`~eventlet.proc.Source.link`
  37. delivers both). Suppose we want to spawn a greenlet to do an important part of
  38. the task; if it fails then there's no way to complete the task so the parent
  39. must fail as well; :meth:`~eventlet.proc.Source.link_exception` is useful here:
  40. >>> p = spawn(demofunc, 1, 0)
  41. >>> _ = p.link_exception()
  42. >>> try:
  43. ... api.sleep(1)
  44. ... except LinkedFailed:
  45. ... print 'LinkedFailed'
  46. LinkedFailed
  47. One application of linking is :func:`waitall` function: link to a bunch of
  48. coroutines and wait for all them to complete. Such a function is provided by
  49. this module.
  50. """
  51. import sys
  52. from eventlet import api, coros, hubs
  53. __all__ = ['LinkedExited',
  54. 'LinkedFailed',
  55. 'LinkedCompleted',
  56. 'LinkedKilled',
  57. 'ProcExit',
  58. 'Link',
  59. 'waitall',
  60. 'killall',
  61. 'Source',
  62. 'Proc',
  63. 'spawn',
  64. 'spawn_link',
  65. 'spawn_link_value',
  66. 'spawn_link_exception']
  67. class LinkedExited(Exception):
  68. """Raised when a linked proc exits"""
  69. msg = "%r exited"
  70. def __init__(self, name=None, msg=None):
  71. self.name = name
  72. if msg is None:
  73. msg = self.msg % self.name
  74. Exception.__init__(self, msg)
  75. class LinkedCompleted(LinkedExited):
  76. """Raised when a linked proc finishes the execution cleanly"""
  77. msg = "%r completed successfully"
  78. class LinkedFailed(LinkedExited):
  79. """Raised when a linked proc dies because of unhandled exception"""
  80. msg = "%r failed with %s"
  81. def __init__(self, name, typ, value=None, tb=None):
  82. msg = self.msg % (name, typ.__name__)
  83. LinkedExited.__init__(self, name, msg)
  84. class LinkedKilled(LinkedFailed):
  85. """Raised when a linked proc dies because of unhandled GreenletExit
  86. (i.e. it was killed)
  87. """
  88. msg = """%r was killed with %s"""
  89. def getLinkedFailed(name, typ, value=None, tb=None):
  90. if issubclass(typ, api.GreenletExit):
  91. return LinkedKilled(name, typ, value, tb)
  92. return LinkedFailed(name, typ, value, tb)
  93. class ProcExit(api.GreenletExit):
  94. """Raised when this proc is killed."""
  95. class Link(object):
  96. """
  97. A link to a greenlet, triggered when the greenlet exits.
  98. """
  99. def __init__(self, listener):
  100. self.listener = listener
  101. def cancel(self):
  102. self.listener = None
  103. def __enter__(self):
  104. pass
  105. def __exit__(self, *args):
  106. self.cancel()
  107. class LinkToEvent(Link):
  108. def __call__(self, source):
  109. if self.listener is None:
  110. return
  111. if source.has_value():
  112. self.listener.send(source.value)
  113. else:
  114. self.listener.send_exception(*source.exc_info())
  115. class LinkToGreenlet(Link):
  116. def __call__(self, source):
  117. if source.has_value():
  118. self.listener.throw(LinkedCompleted(source.name))
  119. else:
  120. self.listener.throw(getLinkedFailed(source.name, *source.exc_info()))
  121. class LinkToCallable(Link):
  122. def __call__(self, source):
  123. self.listener(source)
  124. def waitall(lst, trap_errors=False, queue=None):
  125. if queue is None:
  126. queue = coros.queue()
  127. index = -1
  128. for (index, linkable) in enumerate(lst):
  129. linkable.link(decorate_send(queue, index))
  130. len = index + 1
  131. results = [None] * len
  132. count = 0
  133. while count < len:
  134. try:
  135. index, value = queue.wait()
  136. except Exception:
  137. if not trap_errors:
  138. raise
  139. else:
  140. results[index] = value
  141. count += 1
  142. return results
  143. class decorate_send(object):
  144. def __init__(self, event, tag):
  145. self._event = event
  146. self._tag = tag
  147. def __repr__(self):
  148. params = (type(self).__name__, self._tag, self._event)
  149. return '<%s tag=%r event=%r>' % params
  150. def __getattr__(self, name):
  151. assert name != '_event'
  152. return getattr(self._event, name)
  153. def send(self, value):
  154. self._event.send((self._tag, value))
  155. def killall(procs, *throw_args, **kwargs):
  156. if not throw_args:
  157. throw_args = (ProcExit, )
  158. wait = kwargs.pop('wait', False)
  159. if kwargs:
  160. raise TypeError('Invalid keyword argument for proc.killall(): %s' % ', '.join(kwargs.keys()))
  161. for g in procs:
  162. if not g.dead:
  163. hubs.get_hub().schedule_call_global(0, g.throw, *throw_args)
  164. if wait and api.getcurrent() is not hubs.get_hub().greenlet:
  165. api.sleep(0)
  166. class NotUsed(object):
  167. def __str__(self):
  168. return '<Source instance does not hold a value or an exception>'
  169. __repr__ = __str__
  170. _NOT_USED = NotUsed()
  171. def spawn_greenlet(function, *args):
  172. """Create a new greenlet that will run ``function(*args)``.
  173. The current greenlet won't be unscheduled. Keyword arguments aren't
  174. supported (limitation of greenlet), use :func:`spawn` to work around that.
  175. """
  176. g = api.Greenlet(function)
  177. g.parent = hubs.get_hub().greenlet
  178. hubs.get_hub().schedule_call_global(0, g.switch, *args)
  179. return g
  180. class Source(object):
  181. """Maintain a set of links to the listeners. Delegate the sent value or
  182. the exception to all of them.
  183. To set up a link, use :meth:`link_value`, :meth:`link_exception` or
  184. :meth:`link` method. The latter establishes both "value" and "exception"
  185. link. It is possible to link to events, queues, greenlets and callables.
  186. >>> source = Source()
  187. >>> event = coros.Event()
  188. >>> _ = source.link(event)
  189. Once source's :meth:`send` or :meth:`send_exception` method is called, all
  190. the listeners with the right type of link will be notified ("right type"
  191. means that exceptions won't be delivered to "value" links and values won't
  192. be delivered to "exception" links). Once link has been fired it is removed.
  193. Notifying listeners is performed in the **mainloop** greenlet. Under the
  194. hood notifying a link means executing a callback, see :class:`Link` class
  195. for details. Notification *must not* attempt to switch to the hub, i.e.
  196. call any blocking functions.
  197. >>> source.send('hello')
  198. >>> event.wait()
  199. 'hello'
  200. Any error happened while sending will be logged as a regular unhandled
  201. exception. This won't prevent other links from being fired.
  202. There 3 kinds of listeners supported:
  203. 1. If *listener* is a greenlet (regardless if it's a raw greenlet or an
  204. extension like :class:`Proc`), a subclass of :class:`LinkedExited`
  205. exception is raised in it.
  206. 2. If *listener* is something with send/send_exception methods (event,
  207. queue, :class:`Source` but not :class:`Proc`) the relevant method is
  208. called.
  209. 3. If *listener* is a callable, it is called with 1 argument (the result)
  210. for "value" links and with 3 arguments ``(typ, value, tb)`` for
  211. "exception" links.
  212. """
  213. def __init__(self, name=None):
  214. self.name = name
  215. self._value_links = {}
  216. self._exception_links = {}
  217. self.value = _NOT_USED
  218. self._exc = None
  219. def _repr_helper(self):
  220. result = []
  221. result.append(repr(self.name))
  222. if self.value is not _NOT_USED:
  223. if self._exc is None:
  224. res = repr(self.value)
  225. if len(res)>50:
  226. res = res[:50]+'...'
  227. result.append('result=%s' % res)
  228. else:
  229. result.append('raised=%s' % (self._exc, ))
  230. result.append('{%s:%s}' % (len(self._value_links), len(self._exception_links)))
  231. return result
  232. def __repr__(self):
  233. klass = type(self).__name__
  234. return '<%s at %s %s>' % (klass, hex(id(self)), ' '.join(self._repr_helper()))
  235. def ready(self):
  236. return self.value is not _NOT_USED
  237. def has_value(self):
  238. return self.value is not _NOT_USED and self._exc is None
  239. def has_exception(self):
  240. return self.value is not _NOT_USED and self._exc is not None
  241. def exc_info(self):
  242. if not self._exc:
  243. return (None, None, None)
  244. elif len(self._exc)==3:
  245. return self._exc
  246. elif len(self._exc)==1:
  247. if isinstance(self._exc[0], type):
  248. return self._exc[0], None, None
  249. else:
  250. return self._exc[0].__class__, self._exc[0], None
  251. elif len(self._exc)==2:
  252. return self._exc[0], self._exc[1], None
  253. else:
  254. return self._exc
  255. def link_value(self, listener=None, link=None):
  256. if self.ready() and self._exc is not None:
  257. return
  258. if listener is None:
  259. listener = api.getcurrent()
  260. if link is None:
  261. link = self.getLink(listener)
  262. if self.ready() and listener is api.getcurrent():
  263. link(self)
  264. else:
  265. self._value_links[listener] = link
  266. if self.value is not _NOT_USED:
  267. self._start_send()
  268. return link
  269. def link_exception(self, listener=None, link=None):
  270. if self.value is not _NOT_USED and self._exc is None:
  271. return
  272. if listener is None:
  273. listener = api.getcurrent()
  274. if link is None:
  275. link = self.getLink(listener)
  276. if self.ready() and listener is api.getcurrent():
  277. link(self)
  278. else:
  279. self._exception_links[listener] = link
  280. if self.value is not _NOT_USED:
  281. self._start_send_exception()
  282. return link
  283. def link(self, listener=None, link=None):
  284. if listener is None:
  285. listener = api.getcurrent()
  286. if link is None:
  287. link = self.getLink(listener)
  288. if self.ready() and listener is api.getcurrent():
  289. if self._exc is None:
  290. link(self)
  291. else:
  292. link(self)
  293. else:
  294. self._value_links[listener] = link
  295. self._exception_links[listener] = link
  296. if self.value is not _NOT_USED:
  297. if self._exc is None:
  298. self._start_send()
  299. else:
  300. self._start_send_exception()
  301. return link
  302. def unlink(self, listener=None):
  303. if listener is None:
  304. listener = api.getcurrent()
  305. self._value_links.pop(listener, None)
  306. self._exception_links.pop(listener, None)
  307. @staticmethod
  308. def getLink(listener):
  309. if hasattr(listener, 'throw'):
  310. return LinkToGreenlet(listener)
  311. if hasattr(listener, 'send'):
  312. return LinkToEvent(listener)
  313. elif hasattr(listener, '__call__'):
  314. return LinkToCallable(listener)
  315. else:
  316. raise TypeError("Don't know how to link to %r" % (listener, ))
  317. def send(self, value):
  318. assert not self.ready(), "%s has been fired already" % self
  319. self.value = value
  320. self._exc = None
  321. self._start_send()
  322. def _start_send(self):
  323. hubs.get_hub().schedule_call_global(0, self._do_send, self._value_links.items(), self._value_links)
  324. def send_exception(self, *throw_args):
  325. assert not self.ready(), "%s has been fired already" % self
  326. self.value = None
  327. self._exc = throw_args
  328. self._start_send_exception()
  329. def _start_send_exception(self):
  330. hubs.get_hub().schedule_call_global(0, self._do_send, self._exception_links.items(), self._exception_links)
  331. def _do_send(self, links, consult):
  332. while links:
  333. listener, link = links.pop()
  334. try:
  335. if listener in consult:
  336. try:
  337. link(self)
  338. finally:
  339. consult.pop(listener, None)
  340. except:
  341. hubs.get_hub().schedule_call_global(0, self._do_send, links, consult)
  342. raise
  343. def wait(self, timeout=None, *throw_args):
  344. """Wait until :meth:`send` or :meth:`send_exception` is called or
  345. *timeout* has expired. Return the argument of :meth:`send` or raise the
  346. argument of :meth:`send_exception`. If *timeout* has expired, ``None``
  347. is returned.
  348. The arguments, when provided, specify how many seconds to wait and what
  349. to do when *timeout* has expired. They are treated the same way as
  350. :func:`~eventlet.api.timeout` treats them.
  351. """
  352. if self.value is not _NOT_USED:
  353. if self._exc is None:
  354. return self.value
  355. else:
  356. api.getcurrent().throw(*self._exc)
  357. if timeout is not None:
  358. timer = api.timeout(timeout, *throw_args)
  359. timer.__enter__()
  360. if timeout==0:
  361. if timer.__exit__(None, None, None):
  362. return
  363. else:
  364. try:
  365. api.getcurrent().throw(*timer.throw_args)
  366. except:
  367. if not timer.__exit__(*sys.exc_info()):
  368. raise
  369. return
  370. EXC = True
  371. try:
  372. try:
  373. waiter = Waiter()
  374. self.link(waiter)
  375. try:
  376. return waiter.wait()
  377. finally:
  378. self.unlink(waiter)
  379. except:
  380. EXC = False
  381. if timeout is None or not timer.__exit__(*sys.exc_info()):
  382. raise
  383. finally:
  384. if timeout is not None and EXC:
  385. timer.__exit__(None, None, None)
  386. class Waiter(object):
  387. def __init__(self):
  388. self.greenlet = None
  389. def send(self, value):
  390. """Wake up the greenlet that is calling wait() currently (if there is one).
  391. Can only be called from get_hub().greenlet.
  392. """
  393. assert api.getcurrent() is hubs.get_hub().greenlet
  394. if self.greenlet is not None:
  395. self.greenlet.switch(value)
  396. def send_exception(self, *throw_args):
  397. """Make greenlet calling wait() wake up (if there is a wait()).
  398. Can only be called from get_hub().greenlet.
  399. """
  400. assert api.getcurrent() is hubs.get_hub().greenlet
  401. if self.greenlet is not None:
  402. self.greenlet.throw(*throw_args)
  403. def wait(self):
  404. """Wait until send or send_exception is called. Return value passed
  405. into send() or raise exception passed into send_exception().
  406. """
  407. assert self.greenlet is None
  408. current = api.getcurrent()
  409. assert current is not hubs.get_hub().greenlet
  410. self.greenlet = current
  411. try:
  412. return hubs.get_hub().switch()
  413. finally:
  414. self.greenlet = None
  415. class Proc(Source):
  416. """A linkable coroutine based on Source.
  417. Upon completion, delivers coroutine's result to the listeners.
  418. """
  419. def __init__(self, name=None):
  420. self.greenlet = None
  421. Source.__init__(self, name)
  422. def _repr_helper(self):
  423. if self.greenlet is not None and self.greenlet.dead:
  424. dead = '(dead)'
  425. else:
  426. dead = ''
  427. return ['%r%s' % (self.greenlet, dead)] + Source._repr_helper(self)
  428. def __repr__(self):
  429. klass = type(self).__name__
  430. return '<%s %s>' % (klass, ' '.join(self._repr_helper()))
  431. def __nonzero__(self):
  432. if self.ready():
  433. # with current _run this does not makes any difference
  434. # still, let keep it there
  435. return False
  436. # otherwise bool(proc) is the same as bool(greenlet)
  437. if self.greenlet is not None:
  438. return bool(self.greenlet)
  439. @property
  440. def dead(self):
  441. return self.ready() or self.greenlet.dead
  442. @classmethod
  443. def spawn(cls, function, *args, **kwargs):
  444. """Return a new :class:`Proc` instance that is scheduled to execute
  445. ``function(*args, **kwargs)`` upon the next hub iteration.
  446. """
  447. proc = cls()
  448. proc.run(function, *args, **kwargs)
  449. return proc
  450. def run(self, function, *args, **kwargs):
  451. """Create a new greenlet to execute ``function(*args, **kwargs)``.
  452. The created greenlet is scheduled to run upon the next hub iteration.
  453. """
  454. assert self.greenlet is None, "'run' can only be called once per instance"
  455. if self.name is None:
  456. self.name = str(function)
  457. self.greenlet = spawn_greenlet(self._run, function, args, kwargs)
  458. def _run(self, function, args, kwargs):
  459. """Internal top level function.
  460. Execute *function* and send its result to the listeners.
  461. """
  462. try:
  463. result = function(*args, **kwargs)
  464. except:
  465. self.send_exception(*sys.exc_info())
  466. raise # let mainloop log the exception
  467. else:
  468. self.send(result)
  469. def throw(self, *throw_args):
  470. """Used internally to raise the exception.
  471. Behaves exactly like greenlet's 'throw' with the exception that
  472. :class:`ProcExit` is raised by default. Do not use this function as it
  473. leaves the current greenlet unscheduled forever. Use :meth:`kill`
  474. method instead.
  475. """
  476. if not self.dead:
  477. if not throw_args:
  478. throw_args = (ProcExit, )
  479. self.greenlet.throw(*throw_args)
  480. def kill(self, *throw_args):
  481. """
  482. Raise an exception in the greenlet. Unschedule the current greenlet so
  483. that this :class:`Proc` can handle the exception (or die).
  484. The exception can be specified with *throw_args*. By default,
  485. :class:`ProcExit` is raised.
  486. """
  487. if not self.dead:
  488. if not throw_args:
  489. throw_args = (ProcExit, )
  490. hubs.get_hub().schedule_call_global(0, self.greenlet.throw, *throw_args)
  491. if api.getcurrent() is not hubs.get_hub().greenlet:
  492. api.sleep(0)
  493. # QQQ maybe Proc should not inherit from Source (because its send() and send_exception()
  494. # QQQ methods are for internal use only)
  495. spawn = Proc.spawn
  496. def spawn_link(function, *args, **kwargs):
  497. p = spawn(function, *args, **kwargs)
  498. p.link()
  499. return p
  500. def spawn_link_value(function, *args, **kwargs):
  501. p = spawn(function, *args, **kwargs)
  502. p.link_value()
  503. return p
  504. def spawn_link_exception(function, *args, **kwargs):
  505. p = spawn(function, *args, **kwargs)
  506. p.link_exception()
  507. return p
  508. class wrap_errors(object):
  509. """Helper to make function return an exception, rather than raise it.
  510. Because every exception that is unhandled by greenlet will be logged by the hub,
  511. it is desirable to prevent non-error exceptions from leaving a greenlet.
  512. This can done with simple try/except construct:
  513. def func1(*args, **kwargs):
  514. try:
  515. return func(*args, **kwargs)
  516. except (A, B, C), ex:
  517. return ex
  518. wrap_errors provides a shortcut to write that in one line:
  519. func1 = wrap_errors((A, B, C), func)
  520. It also preserves __str__ and __repr__ of the original function.
  521. """
  522. def __init__(self, errors, func):
  523. """Make a new function from `func', such that it catches `errors' (an
  524. Exception subclass, or a tuple of Exception subclasses) and return
  525. it as a value.
  526. """
  527. self.errors = errors
  528. self.func = func
  529. def __call__(self, *args, **kwargs):
  530. try:
  531. return self.func(*args, **kwargs)
  532. except self.errors, ex:
  533. return ex
  534. def __str__(self):
  535. return str(self.func)
  536. def __repr__(self):
  537. return repr(self.func)
  538. def __getattr__(self, item):
  539. return getattr(self.func, item)
  540. class RunningProcSet(object):
  541. """
  542. Maintain a set of :class:`Proc` s that are still running, that is,
  543. automatically remove a proc when it's finished. Provide a way to wait/kill
  544. all of them
  545. """
  546. def __init__(self, *args):
  547. self.procs = set(*args)
  548. if args:
  549. for p in self.args[0]:
  550. p.link(lambda p: self.procs.discard(p))
  551. def __len__(self):
  552. return len(self.procs)
  553. def __contains__(self, item):
  554. if isinstance(item, api.Greenlet):
  555. # special case for "api.getcurrent() in running_proc_set" to work
  556. for x in self.procs:
  557. if x.greenlet == item:
  558. return True
  559. else:
  560. return item in self.procs
  561. def __iter__(self):
  562. return iter(self.procs)
  563. def add(self, p):
  564. self.procs.add(p)
  565. p.link(lambda p: self.procs.discard(p))
  566. def spawn(self, func, *args, **kwargs):
  567. p = spawn(func, *args, **kwargs)
  568. self.add(p)
  569. return p
  570. def waitall(self, trap_errors=False):
  571. while self.procs:
  572. waitall(self.procs, trap_errors=trap_errors)
  573. def killall(self, *throw_args, **kwargs):
  574. return killall(self.procs, *throw_args, **kwargs)
  575. class Pool(object):
  576. linkable_class = Proc
  577. def __init__(self, limit):
  578. self.semaphore = coros.Semaphore(limit)
  579. def allocate(self):
  580. self.semaphore.acquire()
  581. g = self.linkable_class()
  582. g.link(lambda *_args: self.semaphore.release())
  583. return g