_base.py 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627
  1. ###############################################################################
  2. # Backport concurrent.futures for python2.7/3.3
  3. #
  4. # author: Thomas Moreau and Olivier Grisel
  5. #
  6. # adapted from concurrent/futures/_base.py (17/02/2017)
  7. # * Do not use yield from
  8. # * Use old super syntax
  9. #
  10. # Copyright 2009 Brian Quinlan. All Rights Reserved.
  11. # Licensed to PSF under a Contributor Agreement.
  12. import sys
  13. import time
  14. import logging
  15. import threading
  16. import collections
  17. if sys.version_info[:2] >= (3, 3):
  18. from concurrent.futures import wait, as_completed
  19. from concurrent.futures import TimeoutError, CancelledError
  20. from concurrent.futures import Executor, Future as _BaseFuture
  21. from concurrent.futures import FIRST_EXCEPTION
  22. from concurrent.futures import ALL_COMPLETED, FIRST_COMPLETED
  23. from concurrent.futures._base import LOGGER
  24. from concurrent.futures._base import PENDING, RUNNING, CANCELLED
  25. from concurrent.futures._base import CANCELLED_AND_NOTIFIED, FINISHED
  26. else:
  27. FIRST_COMPLETED = 'FIRST_COMPLETED'
  28. FIRST_EXCEPTION = 'FIRST_EXCEPTION'
  29. ALL_COMPLETED = 'ALL_COMPLETED'
  30. _AS_COMPLETED = '_AS_COMPLETED'
  31. # Possible future states (for internal use by the futures package).
  32. PENDING = 'PENDING'
  33. RUNNING = 'RUNNING'
  34. # The future was cancelled by the user...
  35. CANCELLED = 'CANCELLED'
  36. # ...and _Waiter.add_cancelled() was called by a worker.
  37. CANCELLED_AND_NOTIFIED = 'CANCELLED_AND_NOTIFIED'
  38. FINISHED = 'FINISHED'
  39. _FUTURE_STATES = [
  40. PENDING,
  41. RUNNING,
  42. CANCELLED,
  43. CANCELLED_AND_NOTIFIED,
  44. FINISHED
  45. ]
  46. _STATE_TO_DESCRIPTION_MAP = {
  47. PENDING: "pending",
  48. RUNNING: "running",
  49. CANCELLED: "cancelled",
  50. CANCELLED_AND_NOTIFIED: "cancelled",
  51. FINISHED: "finished"
  52. }
  53. # Logger for internal use by the futures package.
  54. LOGGER = logging.getLogger("concurrent.futures")
  55. class Error(Exception):
  56. """Base class for all future-related exceptions."""
  57. pass
  58. class CancelledError(Error):
  59. """The Future was cancelled."""
  60. pass
  61. class TimeoutError(Error):
  62. """The operation exceeded the given deadline."""
  63. pass
  64. class _Waiter(object):
  65. """Provides the event that wait() and as_completed() block on."""
  66. def __init__(self):
  67. self.event = threading.Event()
  68. self.finished_futures = []
  69. def add_result(self, future):
  70. self.finished_futures.append(future)
  71. def add_exception(self, future):
  72. self.finished_futures.append(future)
  73. def add_cancelled(self, future):
  74. self.finished_futures.append(future)
  75. class _AsCompletedWaiter(_Waiter):
  76. """Used by as_completed()."""
  77. def __init__(self):
  78. super(_AsCompletedWaiter, self).__init__()
  79. self.lock = threading.Lock()
  80. def add_result(self, future):
  81. with self.lock:
  82. super(_AsCompletedWaiter, self).add_result(future)
  83. self.event.set()
  84. def add_exception(self, future):
  85. with self.lock:
  86. super(_AsCompletedWaiter, self).add_exception(future)
  87. self.event.set()
  88. def add_cancelled(self, future):
  89. with self.lock:
  90. super(_AsCompletedWaiter, self).add_cancelled(future)
  91. self.event.set()
  92. class _FirstCompletedWaiter(_Waiter):
  93. """Used by wait(return_when=FIRST_COMPLETED)."""
  94. def add_result(self, future):
  95. super(_FirstCompletedWaiter, self).add_result(future)
  96. self.event.set()
  97. def add_exception(self, future):
  98. super(_FirstCompletedWaiter, self).add_exception(future)
  99. self.event.set()
  100. def add_cancelled(self, future):
  101. super(_FirstCompletedWaiter, self).add_cancelled(future)
  102. self.event.set()
  103. class _AllCompletedWaiter(_Waiter):
  104. """Used by wait(return_when=FIRST_EXCEPTION and ALL_COMPLETED)."""
  105. def __init__(self, num_pending_calls, stop_on_exception):
  106. self.num_pending_calls = num_pending_calls
  107. self.stop_on_exception = stop_on_exception
  108. self.lock = threading.Lock()
  109. super(_AllCompletedWaiter, self).__init__()
  110. def _decrement_pending_calls(self):
  111. with self.lock:
  112. self.num_pending_calls -= 1
  113. if not self.num_pending_calls:
  114. self.event.set()
  115. def add_result(self, future):
  116. super(_AllCompletedWaiter, self).add_result(future)
  117. self._decrement_pending_calls()
  118. def add_exception(self, future):
  119. super(_AllCompletedWaiter, self).add_exception(future)
  120. if self.stop_on_exception:
  121. self.event.set()
  122. else:
  123. self._decrement_pending_calls()
  124. def add_cancelled(self, future):
  125. super(_AllCompletedWaiter, self).add_cancelled(future)
  126. self._decrement_pending_calls()
  127. class _AcquireFutures(object):
  128. """A context manager that does an ordered acquire of Future conditions.
  129. """
  130. def __init__(self, futures):
  131. self.futures = sorted(futures, key=id)
  132. def __enter__(self):
  133. for future in self.futures:
  134. future._condition.acquire()
  135. def __exit__(self, *args):
  136. for future in self.futures:
  137. future._condition.release()
  138. def _create_and_install_waiters(fs, return_when):
  139. if return_when == _AS_COMPLETED:
  140. waiter = _AsCompletedWaiter()
  141. elif return_when == FIRST_COMPLETED:
  142. waiter = _FirstCompletedWaiter()
  143. else:
  144. pending_count = sum(
  145. f._state not in [CANCELLED_AND_NOTIFIED, FINISHED]
  146. for f in fs)
  147. if return_when == FIRST_EXCEPTION:
  148. waiter = _AllCompletedWaiter(pending_count,
  149. stop_on_exception=True)
  150. elif return_when == ALL_COMPLETED:
  151. waiter = _AllCompletedWaiter(pending_count,
  152. stop_on_exception=False)
  153. else:
  154. raise ValueError("Invalid return condition: %r" % return_when)
  155. for f in fs:
  156. f._waiters.append(waiter)
  157. return waiter
  158. def as_completed(fs, timeout=None):
  159. """An iterator over the given futures that yields each as it completes.
  160. Args:
  161. fs: The sequence of Futures (possibly created by different
  162. Executors) to iterate over.
  163. timeout: The maximum number of seconds to wait. If None, then there
  164. is no limit on the wait time.
  165. Returns:
  166. An iterator that yields the given Futures as they complete
  167. (finished or cancelled). If any given Futures are duplicated, they
  168. will be returned once.
  169. Raises:
  170. TimeoutError: If the entire result iterator could not be generated
  171. before the given timeout.
  172. """
  173. if timeout is not None:
  174. end_time = timeout + time.time()
  175. fs = set(fs)
  176. with _AcquireFutures(fs):
  177. finished = set(
  178. f for f in fs
  179. if f._state in [CANCELLED_AND_NOTIFIED, FINISHED])
  180. pending = fs - finished
  181. waiter = _create_and_install_waiters(fs, _AS_COMPLETED)
  182. try:
  183. for future in finished:
  184. yield future
  185. while pending:
  186. if timeout is None:
  187. wait_timeout = None
  188. else:
  189. wait_timeout = end_time - time.time()
  190. if wait_timeout < 0:
  191. raise TimeoutError('%d (of %d) futures unfinished' % (
  192. len(pending), len(fs)))
  193. waiter.event.wait(wait_timeout)
  194. with waiter.lock:
  195. finished = waiter.finished_futures
  196. waiter.finished_futures = []
  197. waiter.event.clear()
  198. for future in finished:
  199. yield future
  200. pending.remove(future)
  201. finally:
  202. for f in fs:
  203. with f._condition:
  204. f._waiters.remove(waiter)
  205. DoneAndNotDoneFutures = collections.namedtuple(
  206. 'DoneAndNotDoneFutures', 'done not_done')
  207. def wait(fs, timeout=None, return_when=ALL_COMPLETED):
  208. """Wait for the futures in the given sequence to complete.
  209. Args:
  210. fs: The sequence of Futures (possibly created by different
  211. Executors) to wait upon.
  212. timeout: The maximum number of seconds to wait. If None, then there
  213. is no limit on the wait time.
  214. return_when: Indicates when this function should return. The
  215. options are:
  216. FIRST_COMPLETED - Return when any future finishes or is
  217. cancelled.
  218. FIRST_EXCEPTION - Return when any future finishes by raising an
  219. exception. If no future raises an exception
  220. then it is equivalent to ALL_COMPLETED.
  221. ALL_COMPLETED - Return when all futures finish or are
  222. cancelled.
  223. Returns:
  224. A named 2-tuple of sets. The first set, named 'done', contains the
  225. futures that completed (is finished or cancelled) before the wait
  226. completed. The second set, named 'not_done', contains uncompleted
  227. futures.
  228. """
  229. with _AcquireFutures(fs):
  230. done = set(f for f in fs
  231. if f._state in [CANCELLED_AND_NOTIFIED, FINISHED])
  232. not_done = set(fs) - done
  233. if (return_when == FIRST_COMPLETED) and done:
  234. return DoneAndNotDoneFutures(done, not_done)
  235. elif (return_when == FIRST_EXCEPTION) and done:
  236. if any(f for f in done
  237. if not f.cancelled() and f.exception() is not None):
  238. return DoneAndNotDoneFutures(done, not_done)
  239. if len(done) == len(fs):
  240. return DoneAndNotDoneFutures(done, not_done)
  241. waiter = _create_and_install_waiters(fs, return_when)
  242. waiter.event.wait(timeout)
  243. for f in fs:
  244. with f._condition:
  245. f._waiters.remove(waiter)
  246. done.update(waiter.finished_futures)
  247. return DoneAndNotDoneFutures(done, set(fs) - done)
  248. class _BaseFuture(object):
  249. """Represents the result of an asynchronous computation."""
  250. def __init__(self):
  251. """Initializes the future. Should not be called by clients."""
  252. self._condition = threading.Condition()
  253. self._state = PENDING
  254. self._result = None
  255. self._exception = None
  256. self._waiters = []
  257. self._done_callbacks = []
  258. def __repr__(self):
  259. with self._condition:
  260. if self._state == FINISHED:
  261. if self._exception:
  262. return '<%s at %#x state=%s raised %s>' % (
  263. self.__class__.__name__,
  264. id(self),
  265. _STATE_TO_DESCRIPTION_MAP[self._state],
  266. self._exception.__class__.__name__)
  267. else:
  268. return '<%s at %#x state=%s returned %s>' % (
  269. self.__class__.__name__,
  270. id(self),
  271. _STATE_TO_DESCRIPTION_MAP[self._state],
  272. self._result.__class__.__name__)
  273. return '<%s at %#x state=%s>' % (
  274. self.__class__.__name__,
  275. id(self),
  276. _STATE_TO_DESCRIPTION_MAP[self._state])
  277. def cancel(self):
  278. """Cancel the future if possible.
  279. Returns True if the future was cancelled, False otherwise. A future
  280. cannot be cancelled if it is running or has already completed.
  281. """
  282. with self._condition:
  283. if self._state in [RUNNING, FINISHED]:
  284. return False
  285. if self._state in [CANCELLED, CANCELLED_AND_NOTIFIED]:
  286. return True
  287. self._state = CANCELLED
  288. self._condition.notify_all()
  289. self._invoke_callbacks()
  290. return True
  291. def cancelled(self):
  292. """Return True if the future was cancelled."""
  293. with self._condition:
  294. return self._state in [CANCELLED, CANCELLED_AND_NOTIFIED]
  295. def running(self):
  296. """Return True if the future is currently executing."""
  297. with self._condition:
  298. return self._state == RUNNING
  299. def done(self):
  300. """Return True of the future was cancelled or finished executing.
  301. """
  302. with self._condition:
  303. return self._state in [CANCELLED, CANCELLED_AND_NOTIFIED,
  304. FINISHED]
  305. def __get_result(self):
  306. if self._exception:
  307. raise self._exception
  308. else:
  309. return self._result
  310. def add_done_callback(self, fn):
  311. """Attaches a callable that will be called when the future finishes.
  312. Args:
  313. fn: A callable that will be called with this future as its only
  314. argument when the future completes or is cancelled. The
  315. callable will always be called by a thread in the same
  316. process in which it was added. If the future has already
  317. completed or been cancelled then the callable will be
  318. called immediately. These callables are called in the order
  319. that they were added.
  320. """
  321. with self._condition:
  322. if self._state not in [CANCELLED, CANCELLED_AND_NOTIFIED,
  323. FINISHED]:
  324. self._done_callbacks.append(fn)
  325. return
  326. fn(self)
  327. def result(self, timeout=None):
  328. """Return the result of the call that the future represents.
  329. Args:
  330. timeout: The number of seconds to wait for the result if the
  331. future isn't done. If None, then there is no limit on the
  332. wait time.
  333. Returns:
  334. The result of the call that the future represents.
  335. Raises:
  336. CancelledError: If the future was cancelled.
  337. TimeoutError: If the future didn't finish executing before the
  338. given timeout.
  339. Exception: If the call raised then that exception will be
  340. raised.
  341. """
  342. with self._condition:
  343. if self._state in [CANCELLED, CANCELLED_AND_NOTIFIED]:
  344. raise CancelledError()
  345. elif self._state == FINISHED:
  346. return self.__get_result()
  347. self._condition.wait(timeout)
  348. if self._state in [CANCELLED, CANCELLED_AND_NOTIFIED]:
  349. raise CancelledError()
  350. elif self._state == FINISHED:
  351. return self.__get_result()
  352. else:
  353. raise TimeoutError()
  354. def exception(self, timeout=None):
  355. """Return the exception raised by the call that the future
  356. represents.
  357. Args:
  358. timeout: The number of seconds to wait for the exception if the
  359. future isn't done. If None, then there is no limit on the
  360. wait time.
  361. Returns:
  362. The exception raised by the call that the future represents or
  363. None if the call completed without raising.
  364. Raises:
  365. CancelledError: If the future was cancelled.
  366. TimeoutError: If the future didn't finish executing before the
  367. given timeout.
  368. """
  369. with self._condition:
  370. if self._state in [CANCELLED, CANCELLED_AND_NOTIFIED]:
  371. raise CancelledError()
  372. elif self._state == FINISHED:
  373. return self._exception
  374. self._condition.wait(timeout)
  375. if self._state in [CANCELLED, CANCELLED_AND_NOTIFIED]:
  376. raise CancelledError()
  377. elif self._state == FINISHED:
  378. return self._exception
  379. else:
  380. raise TimeoutError()
  381. # The following methods should only be used by Executors and in tests.
  382. def set_running_or_notify_cancel(self):
  383. """Mark the future as running or process any cancel notifications.
  384. Should only be used by Executor implementations and unit tests.
  385. If the future has been cancelled (cancel() was called and returned
  386. True) then any threads waiting on the future completing (though
  387. calls to as_completed() or wait()) are notified and False is
  388. returned.
  389. If the future was not cancelled then it is put in the running state
  390. (future calls to running() will return True) and True is returned.
  391. This method should be called by Executor implementations before
  392. executing the work associated with this future. If this method
  393. returns False then the work should not be executed.
  394. Returns:
  395. False if the Future was cancelled, True otherwise.
  396. Raises:
  397. RuntimeError: if this method was already called or if
  398. set_result() or set_exception() was called.
  399. """
  400. with self._condition:
  401. if self._state == CANCELLED:
  402. self._state = CANCELLED_AND_NOTIFIED
  403. for waiter in self._waiters:
  404. waiter.add_cancelled(self)
  405. # self._condition.notify_all() is not necessary because
  406. # self.cancel() triggers a notification.
  407. return False
  408. elif self._state == PENDING:
  409. self._state = RUNNING
  410. return True
  411. else:
  412. LOGGER.critical('Future %s in unexpected state: %s',
  413. id(self),
  414. self._state)
  415. raise RuntimeError('Future in unexpected state')
  416. def set_result(self, result):
  417. """Sets the return value of work associated with the future.
  418. Should only be used by Executor implementations and unit tests.
  419. """
  420. with self._condition:
  421. self._result = result
  422. self._state = FINISHED
  423. for waiter in self._waiters:
  424. waiter.add_result(self)
  425. self._condition.notify_all()
  426. self._invoke_callbacks()
  427. def set_exception(self, exception):
  428. """Sets the result of the future as being the given exception.
  429. Should only be used by Executor implementations and unit tests.
  430. """
  431. with self._condition:
  432. self._exception = exception
  433. self._state = FINISHED
  434. for waiter in self._waiters:
  435. waiter.add_exception(self)
  436. self._condition.notify_all()
  437. self._invoke_callbacks()
  438. class Executor(object):
  439. """This is an abstract base class for concrete asynchronous executors.
  440. """
  441. def submit(self, fn, *args, **kwargs):
  442. """Submits a callable to be executed with the given arguments.
  443. Schedules the callable to be executed as fn(*args, **kwargs) and
  444. returns a Future instance representing the execution of the
  445. callable.
  446. Returns:
  447. A Future representing the given call.
  448. """
  449. raise NotImplementedError()
  450. def map(self, fn, *iterables, **kwargs):
  451. """Returns an iterator equivalent to map(fn, iter).
  452. Args:
  453. fn: A callable that will take as many arguments as there are
  454. passed iterables.
  455. timeout: The maximum number of seconds to wait. If None, then
  456. there is no limit on the wait time.
  457. chunksize: The size of the chunks the iterable will be broken
  458. into before being passed to a child process. This argument
  459. is only used by ProcessPoolExecutor; it is ignored by
  460. ThreadPoolExecutor.
  461. Returns:
  462. An iterator equivalent to: map(func, *iterables) but the calls
  463. may be evaluated out-of-order.
  464. Raises:
  465. TimeoutError: If the entire result iterator could not be
  466. generated before the given timeout.
  467. Exception: If fn(*args) raises for any values.
  468. """
  469. timeout = kwargs.get('timeout')
  470. if timeout is not None:
  471. end_time = timeout + time.time()
  472. fs = [self.submit(fn, *args) for args in zip(*iterables)]
  473. # Yield must be hidden in closure so that the futures are submitted
  474. # before the first iterator value is required.
  475. def result_iterator():
  476. try:
  477. for future in fs:
  478. if timeout is None:
  479. yield future.result()
  480. else:
  481. yield future.result(end_time - time.time())
  482. finally:
  483. for future in fs:
  484. future.cancel()
  485. return result_iterator()
  486. def shutdown(self, wait=True):
  487. """Clean-up the resources associated with the Executor.
  488. It is safe to call this method several times. Otherwise, no other
  489. methods can be called after this one.
  490. Args:
  491. wait: If True then shutdown will not return until all running
  492. futures have finished executing and the resources used by
  493. the executor have been reclaimed.
  494. """
  495. pass
  496. def __enter__(self):
  497. return self
  498. def __exit__(self, exc_type, exc_val, exc_tb):
  499. self.shutdown(wait=True)
  500. return False
  501. # To make loky._base.Future instances awaitable by concurrent.futures.wait,
  502. # derive our custom Future class from _BaseFuture. _invoke_callback is the only
  503. # modification made to this class in loky.
  504. class Future(_BaseFuture):
  505. def _invoke_callbacks(self):
  506. for callback in self._done_callbacks:
  507. try:
  508. callback(self)
  509. except BaseException:
  510. LOGGER.exception('exception calling callback for %r', self)