| 1 |
import errno |
| 2 |
import os |
| 3 |
import socket |
| 4 |
import tempfile |
| 5 |
from itertools import cycle |
| 6 |
from unittest.mock import MagicMock, Mock, patch |
| 7 |
|
| 8 |
import pytest |
| 9 |
from billiard.pool import ApplyResult |
| 10 |
from kombu.asynchronous import Hub |
| 11 |
|
| 12 |
import t.skip |
| 13 |
from celery.app.defaults import DEFAULTS |
| 14 |
from celery.concurrency.asynpool import iterate_file_descriptors_safely |
| 15 |
from celery.utils.collections import AttributeDict |
| 16 |
from celery.utils.functional import noop |
| 17 |
from celery.utils.objects import Bunch |
| 18 |
|
| 19 |
try: |
| 20 |
from celery.concurrency import asynpool |
| 21 |
from celery.concurrency import prefork as mp |
| 22 |
except ImportError: |
| 23 |
|
| 24 |
class _mp: |
| 25 |
RUN = 0x1 |
| 26 |
|
| 27 |
class TaskPool: |
| 28 |
_pool = Mock() |
| 29 |
|
| 30 |
def __init__(self, *args, **kwargs): |
| 31 |
pass |
| 32 |
|
| 33 |
def start(self): |
| 34 |
pass |
| 35 |
|
| 36 |
def stop(self): |
| 37 |
pass |
| 38 |
|
| 39 |
def apply_async(self, *args, **kwargs): |
| 40 |
pass |
| 41 |
mp = _mp() |
| 42 |
asynpool = None |
| 43 |
|
| 44 |
|
| 45 |
class MockResult: |
| 46 |
|
| 47 |
def __init__(self, value, pid): |
| 48 |
self.value = value |
| 49 |
self.pid = pid |
| 50 |
|
| 51 |
def worker_pids(self): |
| 52 |
return [self.pid] |
| 53 |
|
| 54 |
def get(self): |
| 55 |
return self.value |
| 56 |
|
| 57 |
|
| 58 |
@patch('celery.platforms.set_mp_process_title') |
| 59 |
class test_process_initializer: |
| 60 |
|
| 61 |
@staticmethod |
| 62 |
def Loader(*args, **kwargs): |
| 63 |
loader = Mock(*args, **kwargs) |
| 64 |
loader.conf = {} |
| 65 |
loader.override_backends = {} |
| 66 |
return loader |
| 67 |
|
| 68 |
@patch('celery.platforms.signals') |
| 69 |
def test_process_initializer(self, _signals, set_mp_process_title, restore_logging): |
| 70 |
from celery import signals |
| 71 |
from celery._state import _tls |
| 72 |
from celery.concurrency.prefork import WORKER_SIGIGNORE, WORKER_SIGRESET, process_initializer |
| 73 |
on_worker_process_init = Mock() |
| 74 |
signals.worker_process_init.connect(on_worker_process_init) |
| 75 |
|
| 76 |
with self.Celery(loader=self.Loader) as app: |
| 77 |
app.conf = AttributeDict(DEFAULTS) |
| 78 |
process_initializer(app, 'awesome.worker.com') |
| 79 |
_signals.ignore.assert_any_call(*WORKER_SIGIGNORE) |
| 80 |
_signals.reset.assert_any_call(*WORKER_SIGRESET) |
| 81 |
assert app.loader.init_worker.call_count |
| 82 |
on_worker_process_init.assert_called() |
| 83 |
assert _tls.current_app is app |
| 84 |
set_mp_process_title.assert_called_with( |
| 85 |
'celeryd', hostname='awesome.worker.com', |
| 86 |
) |
| 87 |
|
| 88 |
with patch('celery.app.trace.setup_worker_optimizations') as S: |
| 89 |
os.environ['FORKED_BY_MULTIPROCESSING'] = '1' |
| 90 |
try: |
| 91 |
process_initializer(app, 'luke.worker.com') |
| 92 |
S.assert_called_with(app, 'luke.worker.com') |
| 93 |
finally: |
| 94 |
os.environ.pop('FORKED_BY_MULTIPROCESSING', None) |
| 95 |
|
| 96 |
os.environ['CELERY_LOG_FILE'] = 'worker%I.log' |
| 97 |
app.log.setup = Mock(name='log_setup') |
| 98 |
try: |
| 99 |
process_initializer(app, 'luke.worker.com') |
| 100 |
finally: |
| 101 |
os.environ.pop('CELERY_LOG_FILE', None) |
| 102 |
|
| 103 |
@patch('celery.platforms.set_pdeathsig') |
| 104 |
def test_pdeath_sig(self, _set_pdeathsig, set_mp_process_title, restore_logging): |
| 105 |
from celery import signals |
| 106 |
on_worker_process_init = Mock() |
| 107 |
signals.worker_process_init.connect(on_worker_process_init) |
| 108 |
from celery.concurrency.prefork import process_initializer |
| 109 |
|
| 110 |
with self.Celery(loader=self.Loader) as app: |
| 111 |
app.conf = AttributeDict(DEFAULTS) |
| 112 |
process_initializer(app, 'awesome.worker.com') |
| 113 |
_set_pdeathsig.assert_called_once_with('SIGKILL') |
| 114 |
|
| 115 |
|
| 116 |
class test_process_destructor: |
| 117 |
|
| 118 |
@patch('celery.concurrency.prefork.signals') |
| 119 |
def test_process_destructor(self, signals): |
| 120 |
mp.process_destructor(13, -3) |
| 121 |
signals.worker_process_shutdown.send.assert_called_with( |
| 122 |
sender=None, pid=13, exitcode=-3, |
| 123 |
) |
| 124 |
|
| 125 |
|
| 126 |
class MockPool: |
| 127 |
started = False |
| 128 |
closed = False |
| 129 |
joined = False |
| 130 |
terminated = False |
| 131 |
_state = None |
| 132 |
|
| 133 |
def __init__(self, *args, **kwargs): |
| 134 |
self.started = True |
| 135 |
self._timeout_handler = Mock() |
| 136 |
self._result_handler = Mock() |
| 137 |
self.maintain_pool = Mock() |
| 138 |
self._state = mp.RUN |
| 139 |
self._processes = kwargs.get('processes') |
| 140 |
self._proc_alive_timeout = kwargs.get('proc_alive_timeout') |
| 141 |
self._pool = [Bunch(pid=i, inqW_fd=1, outqR_fd=2) |
| 142 |
for i in range(self._processes)] |
| 143 |
self._current_proc = cycle(range(self._processes)) |
| 144 |
|
| 145 |
def close(self): |
| 146 |
self.closed = True |
| 147 |
self._state = 'CLOSE' |
| 148 |
|
| 149 |
def join(self): |
| 150 |
self.joined = True |
| 151 |
|
| 152 |
def terminate(self): |
| 153 |
self.terminated = True |
| 154 |
|
| 155 |
def terminate_job(self, *args, **kwargs): |
| 156 |
pass |
| 157 |
|
| 158 |
def restart(self, *args, **kwargs): |
| 159 |
pass |
| 160 |
|
| 161 |
def handle_result_event(self, *args, **kwargs): |
| 162 |
pass |
| 163 |
|
| 164 |
def flush(self): |
| 165 |
pass |
| 166 |
|
| 167 |
def grow(self, n=1): |
| 168 |
self._processes += n |
| 169 |
|
| 170 |
def shrink(self, n=1): |
| 171 |
self._processes -= n |
| 172 |
|
| 173 |
def apply_async(self, *args, **kwargs): |
| 174 |
pass |
| 175 |
|
| 176 |
def register_with_event_loop(self, loop): |
| 177 |
pass |
| 178 |
|
| 179 |
|
| 180 |
class ExeMockPool(MockPool): |
| 181 |
|
| 182 |
def apply_async(self, target, args=(), kwargs={}, callback=noop): |
| 183 |
from threading import Timer |
| 184 |
res = target(*args, **kwargs) |
| 185 |
Timer(0.1, callback, (res,)).start() |
| 186 |
return MockResult(res, next(self._current_proc)) |
| 187 |
|
| 188 |
|
| 189 |
class TaskPool(mp.TaskPool): |
| 190 |
Pool = BlockingPool = MockPool |
| 191 |
|
| 192 |
|
| 193 |
class ExeMockTaskPool(mp.TaskPool): |
| 194 |
Pool = BlockingPool = ExeMockPool |
| 195 |
|
| 196 |
|
| 197 |
@t.skip.if_win32 |
| 198 |
class test_AsynPool: |
| 199 |
|
| 200 |
def setup_method(self): |
| 201 |
pytest.importorskip('multiprocessing') |
| 202 |
|
| 203 |
def test_gen_not_started(self): |
| 204 |
|
| 205 |
def gen(): |
| 206 |
yield 1 |
| 207 |
assert not asynpool.gen_not_started(g) |
| 208 |
yield 2 |
| 209 |
g = gen() |
| 210 |
assert asynpool.gen_not_started(g) |
| 211 |
next(g) |
| 212 |
assert not asynpool.gen_not_started(g) |
| 213 |
list(g) |
| 214 |
assert not asynpool.gen_not_started(g) |
| 215 |
|
| 216 |
def gen2(): |
| 217 |
yield 1 |
| 218 |
raise RuntimeError('generator error') |
| 219 |
g = gen2() |
| 220 |
assert asynpool.gen_not_started(g) |
| 221 |
next(g) |
| 222 |
assert not asynpool.gen_not_started(g) |
| 223 |
with pytest.raises(RuntimeError): |
| 224 |
next(g) |
| 225 |
assert not asynpool.gen_not_started(g) |
| 226 |
|
| 227 |
@patch('select.select', create=True) |
| 228 |
def test_select(self, __select): |
| 229 |
ebadf = socket.error() |
| 230 |
ebadf.errno = errno.EBADF |
| 231 |
with patch('select.poll', create=True) as poller: |
| 232 |
poll = poller.return_value = Mock(name='poll.poll') |
| 233 |
poll.return_value = {3}, set(), 0 |
| 234 |
assert asynpool._select({3}, poll=poll) == ({3}, set(), 0) |
| 235 |
|
| 236 |
poll.return_value = {3}, set(), 0 |
| 237 |
assert asynpool._select({3}, None, {3}, poll=poll) == ( |
| 238 |
{3}, set(), 0, |
| 239 |
) |
| 240 |
|
| 241 |
eintr = socket.error() |
| 242 |
eintr.errno = errno.EINTR |
| 243 |
poll.side_effect = eintr |
| 244 |
|
| 245 |
readers = {3} |
| 246 |
assert asynpool._select(readers, poll=poll) == (set(), set(), 1) |
| 247 |
assert 3 in readers |
| 248 |
|
| 249 |
with patch('select.poll', create=True) as poller: |
| 250 |
poll = poller.return_value = Mock(name='poll.poll') |
| 251 |
poll.side_effect = ebadf |
| 252 |
with patch('select.select') as selcheck: |
| 253 |
selcheck.side_effect = ebadf |
| 254 |
readers = {3} |
| 255 |
assert asynpool._select(readers, poll=poll) == ( |
| 256 |
set(), set(), 1, |
| 257 |
) |
| 258 |
assert 3 not in readers |
| 259 |
|
| 260 |
with patch('select.poll', create=True) as poller: |
| 261 |
poll = poller.return_value = Mock(name='poll.poll') |
| 262 |
poll.side_effect = MemoryError() |
| 263 |
with pytest.raises(MemoryError): |
| 264 |
asynpool._select({1}, poll=poll) |
| 265 |
|
| 266 |
with patch('select.poll', create=True) as poller: |
| 267 |
poll = poller.return_value = Mock(name='poll.poll') |
| 268 |
with patch('select.select') as selcheck: |
| 269 |
|
| 270 |
def se(*args): |
| 271 |
selcheck.side_effect = MemoryError() |
| 272 |
raise ebadf |
| 273 |
poll.side_effect = se |
| 274 |
with pytest.raises(MemoryError): |
| 275 |
asynpool._select({3}, poll=poll) |
| 276 |
|
| 277 |
with patch('select.poll', create=True) as poller: |
| 278 |
poll = poller.return_value = Mock(name='poll.poll') |
| 279 |
with patch('select.select') as selcheck: |
| 280 |
|
| 281 |
def se2(*args): |
| 282 |
selcheck.side_effect = socket.error() |
| 283 |
selcheck.side_effect.errno = 1321 |
| 284 |
raise ebadf |
| 285 |
poll.side_effect = se2 |
| 286 |
with pytest.raises(socket.error): |
| 287 |
asynpool._select({3}, poll=poll) |
| 288 |
|
| 289 |
with patch('select.poll', create=True) as poller: |
| 290 |
poll = poller.return_value = Mock(name='poll.poll') |
| 291 |
|
| 292 |
poll.side_effect = socket.error() |
| 293 |
poll.side_effect.errno = 34134 |
| 294 |
with pytest.raises(socket.error): |
| 295 |
asynpool._select({3}, poll=poll) |
| 296 |
|
| 297 |
def test_select_unpatched(self): |
| 298 |
with tempfile.TemporaryFile('w') as f: |
| 299 |
_, writeable, _ = asynpool._select(writers={f, }, err={f, }) |
| 300 |
assert f.fileno() in writeable |
| 301 |
|
| 302 |
with tempfile.TemporaryFile('r') as f: |
| 303 |
readable, _, _ = asynpool._select(readers={f, }, err={f, }) |
| 304 |
assert f.fileno() in readable |
| 305 |
|
| 306 |
def test_promise(self): |
| 307 |
fun = Mock() |
| 308 |
x = asynpool.promise(fun, (1,), {'foo': 1}) |
| 309 |
x() |
| 310 |
assert x.ready |
| 311 |
fun.assert_called_with(1, foo=1) |
| 312 |
|
| 313 |
def test_Worker(self): |
| 314 |
w = asynpool.Worker(Mock(), Mock()) |
| 315 |
w.on_loop_start(1234) |
| 316 |
w.outq.put.assert_called_with((asynpool.WORKER_UP, (1234,))) |
| 317 |
|
| 318 |
def test_iterate_file_descriptors_safely_source_data_list(self): |
| 319 |
# Given: a list of integers that could be file descriptors |
| 320 |
fd_iter = [1, 2, 3, 4, 5] |
| 321 |
|
| 322 |
# Given: a mock hub method that does nothing to call |
| 323 |
def _fake_hub(*args, **kwargs): |
| 324 |
raise OSError |
| 325 |
|
| 326 |
# When Calling the helper to iterate_file_descriptors_safely |
| 327 |
iterate_file_descriptors_safely( |
| 328 |
fd_iter, fd_iter, _fake_hub, |
| 329 |
"arg1", "arg2", kw1="kw1", kw2="kw2", |
| 330 |
) |
| 331 |
|
| 332 |
# Then: all items were removed from the managed data source |
| 333 |
assert fd_iter == [], "Expected all items removed from managed list" |
| 334 |
|
| 335 |
def test_iterate_file_descriptors_safely_source_data_set(self): |
| 336 |
# Given: a list of integers that could be file descriptors |
| 337 |
fd_iter = {1, 2, 3, 4, 5} |
| 338 |
|
| 339 |
# Given: a mock hub method that does nothing to call |
| 340 |
def _fake_hub(*args, **kwargs): |
| 341 |
raise OSError |
| 342 |
|
| 343 |
# When Calling the helper to iterate_file_descriptors_safely |
| 344 |
iterate_file_descriptors_safely( |
| 345 |
fd_iter, fd_iter, _fake_hub, |
| 346 |
"arg1", "arg2", kw1="kw1", kw2="kw2", |
| 347 |
) |
| 348 |
|
| 349 |
# Then: all items were removed from the managed data source |
| 350 |
assert fd_iter == set(), "Expected all items removed from managed set" |
| 351 |
|
| 352 |
def test_iterate_file_descriptors_safely_source_data_dict(self): |
| 353 |
# Given: a list of integers that could be file descriptors |
| 354 |
fd_iter = {1: 1, 2: 2, 3: 3, 4: 4, 5: 5} |
| 355 |
|
| 356 |
# Given: a mock hub method that does nothing to call |
| 357 |
def _fake_hub(*args, **kwargs): |
| 358 |
raise OSError |
| 359 |
|
| 360 |
# When Calling the helper to iterate_file_descriptors_safely |
| 361 |
iterate_file_descriptors_safely( |
| 362 |
fd_iter, fd_iter, _fake_hub, |
| 363 |
"arg1", "arg2", kw1="kw1", kw2="kw2", |
| 364 |
) |
| 365 |
|
| 366 |
# Then: all items were removed from the managed data source |
| 367 |
assert fd_iter == {}, "Expected all items removed from managed dict" |
| 368 |
|
| 369 |
def _get_hub(self): |
| 370 |
hub = Hub() |
| 371 |
hub.readers = {} |
| 372 |
hub.writers = {} |
| 373 |
hub.timer = Mock(name='hub.timer') |
| 374 |
hub.timer._queue = [Mock()] |
| 375 |
hub.fire_timers = Mock(name='hub.fire_timers') |
| 376 |
hub.fire_timers.return_value = 1.7 |
| 377 |
hub.poller = Mock(name='hub.poller') |
| 378 |
hub.close = Mock(name='hub.close()') |
| 379 |
return hub |
| 380 |
|
| 381 |
@t.skip.if_pypy |
| 382 |
def test_schedule_writes_hub_remove_writer_ready_fd_not_in_all_inqueues(self): |
| 383 |
pool = asynpool.AsynPool(threads=False) |
| 384 |
hub = self._get_hub() |
| 385 |
|
| 386 |
writer = Mock(name='writer') |
| 387 |
reader = Mock(name='reader') |
| 388 |
|
| 389 |
# add 2 fake fds with the same id |
| 390 |
hub.add_reader(6, reader, 6) |
| 391 |
hub.add_writer(6, writer, 6) |
| 392 |
pool._all_inqueues.clear() |
| 393 |
pool._create_write_handlers(hub) |
| 394 |
|
| 395 |
# check schedule_writes write fds remove not remove the reader one from the hub. |
| 396 |
hub.consolidate_callback(ready_fds=[6]) |
| 397 |
assert 6 in hub.readers |
| 398 |
assert 6 not in hub.writers |
| 399 |
|
| 400 |
@t.skip.if_pypy |
| 401 |
def test_schedule_writes_hub_remove_writers_from_active_writers_when_get_index_error(self): |
| 402 |
pool = asynpool.AsynPool(threads=False) |
| 403 |
hub = self._get_hub() |
| 404 |
|
| 405 |
writer = Mock(name='writer') |
| 406 |
reader = Mock(name='reader') |
| 407 |
|
| 408 |
# add 3 fake fds with the same id to reader and writer |
| 409 |
hub.add_reader(6, reader, 6) |
| 410 |
hub.add_reader(8, reader, 8) |
| 411 |
hub.add_reader(9, reader, 9) |
| 412 |
hub.add_writer(6, writer, 6) |
| 413 |
hub.add_writer(8, writer, 8) |
| 414 |
hub.add_writer(9, writer, 9) |
| 415 |
|
| 416 |
# add fake fd to pool _all_inqueues to make sure we try to read from outbound_buffer |
| 417 |
# set active_writes to 6 to make sure we remove all write fds except 6 |
| 418 |
pool._active_writes = {6} |
| 419 |
pool._all_inqueues = {2, 6, 8, 9} |
| 420 |
|
| 421 |
pool._create_write_handlers(hub) |
| 422 |
|
| 423 |
# clear outbound_buffer to get IndexError when trying to pop any message |
| 424 |
# in this case all active_writers fds will be removed from the hub |
| 425 |
pool.outbound_buffer.clear() |
| 426 |
|
| 427 |
hub.consolidate_callback(ready_fds=[2]) |
| 428 |
if {6, 8, 9} <= hub.readers.keys() and not {8, 9} <= hub.writers.keys(): |
| 429 |
assert True |
| 430 |
else: |
| 431 |
assert False |
| 432 |
|
| 433 |
assert 6 in hub.writers |
| 434 |
|
| 435 |
@t.skip.if_pypy |
| 436 |
def test_schedule_writes_hub_remove_fd_only_from_writers_when_write_job_is_done(self): |
| 437 |
pool = asynpool.AsynPool(threads=False) |
| 438 |
hub = self._get_hub() |
| 439 |
|
| 440 |
writer = Mock(name='writer') |
| 441 |
reader = Mock(name='reader') |
| 442 |
|
| 443 |
# add one writer and one reader with the same fd |
| 444 |
hub.add_writer(2, writer, 2) |
| 445 |
hub.add_reader(2, reader, 2) |
| 446 |
assert 2 in hub.writers |
| 447 |
|
| 448 |
# For test purposes to reach _write_job in schedule writes |
| 449 |
pool._all_inqueues = {2} |
| 450 |
worker = Mock("worker") |
| 451 |
# this lambda need to return a number higher than 4 |
| 452 |
# to pass the while loop in _write_job function and to reach the hub.remove_writer |
| 453 |
worker.send_job_offset = lambda header, HW: 5 |
| 454 |
|
| 455 |
pool._fileno_to_inq[2] = worker |
| 456 |
pool._create_write_handlers(hub) |
| 457 |
|
| 458 |
result = ApplyResult({}, lambda x: True) |
| 459 |
result._payload = [None, None, -1] |
| 460 |
pool.outbound_buffer.appendleft(result) |
| 461 |
|
| 462 |
hub.consolidate_callback(ready_fds=[2]) |
| 463 |
assert 2 not in hub.writers |
| 464 |
assert 2 in hub.readers |
| 465 |
|
| 466 |
@t.skip.if_pypy |
| 467 |
def test_register_with_event_loop__no_on_tick_dupes(self): |
| 468 |
"""Ensure AsynPool's register_with_event_loop only registers |
| 469 |
on_poll_start in the event loop the first time it's called. This |
| 470 |
prevents a leak when the Consumer is restarted. |
| 471 |
""" |
| 472 |
pool = asynpool.AsynPool(threads=False) |
| 473 |
hub = Mock(name='hub') |
| 474 |
pool.register_with_event_loop(hub) |
| 475 |
pool.register_with_event_loop(hub) |
| 476 |
hub.on_tick.add.assert_called_once() |
| 477 |
|
| 478 |
@t.skip.if_pypy |
| 479 |
@patch('billiard.pool.Pool._create_worker_process') |
| 480 |
def test_before_create_process_signal(self, create_process): |
| 481 |
from celery import signals |
| 482 |
on_worker_before_create_process = Mock() |
| 483 |
signals.worker_before_create_process.connect(on_worker_before_create_process) |
| 484 |
pool = asynpool.AsynPool(processes=1, threads=False) |
| 485 |
create_process.assert_called_once_with(0) |
| 486 |
on_worker_before_create_process.assert_any_call( |
| 487 |
signal=signals.worker_before_create_process, |
| 488 |
sender=pool, |
| 489 |
) |
| 490 |
|
| 491 |
def test_untrack_child_process_without_sentinel_poll(self): |
| 492 |
"""_untrack_child_process must not raise when proc lacks _sentinel_poll. |
| 493 |
|
| 494 |
Race condition during cold shutdown can cause _untrack_child_process to |
| 495 |
be called with a process that never had _sentinel_poll set or had it |
| 496 |
cleared. Use getattr for safe access. |
| 497 |
""" |
| 498 |
pytest.importorskip('multiprocessing') |
| 499 |
pool = asynpool.AsynPool(processes=1, threads=False) |
| 500 |
hub = Mock(name='hub') |
| 501 |
proc = object() # No _sentinel_poll attribute |
| 502 |
pool._untrack_child_process(proc, hub) # Should not raise AttributeError |
| 503 |
hub.remove.assert_not_called() |
| 504 |
|
| 505 |
def test_untrack_child_process_with_sentinel_poll(self): |
| 506 |
"""_untrack_child_process cleans up when proc has _sentinel_poll set.""" |
| 507 |
pytest.importorskip('multiprocessing') |
| 508 |
pool = asynpool.AsynPool(processes=1, threads=False) |
| 509 |
hub = Mock(name='hub') |
| 510 |
fd = os.open(os.devnull, os.O_RDONLY) |
| 511 |
proc = Mock(_sentinel_poll=fd) |
| 512 |
pool._untrack_child_process(proc, hub) |
| 513 |
hub.remove.assert_called_once_with(fd) |
| 514 |
assert proc._sentinel_poll is None |
| 515 |
|
| 516 |
@t.skip.if_pypy |
| 517 |
def test_flush_no_synack_discards_unaccepted_jobs(self): |
| 518 |
"""flush() should discard unaccepted jobs when synack is disabled. |
| 519 |
|
| 520 |
Previously, flush() only handled the synack case. Without synack, |
| 521 |
unaccepted jobs were never cleaned from the cache, leading to stale |
| 522 |
entries. |
| 523 |
""" |
| 524 |
pool = asynpool.AsynPool(processes=1, synack=False, threads=False) |
| 525 |
pool._state = asynpool.RUN |
| 526 |
pool.maintain_pool = Mock(name='maintain_pool') |
| 527 |
|
| 528 |
job1 = Mock(name='job1') |
| 529 |
job1._accepted = False |
| 530 |
job1._writer.return_value = None |
| 531 |
job2 = Mock(name='job2') |
| 532 |
job2._accepted = True |
| 533 |
job2._writer.return_value = None |
| 534 |
|
| 535 |
pool._cache = {1: job1, 2: job2} |
| 536 |
pool.outbound_buffer.clear() |
| 537 |
pool._active_writers.clear() |
| 538 |
|
| 539 |
pool.flush() |
| 540 |
|
| 541 |
job1.discard.assert_called_once() |
| 542 |
job2.discard.assert_not_called() |
| 543 |
|
| 544 |
@t.skip.if_pypy |
| 545 |
def test_flush_synack_cancels_unaccepted_jobs(self): |
| 546 |
"""flush() should call _cancel() on unaccepted jobs when synack is enabled.""" |
| 547 |
pool = asynpool.AsynPool(processes=1, synack=True, threads=False) |
| 548 |
pool._state = asynpool.RUN |
| 549 |
pool.maintain_pool = Mock(name='maintain_pool') |
| 550 |
|
| 551 |
job1 = Mock(name='job1') |
| 552 |
job1._accepted = False |
| 553 |
job1._writer.return_value = None |
| 554 |
job2 = Mock(name='job2') |
| 555 |
job2._accepted = True |
| 556 |
job2._writer.return_value = None |
| 557 |
|
| 558 |
pool._cache = {1: job1, 2: job2} |
| 559 |
pool.outbound_buffer.clear() |
| 560 |
pool._active_writers.clear() |
| 561 |
|
| 562 |
pool.flush() |
| 563 |
|
| 564 |
job1._cancel.assert_called_once() |
| 565 |
job1.discard.assert_not_called() |
| 566 |
job2._cancel.assert_not_called() |
| 567 |
|
| 568 |
@t.skip.if_pypy |
| 569 |
@patch('billiard.pool.Pool._create_worker_process') |
| 570 |
def test_flush_dead_process_discards_active_writer(self, _create_worker_process): |
| 571 |
"""flush() must discard generator from _active_writers when process is dead. |
| 572 |
|
| 573 |
Previously, when a process was dead, the generator was never removed |
| 574 |
from _active_writers, causing an infinite loop in the while loop. |
| 575 |
""" |
| 576 |
pool = asynpool.AsynPool(processes=1, synack=False, threads=False) |
| 577 |
pool._state = asynpool.RUN |
| 578 |
pool.maintain_pool = Mock(name='maintain_pool') |
| 579 |
|
| 580 |
# Create a mock generator (already started, so not gen_not_started) |
| 581 |
gen = Mock(name='gen') |
| 582 |
gen.__name__ = '_write_job' |
| 583 |
# Simulate a started generator |
| 584 |
with patch.object(asynpool, 'gen_not_started', return_value=False): |
| 585 |
proc = Mock(name='proc') |
| 586 |
proc._is_alive.return_value = False # Process is dead |
| 587 |
|
| 588 |
job = Mock(name='job') |
| 589 |
job._accepted = True |
| 590 |
job._write_to = proc |
| 591 |
job._writer.return_value = gen |
| 592 |
|
| 593 |
pool._cache = {1: job} |
| 594 |
pool._active_writers = {gen} |
| 595 |
pool.outbound_buffer.clear() |
| 596 |
|
| 597 |
pool.flush() |
| 598 |
|
| 599 |
# Generator should have been removed from active_writers |
| 600 |
assert gen not in pool._active_writers |
| 601 |
# Job should have been discarded since process is dead |
| 602 |
job.discard.assert_called() |
| 603 |
|
| 604 |
@t.skip.if_pypy |
| 605 |
@patch('billiard.pool.Pool._create_worker_process') |
| 606 |
def test_flush_alive_process_flushes_writer(self, _create_worker_process): |
| 607 |
"""flush() should call _flush_writer when process is still alive.""" |
| 608 |
pool = asynpool.AsynPool(processes=1, synack=False, threads=False) |
| 609 |
pool._state = asynpool.RUN |
| 610 |
pool.maintain_pool = Mock(name='maintain_pool') |
| 611 |
|
| 612 |
gen = Mock(name='gen') |
| 613 |
gen.__name__ = '_write_job' |
| 614 |
|
| 615 |
with patch.object(asynpool, 'gen_not_started', return_value=False): |
| 616 |
proc = Mock(name='proc') |
| 617 |
proc._is_alive.return_value = True |
| 618 |
|
| 619 |
job = Mock(name='job') |
| 620 |
job._accepted = True |
| 621 |
job._write_to = proc |
| 622 |
job._writer.return_value = gen |
| 623 |
|
| 624 |
pool._cache = {1: job} |
| 625 |
pool._active_writers = {gen} |
| 626 |
pool.outbound_buffer.clear() |
| 627 |
|
| 628 |
with patch.object(pool, '_flush_writer') as mock_flush: |
| 629 |
# _flush_writer removes from _active_writers in its finally |
| 630 |
def side_effect(p, g): |
| 631 |
pool._active_writers.discard(g) |
| 632 |
mock_flush.side_effect = side_effect |
| 633 |
|
| 634 |
pool.flush() |
| 635 |
|
| 636 |
mock_flush.assert_called_once_with(proc, gen) |
| 637 |
|
| 638 |
@t.skip.if_pypy |
| 639 |
@patch('billiard.pool.Pool._create_worker_process') |
| 640 |
def test_flush_write_ack_coroutine_is_advanced_not_dropped(self, _create_worker_process): |
| 641 |
"""flush() must not silently drop _write_ack generators (synack mode). |
| 642 |
|
| 643 |
_write_ack coroutines are added to _active_writers by send_ack() but |
| 644 |
are NOT mapped in owned_by (which is built from _cache job writers only). |
| 645 |
Dropping them mid-write leaves a partially-written ack on the synq pipe |
| 646 |
and hangs the worker process waiting for the ack that never arrives. |
| 647 |
flush() must advance them to completion instead. |
| 648 |
""" |
| 649 |
pool = asynpool.AsynPool(processes=1, synack=True, threads=False) |
| 650 |
pool._state = asynpool.RUN |
| 651 |
pool.maintain_pool = Mock(name='maintain_pool') |
| 652 |
|
| 653 |
# Simulate a _write_ack generator (name != '_write_job', not in owned_by) |
| 654 |
ack_gen = Mock(name='ack_gen') |
| 655 |
ack_gen.__name__ = '_write_ack' |
| 656 |
# First call to next() returns normally (still writing), |
| 657 |
# second raises StopIteration (write complete). |
| 658 |
ack_gen.__next__ = Mock(side_effect=[None, StopIteration()]) |
| 659 |
|
| 660 |
pool._cache = {} |
| 661 |
pool._active_writers = {ack_gen} |
| 662 |
pool.outbound_buffer.clear() |
| 663 |
|
| 664 |
pool.flush() |
| 665 |
|
| 666 |
# Generator should have been advanced (not just silently discarded) |
| 667 |
assert ack_gen.__next__.called |
| 668 |
# And removed once it signalled completion |
| 669 |
assert ack_gen not in pool._active_writers |
| 670 |
|
| 671 |
@t.skip.if_pypy |
| 672 |
@patch('billiard.pool.Pool._create_worker_process') |
| 673 |
def test_flush_write_ack_coroutine_handles_oserror(self, _create_worker_process): |
| 674 |
"""flush() should discard the coroutine if OSError is raised during next().""" |
| 675 |
pool = asynpool.AsynPool(processes=1, synack=True, threads=False) |
| 676 |
pool._state = asynpool.RUN |
| 677 |
pool.maintain_pool = Mock(name='maintain_pool') |
| 678 |
|
| 679 |
ack_gen = MagicMock(name='ack_gen') |
| 680 |
ack_gen.__name__ = '_write_ack' |
| 681 |
ack_gen.__next__.side_effect = OSError() |
| 682 |
|
| 683 |
pool._cache = {} |
| 684 |
pool._active_writers = {ack_gen} |
| 685 |
pool.outbound_buffer.clear() |
| 686 |
pool.flush() |
| 687 |
|
| 688 |
assert ack_gen not in pool._active_writers |
| 689 |
|
| 690 |
@t.skip.if_pypy |
| 691 |
@patch('billiard.pool.Pool._create_worker_process') |
| 692 |
def test_flush_write_ack_coroutine_handles_eoferror(self, _create_worker_process): |
| 693 |
"""flush() should discard the coroutine if EOFError is raised during next().""" |
| 694 |
pool = asynpool.AsynPool(processes=1, synack=True, threads=False) |
| 695 |
pool._state = asynpool.RUN |
| 696 |
pool.maintain_pool = Mock(name='maintain_pool') |
| 697 |
|
| 698 |
ack_gen = MagicMock(name='ack_gen') |
| 699 |
ack_gen.__name__ = '_write_ack' |
| 700 |
ack_gen.__next__.side_effect = EOFError() |
| 701 |
|
| 702 |
pool._cache = {} |
| 703 |
pool._active_writers = {ack_gen} |
| 704 |
pool.outbound_buffer.clear() |
| 705 |
pool.flush() |
| 706 |
|
| 707 |
assert ack_gen not in pool._active_writers |
| 708 |
|
| 709 |
@t.skip.if_pypy |
| 710 |
@patch('billiard.pool.Pool._create_worker_process') |
| 711 |
def test_flush_not_started_write_job_is_discarded(self, _create_worker_process): |
| 712 |
"""flush() should discard a _write_job generator that has not started yet. |
| 713 |
|
| 714 |
When gen_not_started() returns True the job has not been written to the |
| 715 |
pipe at all, so it is safe to discard it and let the broker redeliver. |
| 716 |
""" |
| 717 |
pool = asynpool.AsynPool(processes=1, synack=False, threads=False) |
| 718 |
pool._state = asynpool.RUN |
| 719 |
pool.maintain_pool = Mock(name='maintain_pool') |
| 720 |
|
| 721 |
gen = Mock(name='gen') |
| 722 |
gen.__name__ = '_write_job' |
| 723 |
|
| 724 |
with patch.object(asynpool, 'gen_not_started', return_value=True): |
| 725 |
job = Mock(name='job') |
| 726 |
job._accepted = True |
| 727 |
job._writer.return_value = gen |
| 728 |
|
| 729 |
pool._cache = {1: job} |
| 730 |
pool._active_writers = {gen} |
| 731 |
pool.outbound_buffer.clear() |
| 732 |
|
| 733 |
pool.flush() |
| 734 |
|
| 735 |
job.discard.assert_called_once() |
| 736 |
assert gen not in pool._active_writers |
| 737 |
|
| 738 |
def test_process_result(self): |
| 739 |
x = asynpool.ResultHandler( |
| 740 |
Mock(), Mock(), {}, Mock(), |
| 741 |
Mock(), Mock(), Mock(), Mock(), |
| 742 |
fileno_to_outq={}, |
| 743 |
on_process_alive=Mock(), |
| 744 |
on_job_ready=Mock(), |
| 745 |
) |
| 746 |
assert x |
| 747 |
hub = Mock(name='hub') |
| 748 |
recv = x._recv_message = Mock(name='recv_message') |
| 749 |
recv.return_value = iter([]) |
| 750 |
x.on_state_change = Mock() |
| 751 |
x.register_with_event_loop(hub) |
| 752 |
proc = x.fileno_to_outq[3] = Mock() |
| 753 |
reader = proc.outq._reader |
| 754 |
reader.poll.return_value = False |
| 755 |
x.handle_event(6) # KeyError |
| 756 |
x.handle_event(3) |
| 757 |
x._recv_message.assert_called_with( |
| 758 |
hub.add_reader, 3, x.on_state_change, |
| 759 |
) |
| 760 |
|
| 761 |
|
| 762 |
class test_TaskPool: |
| 763 |
|
| 764 |
def test_start(self): |
| 765 |
pool = TaskPool(10) |
| 766 |
pool.start() |
| 767 |
assert pool._pool.started |
| 768 |
assert pool._pool._state == asynpool.RUN |
| 769 |
|
| 770 |
_pool = pool._pool |
| 771 |
pool.stop() |
| 772 |
assert _pool.closed |
| 773 |
assert _pool.joined |
| 774 |
pool.stop() |
| 775 |
|
| 776 |
pool.start() |
| 777 |
_pool = pool._pool |
| 778 |
pool.terminate() |
| 779 |
pool.terminate() |
| 780 |
assert _pool.terminated |
| 781 |
|
| 782 |
def test_restart(self): |
| 783 |
pool = TaskPool(10) |
| 784 |
pool._pool = Mock(name='pool') |
| 785 |
pool.restart() |
| 786 |
pool._pool.restart.assert_called_with() |
| 787 |
pool._pool.apply_async.assert_called_with(mp.noop) |
| 788 |
|
| 789 |
def test_did_start_ok(self): |
| 790 |
pool = TaskPool(10) |
| 791 |
pool._pool = Mock(name='pool') |
| 792 |
assert pool.did_start_ok() is pool._pool.did_start_ok() |
| 793 |
|
| 794 |
def test_register_with_event_loop(self): |
| 795 |
pool = TaskPool(10) |
| 796 |
pool._pool = Mock(name='pool') |
| 797 |
loop = Mock(name='loop') |
| 798 |
pool.register_with_event_loop(loop) |
| 799 |
pool._pool.register_with_event_loop.assert_called_with(loop) |
| 800 |
|
| 801 |
def test_on_close(self): |
| 802 |
pool = TaskPool(10) |
| 803 |
pool._pool = Mock(name='pool') |
| 804 |
pool._pool._state = mp.RUN |
| 805 |
pool.on_close() |
| 806 |
pool._pool.close.assert_called_with() |
| 807 |
|
| 808 |
def test_on_close__pool_not_running(self): |
| 809 |
pool = TaskPool(10) |
| 810 |
pool._pool = Mock(name='pool') |
| 811 |
pool._pool._state = mp.CLOSE |
| 812 |
pool.on_close() |
| 813 |
pool._pool.close.assert_not_called() |
| 814 |
|
| 815 |
@patch('celery.concurrency.prefork.get_event_loop') |
| 816 |
@patch('celery.concurrency.prefork.threading.Thread') |
| 817 |
def test_on_stop_with_hub_fires_timers(self, mock_thread, mock_get_event_loop): |
| 818 |
pool = TaskPool(10) |
| 819 |
mock_pool = Mock(name='pool') |
| 820 |
mock_pool._state = mp.RUN |
| 821 |
pool._pool = mock_pool |
| 822 |
|
| 823 |
mock_hub = Mock(name='hub') |
| 824 |
mock_get_event_loop.return_value = mock_hub |
| 825 |
mock_timer_thread = Mock(name='timer_thread') |
| 826 |
mock_thread.return_value = mock_timer_thread |
| 827 |
|
| 828 |
pool.on_stop() |
| 829 |
|
| 830 |
mock_pool.close.assert_called_with() |
| 831 |
mock_pool.join.assert_called_with() |
| 832 |
mock_get_event_loop.assert_called_once() |
| 833 |
mock_thread.assert_called_once() |
| 834 |
assert mock_thread.call_args[1]['daemon'] is True |
| 835 |
mock_timer_thread.start.assert_called_once() |
| 836 |
mock_timer_thread.join.assert_called_once_with(timeout=1.0) |
| 837 |
|
| 838 |
@patch('celery.concurrency.prefork.get_event_loop') |
| 839 |
@patch('celery.concurrency.prefork.threading.Thread') |
| 840 |
@patch('celery.concurrency.prefork.threading.Event') |
| 841 |
def test_on_stop_timer_thread_handles_exceptions( |
| 842 |
self, |
| 843 |
mock_event_class, |
| 844 |
mock_thread, |
| 845 |
mock_get_event_loop, |
| 846 |
): |
| 847 |
pool = TaskPool(10) |
| 848 |
mock_pool = Mock(name='pool') |
| 849 |
mock_pool._state = mp.RUN |
| 850 |
pool._pool = mock_pool |
| 851 |
|
| 852 |
mock_hub = Mock(name='hub') |
| 853 |
mock_hub.fire_timers.side_effect = [Exception("Hub error"), None] |
| 854 |
mock_get_event_loop.return_value = mock_hub |
| 855 |
|
| 856 |
mock_shutdown_event = Mock(name='shutdown_event') |
| 857 |
# Simulate two loop iterations and then shutdown |
| 858 |
mock_shutdown_event.is_set.side_effect = [False, False, True] |
| 859 |
mock_event_class.return_value = mock_shutdown_event |
| 860 |
|
| 861 |
thread_target = None |
| 862 |
|
| 863 |
def capture_thread(*args, **kwargs): |
| 864 |
nonlocal thread_target |
| 865 |
thread_target = kwargs['target'] |
| 866 |
mock_timer_thread = Mock(name='timer_thread') |
| 867 |
return mock_timer_thread |
| 868 |
|
| 869 |
mock_thread.side_effect = capture_thread |
| 870 |
|
| 871 |
pool.on_stop() |
| 872 |
|
| 873 |
with patch('celery.concurrency.prefork.time.sleep'): |
| 874 |
thread_target() |
| 875 |
|
| 876 |
# Should match number of loop iterations allowed by mock_shutdown_event.is_set.side_effect |
| 877 |
assert mock_hub.fire_timers.call_count == 2 |
| 878 |
|
| 879 |
@patch('celery.concurrency.prefork.get_event_loop') |
| 880 |
def test_on_stop_no_hub(self, mock_get_event_loop): |
| 881 |
pool = TaskPool(10) |
| 882 |
mock_pool = Mock(name='pool') |
| 883 |
mock_pool._state = mp.RUN |
| 884 |
pool._pool = mock_pool |
| 885 |
|
| 886 |
mock_get_event_loop.return_value = None |
| 887 |
|
| 888 |
pool.on_stop() |
| 889 |
|
| 890 |
mock_pool.close.assert_called_with() |
| 891 |
mock_pool.join.assert_called_with() |
| 892 |
mock_get_event_loop.assert_called_once() |
| 893 |
|
| 894 |
def test_apply_async(self): |
| 895 |
pool = TaskPool(10) |
| 896 |
pool.start() |
| 897 |
pool.apply_async(lambda x: x, (2,), {}) |
| 898 |
|
| 899 |
def test_grow_shrink(self): |
| 900 |
pool = TaskPool(10) |
| 901 |
pool.start() |
| 902 |
assert pool._pool._processes == 10 |
| 903 |
pool.grow() |
| 904 |
assert pool._pool._processes == 11 |
| 905 |
pool.shrink(2) |
| 906 |
assert pool._pool._processes == 9 |
| 907 |
|
| 908 |
def test_info(self): |
| 909 |
pool = TaskPool(10) |
| 910 |
procs = [Bunch(pid=i) for i in range(pool.limit)] |
| 911 |
|
| 912 |
class _Pool: |
| 913 |
_pool = procs |
| 914 |
_maxtasksperchild = None |
| 915 |
timeout = 10 |
| 916 |
soft_timeout = 5 |
| 917 |
|
| 918 |
def human_write_stats(self, *args, **kwargs): |
| 919 |
return {} |
| 920 |
pool._pool = _Pool() |
| 921 |
info = pool.info |
| 922 |
assert info['max-concurrency'] == pool.limit |
| 923 |
assert info['max-tasks-per-child'] == 'N/A' |
| 924 |
assert info['timeouts'] == (5, 10) |
| 925 |
|
| 926 |
def test_num_processes(self): |
| 927 |
pool = TaskPool(7) |
| 928 |
pool.start() |
| 929 |
assert pool.num_processes == 7 |
| 930 |
|
| 931 |
@patch('billiard.forking_enable') |
| 932 |
def test_on_start_proc_alive_timeout_default(self, __forking_enable): |
| 933 |
app = Mock(conf=AttributeDict(DEFAULTS)) |
| 934 |
pool = TaskPool(4, app=app) |
| 935 |
pool.on_start() |
| 936 |
assert pool._pool._proc_alive_timeout == 4.0 |
| 937 |
|
| 938 |
@patch('billiard.forking_enable') |
| 939 |
def test_on_start_proc_alive_timeout_custom(self, __forking_enable): |
| 940 |
app = Mock(conf=AttributeDict(DEFAULTS)) |
| 941 |
app.conf.worker_proc_alive_timeout = 8.0 |
| 942 |
pool = TaskPool(4, app=app) |
| 943 |
pool.on_start() |
| 944 |
assert pool._pool._proc_alive_timeout == 8.0 |