| 1 |
# Copyright (C) 2015 Yahoo! Inc. All Rights Reserved. |
| 2 |
# |
| 3 |
# Licensed under the Apache License, Version 2.0 (the "License"); you may |
| 4 |
# not use this file except in compliance with the License. You may obtain |
| 5 |
# a copy of the License at |
| 6 |
# |
| 7 |
# http://www.apache.org/licenses/LICENSE-2.0 |
| 8 |
# |
| 9 |
# Unless required by applicable law or agreed to in writing, software |
| 10 |
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT |
| 11 |
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the |
| 12 |
# License for the specific language governing permissions and limitations |
| 13 |
# under the License. |
| 14 |
|
| 15 |
import collections |
| 16 |
import contextlib |
| 17 |
import functools |
| 18 |
|
| 19 |
from concurrent import futures |
| 20 |
from concurrent.futures import _base |
| 21 |
|
| 22 |
import futurist |
| 23 |
from futurist import _utils |
| 24 |
|
| 25 |
try: |
| 26 |
from eventlet.green import threading as greenthreading |
| 27 |
except ImportError: |
| 28 |
greenthreading = None |
| 29 |
|
| 30 |
|
| 31 |
#: Named tuple returned from ``wait_for*`` calls. |
| 32 |
DoneAndNotDoneFutures = collections.namedtuple( |
| 33 |
'DoneAndNotDoneFutures', 'done not_done') |
| 34 |
|
| 35 |
_DONE_STATES = frozenset([ |
| 36 |
_base.CANCELLED_AND_NOTIFIED, |
| 37 |
_base.FINISHED, |
| 38 |
]) |
| 39 |
|
| 40 |
|
| 41 |
@contextlib.contextmanager |
| 42 |
def _acquire_and_release_futures(fs): |
| 43 |
# Do this to ensure that we always get the futures in the same order (aka |
| 44 |
# always acquire the conditions in the same order, no matter what; a way |
| 45 |
# to avoid dead-lock). |
| 46 |
fs = sorted(fs, key=id) |
| 47 |
with contextlib.ExitStack() as stack: |
| 48 |
for fut in fs: |
| 49 |
stack.enter_context(fut._condition) |
| 50 |
yield |
| 51 |
|
| 52 |
|
| 53 |
def _ensure_eventlet(func): |
| 54 |
"""Decorator that verifies we have the needed eventlet components.""" |
| 55 |
|
| 56 |
@functools.wraps(func) |
| 57 |
def wrapper(*args, **kwargs): |
| 58 |
if not _utils.EVENTLET_AVAILABLE or greenthreading is None: |
| 59 |
raise RuntimeError('Eventlet is needed to wait on green futures') |
| 60 |
return func(*args, **kwargs) |
| 61 |
|
| 62 |
return wrapper |
| 63 |
|
| 64 |
|
| 65 |
def _wait_for(fs, no_green_return_when, on_all_green_cb, |
| 66 |
caller_name, timeout=None): |
| 67 |
green_fs = sum(1 for f in fs if isinstance(f, futurist.GreenFuture)) |
| 68 |
if not green_fs: |
| 69 |
done, not_done = futures.wait(fs, timeout=timeout, |
| 70 |
return_when=no_green_return_when) |
| 71 |
return DoneAndNotDoneFutures(done, not_done) |
| 72 |
else: |
| 73 |
non_green_fs = len(fs) - green_fs |
| 74 |
if non_green_fs: |
| 75 |
raise RuntimeError("Can not wait on %s green futures and %s" |
| 76 |
" non-green futures in the same" |
| 77 |
" `%s` call" % (green_fs, non_green_fs, |
| 78 |
caller_name)) |
| 79 |
else: |
| 80 |
return on_all_green_cb(fs, timeout=timeout) |
| 81 |
|
| 82 |
|
| 83 |
def wait_for_all(fs, timeout=None): |
| 84 |
"""Wait for all of the futures to complete. |
| 85 |
|
| 86 |
Works correctly with both green and non-green futures (but not both |
| 87 |
together, since this can't be guaranteed to avoid dead-lock due to how |
| 88 |
the waiting implementations are different when green threads are being |
| 89 |
used). |
| 90 |
|
| 91 |
Returns pair (done futures, not done futures). |
| 92 |
""" |
| 93 |
return _wait_for(fs, futures.ALL_COMPLETED, _wait_for_all_green, |
| 94 |
'wait_for_all', timeout=timeout) |
| 95 |
|
| 96 |
|
| 97 |
def wait_for_any(fs, timeout=None): |
| 98 |
"""Wait for one (**any**) of the futures to complete. |
| 99 |
|
| 100 |
Works correctly with both green and non-green futures (but not both |
| 101 |
together, since this can't be guaranteed to avoid dead-lock due to how |
| 102 |
the waiting implementations are different when green threads are being |
| 103 |
used). |
| 104 |
|
| 105 |
Returns pair (done futures, not done futures). |
| 106 |
""" |
| 107 |
return _wait_for(fs, futures.FIRST_COMPLETED, _wait_for_any_green, |
| 108 |
'wait_for_any', timeout=timeout) |
| 109 |
|
| 110 |
|
| 111 |
class _AllGreenWaiter: |
| 112 |
"""Provides the event that ``_wait_for_all_green`` blocks on.""" |
| 113 |
|
| 114 |
def __init__(self, pending): |
| 115 |
self.event = greenthreading.Event() |
| 116 |
self.lock = greenthreading.Lock() |
| 117 |
self.pending = pending |
| 118 |
|
| 119 |
def _decrement_pending(self): |
| 120 |
with self.lock: |
| 121 |
self.pending -= 1 |
| 122 |
if self.pending <= 0: |
| 123 |
self.event.set() |
| 124 |
|
| 125 |
def add_result(self, future): |
| 126 |
self._decrement_pending() |
| 127 |
|
| 128 |
def add_exception(self, future): |
| 129 |
self._decrement_pending() |
| 130 |
|
| 131 |
def add_cancelled(self, future): |
| 132 |
self._decrement_pending() |
| 133 |
|
| 134 |
|
| 135 |
class _AnyGreenWaiter: |
| 136 |
"""Provides the event that ``_wait_for_any_green`` blocks on.""" |
| 137 |
|
| 138 |
def __init__(self): |
| 139 |
self.event = greenthreading.Event() |
| 140 |
|
| 141 |
def add_result(self, future): |
| 142 |
self.event.set() |
| 143 |
|
| 144 |
def add_exception(self, future): |
| 145 |
self.event.set() |
| 146 |
|
| 147 |
def add_cancelled(self, future): |
| 148 |
self.event.set() |
| 149 |
|
| 150 |
|
| 151 |
def _partition_futures(fs): |
| 152 |
done = set() |
| 153 |
not_done = set() |
| 154 |
for f in fs: |
| 155 |
if f._state in _DONE_STATES: |
| 156 |
done.add(f) |
| 157 |
else: |
| 158 |
not_done.add(f) |
| 159 |
return done, not_done |
| 160 |
|
| 161 |
|
| 162 |
def _create_and_install_waiters(fs, waiter_cls, *args, **kwargs): |
| 163 |
waiter = waiter_cls(*args, **kwargs) |
| 164 |
for f in fs: |
| 165 |
f._waiters.append(waiter) |
| 166 |
return waiter |
| 167 |
|
| 168 |
|
| 169 |
@_ensure_eventlet |
| 170 |
def _wait_for_all_green(fs, timeout=None): |
| 171 |
if not fs: |
| 172 |
return DoneAndNotDoneFutures(set(), set()) |
| 173 |
|
| 174 |
with _acquire_and_release_futures(fs): |
| 175 |
done, not_done = _partition_futures(fs) |
| 176 |
if len(done) == len(fs): |
| 177 |
return DoneAndNotDoneFutures(done, not_done) |
| 178 |
waiter = _create_and_install_waiters(not_done, |
| 179 |
_AllGreenWaiter, |
| 180 |
len(not_done)) |
| 181 |
waiter.event.wait(timeout) |
| 182 |
for f in not_done: |
| 183 |
with f._condition: |
| 184 |
f._waiters.remove(waiter) |
| 185 |
|
| 186 |
with _acquire_and_release_futures(fs): |
| 187 |
done, not_done = _partition_futures(fs) |
| 188 |
return DoneAndNotDoneFutures(done, not_done) |
| 189 |
|
| 190 |
|
| 191 |
@_ensure_eventlet |
| 192 |
def _wait_for_any_green(fs, timeout=None): |
| 193 |
if not fs: |
| 194 |
return DoneAndNotDoneFutures(set(), set()) |
| 195 |
|
| 196 |
with _acquire_and_release_futures(fs): |
| 197 |
done, not_done = _partition_futures(fs) |
| 198 |
if done: |
| 199 |
return DoneAndNotDoneFutures(done, not_done) |
| 200 |
waiter = _create_and_install_waiters(fs, _AnyGreenWaiter) |
| 201 |
|
| 202 |
waiter.event.wait(timeout) |
| 203 |
for f in fs: |
| 204 |
with f._condition: |
| 205 |
f._waiters.remove(waiter) |
| 206 |
|
| 207 |
with _acquire_and_release_futures(fs): |
| 208 |
done, not_done = _partition_futures(fs) |
| 209 |
return DoneAndNotDoneFutures(done, not_done) |