| 1 |
# Licensed under the Apache License, Version 2.0 (the "License"); you may |
| 2 |
# not use this file except in compliance with the License. You may obtain |
| 3 |
# a copy of the License at |
| 4 |
# |
| 5 |
# http://www.apache.org/licenses/LICENSE-2.0 |
| 6 |
# |
| 7 |
# Unless required by applicable law or agreed to in writing, software |
| 8 |
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT |
| 9 |
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the |
| 10 |
# License for the specific language governing permissions and limitations |
| 11 |
# under the License. |
| 12 |
|
| 13 |
from concurrent import futures |
| 14 |
import threading |
| 15 |
import time |
| 16 |
import unittest |
| 17 |
from unittest import mock |
| 18 |
|
| 19 |
from eventlet.green import threading as green_threading |
| 20 |
import testscenarios |
| 21 |
|
| 22 |
import futurist |
| 23 |
from futurist import rejection |
| 24 |
from futurist.tests import base |
| 25 |
|
| •26 |
import multiprocessing |
| 27 |
|
| 28 |
# Workaround for Python 3.14 multiprocessing/forkserver issues in restricted environments |
| 29 |
# (e.g., Debian build chroots). Force 'spawn' start method to avoid socket-based forkserver. |
| 30 |
try: |
| 31 |
multiprocessing.set_start_method('spawn', force=True) |
| 32 |
except RuntimeError: |
| 33 |
# Already set by someone else; harmless |
| 34 |
pass |
| 35 |
|
| 36 |
# Module level functions need to be used since the process pool |
| 37 |
# executor can not access instance or lambda level functions (since those |
| 38 |
# are not pickleable). |
| 39 |
|
| 40 |
def returns_one(): |
| 41 |
return 1 |
| 42 |
|
| 43 |
|
| 44 |
def blows_up(): |
| 45 |
raise RuntimeError("no worky") |
| 46 |
|
| 47 |
|
| 48 |
def delayed(wait_secs): |
| 49 |
time.sleep(wait_secs) |
| 50 |
|
| 51 |
|
| 52 |
def delayed_with_result(task_id): |
| 53 |
time.sleep(0.1) |
| 54 |
return task_id |
| 55 |
|
| 56 |
|
| 57 |
class TestExecutors(testscenarios.TestWithScenarios, base.TestCase): |
| 58 |
scenarios = [ |
| 59 |
('sync', {'executor_cls': futurist.SynchronousExecutor, |
| 60 |
'restartable': True, 'executor_kwargs': {}}), |
| 61 |
('green_sync', {'executor_cls': futurist.SynchronousExecutor, |
| 62 |
'restartable': True, |
| 63 |
'executor_kwargs': {'green': True}}), |
| 64 |
('green', {'executor_cls': futurist.GreenThreadPoolExecutor, |
| 65 |
'restartable': False, 'executor_kwargs': {}}), |
| 66 |
('thread', {'executor_cls': futurist.ThreadPoolExecutor, |
| 67 |
'restartable': False, 'executor_kwargs': {}}), |
| 68 |
('thread_dyn', {'executor_cls': futurist.DynamicThreadPoolExecutor, |
| 69 |
'restartable': False, 'executor_kwargs': {}}), |
| 70 |
('process', {'executor_cls': futurist.ProcessPoolExecutor, |
| 71 |
'restartable': False, 'executor_kwargs': {}}), |
| 72 |
] |
| 73 |
|
| 74 |
def setUp(self): |
| 75 |
super().setUp() |
| 76 |
self.executor = self.executor_cls(**self.executor_kwargs) |
| 77 |
|
| 78 |
def tearDown(self): |
| 79 |
super().tearDown() |
| 80 |
self.executor.shutdown() |
| 81 |
self.executor = None |
| 82 |
|
| 83 |
def test_run_one(self): |
| 84 |
fut = self.executor.submit(returns_one) |
| 85 |
self.assertEqual(1, fut.result()) |
| 86 |
self.assertTrue(fut.done()) |
| 87 |
|
| 88 |
def test_blows_up(self): |
| 89 |
fut = self.executor.submit(blows_up) |
| 90 |
self.assertRaises(RuntimeError, fut.result) |
| 91 |
self.assertIsInstance(fut.exception(), RuntimeError) |
| 92 |
|
| 93 |
def test_gather_stats(self): |
| 94 |
self.executor.submit(blows_up) |
| 95 |
self.executor.submit(delayed, 0.2) |
| 96 |
self.executor.submit(returns_one) |
| 97 |
self.executor.shutdown() |
| 98 |
|
| 99 |
self.assertEqual(3, self.executor.statistics.executed) |
| 100 |
self.assertEqual(1, self.executor.statistics.failures) |
| 101 |
self.assertGreaterEqual(self.executor.statistics.runtime, |
| 102 |
# It appears that the thread run loop |
| 103 |
# may call this before 0.2 seconds (or 0.2 |
| 104 |
# will not be represented as a float correctly) |
| 105 |
# is really up so accommodate for that |
| 106 |
# happening... |
| 107 |
0.199) |
| 108 |
|
| 109 |
def test_post_shutdown_raises(self): |
| 110 |
executor = self.executor_cls(**self.executor_kwargs) |
| 111 |
executor.shutdown() |
| 112 |
self.assertRaises(RuntimeError, executor.submit, returns_one) |
| 113 |
|
| 114 |
def test_shutdown_waits_for_all_tasks(self): |
| 115 |
num_tasks = 3 |
| 116 |
futures = [] |
| 117 |
for i in range(num_tasks): |
| 118 |
future = self.executor.submit(delayed_with_result, i) |
| 119 |
futures.append(future) |
| 120 |
|
| 121 |
self.executor.shutdown(wait=True) |
| 122 |
|
| 123 |
results = [] |
| 124 |
for future in futures: |
| 125 |
self.assertTrue(future.done()) |
| 126 |
results.append(future.result()) |
| 127 |
|
| 128 |
self.assertEqual(len(results), num_tasks) |
| 129 |
self.assertEqual(set(results), set(range(num_tasks))) |
| 130 |
|
| 131 |
def test_restartable(self): |
| 132 |
if not self.restartable: |
| 133 |
raise unittest.SkipTest("not restartable") |
| 134 |
else: |
| 135 |
executor = self.executor_cls(**self.executor_kwargs) |
| 136 |
fut = executor.submit(returns_one) |
| 137 |
self.assertEqual(1, fut.result()) |
| 138 |
executor.shutdown() |
| 139 |
self.assertEqual(1, executor.statistics.executed) |
| 140 |
|
| 141 |
self.assertRaises(RuntimeError, executor.submit, returns_one) |
| 142 |
|
| 143 |
executor.restart() |
| 144 |
self.assertEqual(0, executor.statistics.executed) |
| 145 |
fut = executor.submit(returns_one) |
| 146 |
self.assertEqual(1, fut.result()) |
| 147 |
self.assertEqual(1, executor.statistics.executed) |
| 148 |
executor.shutdown() |
| 149 |
|
| 150 |
def test_alive(self): |
| 151 |
with self.executor_cls(**self.executor_kwargs) as executor: |
| 152 |
self.assertTrue(executor.alive) |
| 153 |
self.assertFalse(executor.alive) |
| 154 |
|
| 155 |
def test_done_callback(self): |
| 156 |
happy_completed = [] |
| 157 |
unhappy_completed = [] |
| 158 |
|
| 159 |
def on_done(fut): |
| 160 |
if fut.exception(): |
| 161 |
unhappy_completed.append(fut) |
| 162 |
else: |
| 163 |
happy_completed.append(fut) |
| 164 |
|
| 165 |
for i in range(0, 10): |
| 166 |
if i % 2 == 0: |
| 167 |
fut = self.executor.submit(returns_one) |
| 168 |
else: |
| 169 |
fut = self.executor.submit(blows_up) |
| 170 |
fut.add_done_callback(on_done) |
| 171 |
|
| 172 |
self.executor.shutdown() |
| 173 |
self.assertEqual(10, len(happy_completed) + len(unhappy_completed)) |
| 174 |
self.assertEqual(5, len(unhappy_completed)) |
| 175 |
self.assertEqual(5, len(happy_completed)) |
| 176 |
|
| 177 |
|
| 178 |
class TestRejection(testscenarios.TestWithScenarios, base.TestCase): |
| 179 |
rejector = rejection.reject_when_reached(1) |
| 180 |
|
| 181 |
scenarios = [ |
| 182 |
('green', {'executor_cls': futurist.GreenThreadPoolExecutor, |
| 183 |
'executor_kwargs': {'check_and_reject': rejector, |
| 184 |
'max_workers': 1}, |
| 185 |
'event_cls': green_threading.Event}), |
| 186 |
('thread', {'executor_cls': futurist.ThreadPoolExecutor, |
| 187 |
'executor_kwargs': {'check_and_reject': rejector, |
| 188 |
'max_workers': 1}, |
| 189 |
'event_cls': threading.Event}), |
| 190 |
] |
| 191 |
|
| 192 |
def setUp(self): |
| 193 |
super().setUp() |
| 194 |
self.executor = self.executor_cls(**self.executor_kwargs) |
| 195 |
self.addCleanup(self.executor.shutdown, wait=True) |
| 196 |
|
| 197 |
def test_rejection(self): |
| 198 |
ev = self.event_cls() |
| 199 |
ev_thread_started = self.event_cls() |
| 200 |
self.addCleanup(ev.set) |
| 201 |
|
| 202 |
def wait_until_set(check_delay): |
| 203 |
ev_thread_started.set() |
| 204 |
while not ev.is_set(): |
| 205 |
ev.wait(check_delay) |
| 206 |
|
| 207 |
# 1 worker + 1 item of backlog |
| 208 |
self.executor.submit(wait_until_set, 0.1) |
| 209 |
# ensure the above thread has started before doing anything |
| 210 |
# else. |
| 211 |
ev_thread_started.wait() |
| 212 |
self.executor.submit(wait_until_set, 0.1) |
| 213 |
|
| 214 |
self.assertRaises(futurist.RejectedSubmission, |
| 215 |
self.executor.submit, returns_one) |
| 216 |
|
| 217 |
|
| 218 |
@mock.patch.object(futurist.DynamicThreadPoolExecutor, '_add_thread', |
| 219 |
# Use the original function behind the scene |
| 220 |
side_effect=futurist.DynamicThreadPoolExecutor._add_thread, |
| 221 |
autospec=True) |
| 222 |
class TestDynamicThreadPool(base.TestCase): |
| 223 |
|
| 224 |
def _new(self, *args, **kwargs): |
| 225 |
executor = futurist.DynamicThreadPoolExecutor(*args, **kwargs) |
| 226 |
self.addCleanup(executor.shutdown, wait=True) |
| 227 |
self.assertEqual(0, executor.queue_size) |
| 228 |
self.assertEqual(0, executor.num_workers) |
| 229 |
self.assertEqual(0, executor.get_num_idle_workers()) |
| 230 |
self.assertEqual(0, len(executor._dead_workers)) |
| 231 |
return executor |
| 232 |
|
| 233 |
def test_stays_at_min_worker(self, mock_add_thread): |
| 234 |
"""Executing tasks sequentially: no growth beyond 1 thread.""" |
| 235 |
executor = self._new(max_workers=3) |
| 236 |
for _i in range(10): |
| 237 |
executor.submit(lambda: None).result() |
| 238 |
self.assertEqual(0, executor.queue_size) |
| 239 |
self.assertEqual(1, executor.num_workers) |
| 240 |
self.assertEqual(1, executor.get_num_idle_workers()) |
| 241 |
self.assertEqual(0, len(executor._dead_workers)) |
| 242 |
self.assertEqual(1, mock_add_thread.call_count) |
| 243 |
|
| 244 |
def test_grow_and_shrink(self, mock_add_thread): |
| 245 |
"""Executing tasks in parallel: grows and shrinks.""" |
| 246 |
executor = self._new(max_workers=10) |
| 247 |
started = threading.Barrier(11) |
| 248 |
done = threading.Event() |
| 249 |
tasks = [] |
| 250 |
|
| 251 |
self.addCleanup(started.abort) |
| 252 |
self.addCleanup(done.set) |
| 253 |
|
| 254 |
def task(): |
| 255 |
started.wait() |
| 256 |
done.wait() |
| 257 |
|
| 258 |
for _i in range(10): |
| 259 |
tasks.append(executor.submit(task)) |
| 260 |
|
| 261 |
started.wait() # this ensures that all threads have been started |
| 262 |
self.assertEqual(0, executor.queue_size) |
| 263 |
self.assertEqual(10, executor.num_workers) |
| 264 |
self.assertEqual(0, executor.get_num_idle_workers()) |
| 265 |
self.assertEqual(0, len(executor._dead_workers)) |
| 266 |
self.assertEqual(10, mock_add_thread.call_count) |
| 267 |
|
| 268 |
done.set() # this allows all threads to stop |
| 269 |
futures.wait(tasks) |
| 270 |
executor.maintain() |
| 271 |
self.assertEqual(0, executor.queue_size) |
| 272 |
self.assertEqual(1, executor.num_workers) |
| 273 |
self.assertEqual(1, executor.get_num_idle_workers()) |
| 274 |
self.assertEqual(0, len(executor._dead_workers)) |
| 275 |
|
| 276 |
def test_shutdown_waits_for_queued_tasks(self, mock_add_thread): |
| 277 |
results = [] |
| 278 |
results_lock = threading.Lock() |
| 279 |
|
| 280 |
def slow_task(task_id): |
| 281 |
time.sleep(0.1) |
| 282 |
with results_lock: |
| 283 |
results.append(task_id) |
| 284 |
|
| 285 |
num_tasks = 5 |
| 286 |
executor = self._new(max_workers=2, min_workers=1) |
| 287 |
for i in range(num_tasks): |
| 288 |
executor.submit(slow_task, i) |
| 289 |
|
| 290 |
executor.shutdown(wait=True) |
| 291 |
|
| 292 |
self.assertEqual(len(results), num_tasks) |
| 293 |
self.assertEqual(set(results), set(range(num_tasks))) |
| 294 |
|
| 295 |
|
| 296 |
@mock.patch('futurist._thread.ThreadWorker.create_and_register', autospec=True) |
| 297 |
class TestDynamicThreadPoolMaintain(base.TestCase): |
| 298 |
def test_ensure_one_worker(self, mock_create_thread): |
| 299 |
executor = futurist.DynamicThreadPoolExecutor() |
| 300 |
executor.maintain() |
| 301 |
self.assertEqual(1, len(executor._workers)) |
| 302 |
created_worker = mock_create_thread.return_value |
| 303 |
created_worker.start.assert_called_once_with() |
| 304 |
created_worker.stop.assert_not_called() |
| 305 |
|
| 306 |
def test_ensure_min_workers(self, mock_create_thread): |
| 307 |
executor = futurist.DynamicThreadPoolExecutor(min_workers=42) |
| 308 |
executor.maintain() |
| 309 |
self.assertEqual(42, len(executor._workers)) |
| 310 |
created_worker = mock_create_thread.return_value |
| 311 |
created_worker.start.assert_called_with() |
| 312 |
self.assertEqual(42, created_worker.start.call_count) |
| 313 |
created_worker.stop.assert_not_called() |
| 314 |
|
| 315 |
def test_too_many_idle_workers(self, mock_create_thread): |
| 316 |
executor = futurist.DynamicThreadPoolExecutor(min_workers=42) |
| 317 |
executor._workers = [mock.Mock(idle=True)] * 100 |
| 318 |
executor.maintain() |
| 319 |
self.assertEqual(42, len(executor._workers)) |
| 320 |
mock_create_thread.return_value.start.assert_not_called() |
| 321 |
self.assertEqual(58, executor._workers[0].stop.call_count) |
| 322 |
|
| 323 |
def test_all_busy_workers(self, mock_create_thread): |
| 324 |
executor = futurist.DynamicThreadPoolExecutor(max_workers=100) |
| 325 |
executor._workers = [mock.Mock(idle=False)] * 100 |
| 326 |
executor.maintain() |
| 327 |
self.assertEqual(100, len(executor._workers)) |
| 328 |
mock_create_thread.return_value.start.assert_not_called() |
| 329 |
executor._workers[0].stop.assert_not_called() |
| 330 |
|
| 331 |
def test_busy_workers_create_more(self, mock_create_thread): |
| 332 |
executor = futurist.DynamicThreadPoolExecutor(max_workers=200) |
| 333 |
executor._workers = [mock.Mock(idle=False)] * 100 |
| 334 |
executor.maintain() |
| 335 |
# NOTE(dtantsur): once the executor reaches 125 threads, the ratio of |
| 336 |
# busy to total threads is exactly 100/125=0.8 (the default |
| 337 |
# grow_threshold). One more thread is created, resulting in 126. |
| 338 |
self.assertEqual(126, len(executor._workers)) |
| 339 |
self.assertEqual(26, executor.get_num_idle_workers()) |
| 340 |
created_worker = mock_create_thread.return_value |
| 341 |
created_worker.start.assert_called_with() |
| 342 |
self.assertEqual(26, created_worker.start.call_count) |
| 343 |
created_worker.stop.assert_not_called() |
| 344 |
|
| 345 |
def test_busy_workers_within_range(self, mock_create_thread): |
| 346 |
executor = futurist.DynamicThreadPoolExecutor() |
| 347 |
executor._workers = [mock.Mock(idle=i < 30) for i in range(100)] |
| 348 |
executor.maintain() |
| 349 |
self.assertEqual(100, len(executor._workers)) |
| 350 |
mock_create_thread.return_value.start.assert_not_called() |
| 351 |
|
| 352 |
def test_busy_workers_and_large_queue(self, mock_create_thread): |
| 353 |
executor = futurist.DynamicThreadPoolExecutor(max_workers=200) |
| 354 |
executor._workers = [mock.Mock(idle=i < 30) for i in range(100)] |
| 355 |
for i in range(20): |
| 356 |
executor._work_queue.put(None) |
| 357 |
executor.maintain() |
| 358 |
# NOTE(dtantsur): initial busy ratio is (70+20)/100=0.9. As workers |
| 359 |
# are added, it reaches (70+20)/113, which is just below 0.8. |
| 360 |
self.assertEqual(113, len(executor._workers)) |
| 361 |
created_worker = mock_create_thread.return_value |
| 362 |
created_worker.start.assert_called_with() |
| 363 |
self.assertEqual(13, created_worker.start.call_count) |