| 1 |
import errno |
| 2 |
import logging |
| 3 |
import socket |
| 4 |
from collections import deque |
| 5 |
from unittest.mock import MagicMock, Mock, call, patch |
| 6 |
|
| 7 |
import pytest |
| 8 |
from amqp import ChannelError |
| 9 |
from billiard.exceptions import RestartFreqExceeded |
| 10 |
|
| 11 |
from celery import bootsteps |
| 12 |
from celery.contrib.testing.mocks import ContextMock |
| 13 |
from celery.exceptions import WorkerShutdown, WorkerTerminate |
| 14 |
from celery.utils.collections import LimitedSet |
| 15 |
from celery.utils.quorum_queues import detect_quorum_queues |
| 16 |
from celery.worker.consumer.agent import Agent |
| 17 |
from celery.worker.consumer.consumer import CANCEL_TASKS_BY_DEFAULT, CLOSE, TERMINATE, Consumer |
| 18 |
from celery.worker.consumer.gossip import Gossip |
| 19 |
from celery.worker.consumer.heart import Heart |
| 20 |
from celery.worker.consumer.mingle import Mingle |
| 21 |
from celery.worker.consumer.tasks import Tasks |
| 22 |
from celery.worker.state import active_requests, successful_requests |
| 23 |
|
| 24 |
|
| 25 |
class ConsumerTestCase: |
| 26 |
def get_consumer(self, no_hub=False, **kwargs): |
| 27 |
consumer = Consumer( |
| 28 |
on_task_request=Mock(), |
| 29 |
init_callback=Mock(), |
| 30 |
pool=Mock(), |
| 31 |
app=self.app, |
| 32 |
timer=Mock(), |
| 33 |
controller=Mock(), |
| 34 |
hub=None if no_hub else Mock(), |
| 35 |
**kwargs |
| 36 |
) |
| 37 |
consumer.blueprint = Mock(name='blueprint') |
| 38 |
consumer.pool.num_processes = 2 |
| 39 |
consumer._restart_state = Mock(name='_restart_state') |
| 40 |
consumer.connection = _amqp_connection() |
| 41 |
consumer.connection_errors = (socket.error, OSError,) |
| 42 |
consumer.conninfo = consumer.connection |
| 43 |
return consumer |
| 44 |
|
| 45 |
|
| 46 |
class test_Consumer(ConsumerTestCase): |
| 47 |
def setup_method(self): |
| 48 |
@self.app.task(shared=False) |
| 49 |
def add(x, y): |
| 50 |
return x + y |
| 51 |
|
| 52 |
self.add = add |
| 53 |
|
| 54 |
def test_repr(self): |
| 55 |
assert repr(self.get_consumer()) |
| 56 |
|
| 57 |
def test_taskbuckets_defaultdict(self): |
| 58 |
c = self.get_consumer() |
| 59 |
assert c.task_buckets['fooxasdwx.wewe'] is None |
| 60 |
|
| 61 |
def test_sets_heartbeat(self): |
| 62 |
c = self.get_consumer(amqheartbeat=10) |
| 63 |
assert c.amqheartbeat == 10 |
| 64 |
self.app.conf.broker_heartbeat = 20 |
| 65 |
c = self.get_consumer(amqheartbeat=None) |
| 66 |
assert c.amqheartbeat == 20 |
| 67 |
|
| 68 |
def test_gevent_bug_disables_connection_timeout(self): |
| 69 |
with patch('celery.worker.consumer.consumer._detect_environment') as d: |
| 70 |
d.return_value = 'gevent' |
| 71 |
self.app.conf.broker_connection_timeout = 33.33 |
| 72 |
self.get_consumer() |
| 73 |
assert self.app.conf.broker_connection_timeout is None |
| 74 |
|
| 75 |
def test_limit_moved_to_pool(self): |
| 76 |
with patch('celery.worker.consumer.consumer.task_reserved') as task_reserved: |
| 77 |
c = self.get_consumer() |
| 78 |
c.on_task_request = Mock(name='on_task_request') |
| 79 |
request = Mock(name='request') |
| 80 |
c._limit_move_to_pool(request) |
| 81 |
task_reserved.assert_called_with(request) |
| 82 |
c.on_task_request.assert_called_with(request) |
| 83 |
|
| 84 |
def test_update_prefetch_count(self): |
| 85 |
c = self.get_consumer() |
| 86 |
c._update_qos_eventually = Mock(name='update_qos') |
| 87 |
c.initial_prefetch_count = None |
| 88 |
c.pool.num_processes = None |
| 89 |
c.prefetch_multiplier = 10 |
| 90 |
assert c._update_prefetch_count(1) is None |
| 91 |
c.initial_prefetch_count = 10 |
| 92 |
c.pool.num_processes = 10 |
| 93 |
c._update_prefetch_count(8) |
| 94 |
c._update_qos_eventually.assert_called_with(8) |
| 95 |
assert c.initial_prefetch_count == 10 * 10 |
| 96 |
|
| 97 |
@pytest.mark.parametrize( |
| 98 |
'active_requests_count,expected_initial,expected_maximum,enabled', |
| 99 |
[ |
| 100 |
[0, 2, True, True], |
| 101 |
[1, 1, False, True], |
| 102 |
[2, 1, False, True], |
| 103 |
[0, 2, True, False], |
| 104 |
[1, 2, True, False], |
| 105 |
[2, 2, True, False], |
| 106 |
] |
| 107 |
) |
| 108 |
@patch('celery.worker.consumer.consumer.active_requests', new_callable=set) |
| 109 |
def test_restore_prefetch_count_on_restart(self, active_requests_mock, active_requests_count, |
| 110 |
expected_initial, expected_maximum, enabled, subtests): |
| 111 |
self.app.conf.worker_enable_prefetch_count_reduction = enabled |
| 112 |
|
| 113 |
reqs = {Mock() for _ in range(active_requests_count)} |
| 114 |
active_requests_mock.update(reqs) |
| 115 |
|
| 116 |
c = self.get_consumer() |
| 117 |
c.qos = Mock() |
| 118 |
c.blueprint = Mock() |
| 119 |
|
| 120 |
def bp_start(*_, **__): |
| 121 |
if c.restart_count > 1: |
| 122 |
c.blueprint.state = CLOSE |
| 123 |
else: |
| 124 |
raise ConnectionError |
| 125 |
|
| 126 |
c.blueprint.start.side_effect = bp_start |
| 127 |
|
| 128 |
c.start() |
| 129 |
|
| 130 |
with subtests.test("initial prefetch count is never 0"): |
| 131 |
assert c.initial_prefetch_count != 0 |
| 132 |
|
| 133 |
with subtests.test(f"initial prefetch count is equal to {expected_initial}"): |
| 134 |
assert c.initial_prefetch_count == expected_initial |
| 135 |
|
| 136 |
with subtests.test("maximum prefetch is reached"): |
| 137 |
assert c._maximum_prefetch_restored is expected_maximum |
| 138 |
|
| 139 |
def test_restore_prefetch_count_after_connection_restart_negative(self): |
| 140 |
self.app.conf.worker_enable_prefetch_count_reduction = False |
| 141 |
|
| 142 |
c = self.get_consumer() |
| 143 |
c.qos = Mock() |
| 144 |
|
| 145 |
# Overcome TypeError: 'Mock' object does not support the context manager protocol |
| 146 |
class MutexMock: |
| 147 |
def __enter__(self): |
| 148 |
pass |
| 149 |
|
| 150 |
def __exit__(self, *args): |
| 151 |
pass |
| 152 |
|
| 153 |
c.qos._mutex = MutexMock() |
| 154 |
|
| 155 |
assert c._restore_prefetch_count_after_connection_restart(None) is None |
| 156 |
|
| 157 |
def test_create_task_handler(self, subtests): |
| 158 |
c = self.get_consumer() |
| 159 |
c.qos = MagicMock() |
| 160 |
c.qos.value = 1 |
| 161 |
c._maximum_prefetch_restored = False |
| 162 |
|
| 163 |
sig = self.add.s(2, 2) |
| 164 |
message = self.task_message_from_sig(self.app, sig) |
| 165 |
|
| 166 |
def raise_exception(): |
| 167 |
raise KeyError('Foo') |
| 168 |
|
| 169 |
def strategy(_, __, ack_log_error_promise, ___, ____): |
| 170 |
ack_log_error_promise() |
| 171 |
|
| 172 |
c.strategies[sig.task] = strategy |
| 173 |
c.call_soon = raise_exception |
| 174 |
on_task_received = c.create_task_handler() |
| 175 |
on_task_received(message) |
| 176 |
|
| 177 |
with subtests.test("initial prefetch count is never 0"): |
| 178 |
assert c.initial_prefetch_count != 0 |
| 179 |
|
| 180 |
with subtests.test("initial prefetch count is 2"): |
| 181 |
assert c.initial_prefetch_count == 2 |
| 182 |
|
| 183 |
with subtests.test("maximum prefetch is reached"): |
| 184 |
assert c._maximum_prefetch_restored is True |
| 185 |
|
| 186 |
def test_flush_events(self): |
| 187 |
c = self.get_consumer() |
| 188 |
c.event_dispatcher = None |
| 189 |
c._flush_events() |
| 190 |
c.event_dispatcher = Mock(name='evd') |
| 191 |
c._flush_events() |
| 192 |
c.event_dispatcher.flush.assert_called_with() |
| 193 |
|
| 194 |
def test_on_send_event_buffered(self): |
| 195 |
c = self.get_consumer() |
| 196 |
c.hub = None |
| 197 |
c.on_send_event_buffered() |
| 198 |
c.hub = Mock(name='hub') |
| 199 |
c.on_send_event_buffered() |
| 200 |
c.hub._ready.add.assert_called_with(c._flush_events) |
| 201 |
|
| 202 |
def test_schedule_bucket_request(self): |
| 203 |
c = self.get_consumer() |
| 204 |
c.timer = Mock() |
| 205 |
|
| 206 |
bucket = Mock() |
| 207 |
request = Mock() |
| 208 |
bucket.pop = lambda: bucket.contents.popleft() |
| 209 |
bucket.can_consume.return_value = True |
| 210 |
bucket.contents = deque() |
| 211 |
|
| 212 |
with patch( |
| 213 |
'celery.worker.consumer.consumer.Consumer._limit_move_to_pool' |
| 214 |
) as task_reserved: |
| 215 |
bucket.contents.append((request, 3)) |
| 216 |
c._schedule_bucket_request(bucket) |
| 217 |
bucket.can_consume.assert_called_with(3) |
| 218 |
task_reserved.assert_called_with(request) |
| 219 |
|
| 220 |
bucket.can_consume.return_value = False |
| 221 |
bucket.contents = deque() |
| 222 |
bucket.expected_time.return_value = 3.33 |
| 223 |
bucket.contents.append((request, 4)) |
| 224 |
limit_order = c._limit_order |
| 225 |
c._schedule_bucket_request(bucket) |
| 226 |
assert c._limit_order == limit_order + 1 |
| 227 |
bucket.can_consume.assert_called_with(4) |
| 228 |
c.timer.call_after.assert_called_with( |
| 229 |
3.33, c._schedule_bucket_request, (bucket,), |
| 230 |
priority=c._limit_order, |
| 231 |
) |
| 232 |
bucket.expected_time.assert_called_with(4) |
| 233 |
assert bucket.pop() == (request, 4) |
| 234 |
|
| 235 |
bucket.contents = deque() |
| 236 |
bucket.can_consume.reset_mock() |
| 237 |
c._schedule_bucket_request(bucket) |
| 238 |
bucket.can_consume.assert_not_called() |
| 239 |
|
| 240 |
def test_limit_task(self): |
| 241 |
c = self.get_consumer() |
| 242 |
bucket = Mock() |
| 243 |
request = Mock() |
| 244 |
|
| 245 |
with patch( |
| 246 |
'celery.worker.consumer.consumer.Consumer._schedule_bucket_request' |
| 247 |
) as task_reserved: |
| 248 |
c._limit_task(request, bucket, 1) |
| 249 |
bucket.add.assert_called_with((request, 1)) |
| 250 |
task_reserved.assert_called_with(bucket) |
| 251 |
|
| 252 |
def test_post_eta(self): |
| 253 |
c = self.get_consumer() |
| 254 |
c.qos = Mock() |
| 255 |
bucket = Mock() |
| 256 |
request = Mock() |
| 257 |
|
| 258 |
with patch( |
| 259 |
'celery.worker.consumer.consumer.Consumer._schedule_bucket_request' |
| 260 |
) as task_reserved: |
| 261 |
c._limit_post_eta(request, bucket, 1) |
| 262 |
c.qos.decrement_eventually.assert_called_with() |
| 263 |
bucket.add.assert_called_with((request, 1)) |
| 264 |
task_reserved.assert_called_with(bucket) |
| 265 |
|
| 266 |
def test_max_restarts_exceeded(self): |
| 267 |
c = self.get_consumer() |
| 268 |
|
| 269 |
def se(*args, **kwargs): |
| 270 |
c.blueprint.state = CLOSE |
| 271 |
raise RestartFreqExceeded() |
| 272 |
|
| 273 |
c._restart_state.step.side_effect = se |
| 274 |
c.blueprint.start.side_effect = socket.error() |
| 275 |
|
| 276 |
with patch('celery.worker.consumer.consumer.sleep') as sleep: |
| 277 |
c.start() |
| 278 |
sleep.assert_called_with(1) |
| 279 |
|
| 280 |
def test_do_not_restart_when_closed(self): |
| 281 |
c = self.get_consumer() |
| 282 |
|
| 283 |
c.blueprint.state = None |
| 284 |
|
| 285 |
def bp_start(*args, **kwargs): |
| 286 |
c.blueprint.state = CLOSE |
| 287 |
|
| 288 |
c.blueprint.start.side_effect = bp_start |
| 289 |
with patch('celery.worker.consumer.consumer.sleep'): |
| 290 |
c.start() |
| 291 |
|
| 292 |
c.blueprint.start.assert_called_once_with(c) |
| 293 |
|
| 294 |
def test_do_not_restart_when_terminated(self): |
| 295 |
c = self.get_consumer() |
| 296 |
|
| 297 |
c.blueprint.state = None |
| 298 |
|
| 299 |
def bp_start(*args, **kwargs): |
| 300 |
c.blueprint.state = TERMINATE |
| 301 |
|
| 302 |
c.blueprint.start.side_effect = bp_start |
| 303 |
|
| 304 |
with patch('celery.worker.consumer.consumer.sleep'): |
| 305 |
c.start() |
| 306 |
|
| 307 |
c.blueprint.start.assert_called_once_with(c) |
| 308 |
|
| 309 |
def test_too_many_open_files_raises_error(self): |
| 310 |
c = self.get_consumer() |
| 311 |
err = OSError() |
| 312 |
err.errno = errno.EMFILE |
| 313 |
c.blueprint.start.side_effect = err |
| 314 |
with pytest.raises(WorkerTerminate): |
| 315 |
c.start() |
| 316 |
|
| 317 |
def _closer(self, c): |
| 318 |
def se(*args, **kwargs): |
| 319 |
c.blueprint.state = CLOSE |
| 320 |
|
| 321 |
return se |
| 322 |
|
| 323 |
@pytest.mark.parametrize("broker_connection_retry", [True, False]) |
| 324 |
def test_blueprint_restart_when_state_not_in_stop_conditions(self, broker_connection_retry): |
| 325 |
c = self.get_consumer() |
| 326 |
|
| 327 |
# ensure that WorkerShutdown is not raised |
| 328 |
c.app.conf['broker_connection_retry'] = broker_connection_retry |
| 329 |
c.app.conf['broker_connection_retry_on_startup'] = True |
| 330 |
c.restart_count = -1 |
| 331 |
|
| 332 |
# ensure that blueprint state is not in stop conditions |
| 333 |
c.blueprint.state = bootsteps.RUN |
| 334 |
c.blueprint.start.side_effect = ConnectionError() |
| 335 |
|
| 336 |
# stops test from running indefinitely in the while loop |
| 337 |
c.blueprint.restart.side_effect = self._closer(c) |
| 338 |
|
| 339 |
c.start() |
| 340 |
c.blueprint.restart.assert_called_once() |
| 341 |
|
| 342 |
@pytest.mark.parametrize("broker_channel_error_retry", [True, False]) |
| 343 |
def test_blueprint_restart_for_channel_errors(self, broker_channel_error_retry): |
| 344 |
c = self.get_consumer() |
| 345 |
|
| 346 |
# ensure that WorkerShutdown is not raised |
| 347 |
c.app.conf['broker_connection_retry'] = True |
| 348 |
c.app.conf['broker_connection_retry_on_startup'] = True |
| 349 |
c.app.conf['broker_channel_error_retry'] = broker_channel_error_retry |
| 350 |
c.restart_count = -1 |
| 351 |
|
| 352 |
# ensure that blueprint state is not in stop conditions |
| 353 |
c.blueprint.state = bootsteps.RUN |
| 354 |
c.blueprint.start.side_effect = ChannelError() |
| 355 |
|
| 356 |
# stops test from running indefinitely in the while loop |
| 357 |
c.blueprint.restart.side_effect = self._closer(c) |
| 358 |
|
| 359 |
# restarted only when broker_channel_error_retry is True |
| 360 |
if broker_channel_error_retry: |
| 361 |
c.start() |
| 362 |
c.blueprint.restart.assert_called_once() |
| 363 |
else: |
| 364 |
with pytest.raises(ChannelError): |
| 365 |
c.start() |
| 366 |
|
| 367 |
def test_collects_at_restart(self): |
| 368 |
c = self.get_consumer() |
| 369 |
c.connection.collect.side_effect = MemoryError() |
| 370 |
c.blueprint.start.side_effect = socket.error() |
| 371 |
c.blueprint.restart.side_effect = self._closer(c) |
| 372 |
c.start() |
| 373 |
c.connection.collect.assert_called_with() |
| 374 |
|
| 375 |
def test_register_with_event_loop(self): |
| 376 |
c = self.get_consumer() |
| 377 |
c.register_with_event_loop(Mock(name='loop')) |
| 378 |
|
| 379 |
def test_on_close_clears_semaphore_and_reqs(self): |
| 380 |
with patch('celery.worker.consumer.consumer.reserved_requests') as res: |
| 381 |
c = self.get_consumer() |
| 382 |
c.on_close() |
| 383 |
c.controller.semaphore.clear.assert_called_with() |
| 384 |
res.clear.assert_called_with() |
| 385 |
c.pool.flush.assert_called_with() |
| 386 |
|
| 387 |
c.controller = None |
| 388 |
c.timer = None |
| 389 |
c.pool = None |
| 390 |
c.on_close() |
| 391 |
|
| 392 |
def test_connect_error_handler(self): |
| 393 |
self.app._connection = _amqp_connection() |
| 394 |
conn = self.app._connection.return_value |
| 395 |
c = self.get_consumer() |
| 396 |
assert c.connect() |
| 397 |
conn.ensure_connection.assert_called() |
| 398 |
errback = conn.ensure_connection.call_args[0][0] |
| 399 |
errback(Mock(), 0) |
| 400 |
|
| 401 |
@patch('celery.worker.consumer.consumer.error') |
| 402 |
def test_connect_error_handler_progress(self, error): |
| 403 |
self.app.conf.broker_connection_retry = True |
| 404 |
self.app.conf.broker_connection_max_retries = 3 |
| 405 |
self.app._connection = _amqp_connection() |
| 406 |
conn = self.app._connection.return_value |
| 407 |
# Placeholder alt connection to satisfy failover condition |
| 408 |
conn.alt = [conn] |
| 409 |
c = self.get_consumer() |
| 410 |
assert c.connect() |
| 411 |
errback = conn.ensure_connection.call_args[0][0] |
| 412 |
errback(Mock(), 2) |
| 413 |
assert error.call_args[0][3] == 'Trying again in 2.00 seconds... (1/3)' |
| 414 |
errback(Mock(), 4) |
| 415 |
assert error.call_args[0][3] == 'Trying again in 4.00 seconds... (2/3)' |
| 416 |
errback(Mock(), 12) |
| 417 |
assert error.call_args[0][3] == 'Trying again in 12.00 seconds... (3/3)' |
| 418 |
errback(Mock(), 0) |
| 419 |
assert getattr(c, 'broker_connection_retry_attempt', 0) == 3 |
| 420 |
|
| 421 |
def test_cancel_long_running_tasks_on_connection_loss(self): |
| 422 |
c = self.get_consumer() |
| 423 |
c.app.conf.worker_cancel_long_running_tasks_on_connection_loss = True |
| 424 |
|
| 425 |
mock_request_acks_late_not_acknowledged = Mock() |
| 426 |
mock_request_acks_late_not_acknowledged.task.acks_late = True |
| 427 |
mock_request_acks_late_not_acknowledged.acknowledged = False |
| 428 |
mock_request_acks_late_acknowledged = Mock() |
| 429 |
mock_request_acks_late_acknowledged.task.acks_late = True |
| 430 |
mock_request_acks_late_acknowledged.acknowledged = True |
| 431 |
mock_request_acks_early = Mock() |
| 432 |
mock_request_acks_early.task.acks_late = False |
| 433 |
mock_request_acks_early.acknowledged = False |
| 434 |
|
| 435 |
active_requests.add(mock_request_acks_late_not_acknowledged) |
| 436 |
active_requests.add(mock_request_acks_late_acknowledged) |
| 437 |
active_requests.add(mock_request_acks_early) |
| 438 |
|
| 439 |
c.on_connection_error_after_connected(Mock()) |
| 440 |
|
| 441 |
mock_request_acks_late_not_acknowledged.cancel.assert_called_once_with(c.pool) |
| 442 |
mock_request_acks_late_acknowledged.cancel.assert_not_called() |
| 443 |
mock_request_acks_early.cancel.assert_not_called() |
| 444 |
|
| 445 |
active_requests.clear() |
| 446 |
|
| 447 |
def test_cancel_long_running_tasks_on_connection_loss__warning(self): |
| 448 |
c = self.get_consumer() |
| 449 |
c.app.conf.worker_cancel_long_running_tasks_on_connection_loss = False |
| 450 |
|
| 451 |
with pytest.deprecated_call(match=CANCEL_TASKS_BY_DEFAULT): |
| 452 |
c.on_connection_error_after_connected(Mock()) |
| 453 |
|
| 454 |
@pytest.mark.usefixtures('depends_on_current_app') |
| 455 |
def test_cancel_active_requests(self): |
| 456 |
c = self.get_consumer() |
| 457 |
|
| 458 |
mock_request_acks_late_not_acknowledged = Mock(id='1') |
| 459 |
mock_request_acks_late_not_acknowledged.task.acks_late = True |
| 460 |
mock_request_acks_late_not_acknowledged.acknowledged = False |
| 461 |
mock_request_acks_late_acknowledged = Mock(id='2') |
| 462 |
mock_request_acks_late_acknowledged.task.acks_late = True |
| 463 |
mock_request_acks_late_acknowledged.acknowledged = True |
| 464 |
mock_request_acks_early = Mock(id='3') |
| 465 |
mock_request_acks_early.task.acks_late = False |
| 466 |
|
| 467 |
active_requests.add(mock_request_acks_late_not_acknowledged) |
| 468 |
active_requests.add(mock_request_acks_late_acknowledged) |
| 469 |
active_requests.add(mock_request_acks_early) |
| 470 |
|
| 471 |
c.cancel_active_requests() |
| 472 |
|
| 473 |
# acks_late unacknowledged tasks should be cancelled without RETRY |
| 474 |
mock_request_acks_late_not_acknowledged.cancel.assert_called_once_with(c.pool, emit_retry=False) |
| 475 |
# acks_late acknowledged tasks should NOT be cancelled |
| 476 |
mock_request_acks_late_acknowledged.cancel.assert_not_called() |
| 477 |
# Non-acks_late tasks should be cancelled normally (with RETRY) |
| 478 |
mock_request_acks_early.cancel.assert_called_once_with(c.pool, emit_retry=True) |
| 479 |
|
| 480 |
active_requests.clear() |
| 481 |
|
| 482 |
@pytest.mark.usefixtures('depends_on_current_app') |
| 483 |
def test_cancel_active_requests_preserves_successful_tasks(self): |
| 484 |
c = self.get_consumer() |
| 485 |
|
| 486 |
mock_successful_request = Mock(id='successful-task') |
| 487 |
mock_successful_request.task.acks_late = True |
| 488 |
mock_successful_request.acknowledged = False |
| 489 |
|
| 490 |
active_requests.add(mock_successful_request) |
| 491 |
|
| 492 |
successful_requests.add('successful-task') |
| 493 |
|
| 494 |
try: |
| 495 |
c.cancel_active_requests() |
| 496 |
mock_successful_request.cancel.assert_not_called() |
| 497 |
finally: |
| 498 |
active_requests.clear() |
| 499 |
successful_requests.clear() |
| 500 |
|
| 501 |
@pytest.mark.parametrize("broker_connection_retry", [True, False]) |
| 502 |
@pytest.mark.parametrize("broker_connection_retry_on_startup", [None, False]) |
| 503 |
@pytest.mark.parametrize("first_connection_attempt", [True, False]) |
| 504 |
def test_ensure_connected(self, subtests, broker_connection_retry, broker_connection_retry_on_startup, |
| 505 |
first_connection_attempt): |
| 506 |
c = self.get_consumer() |
| 507 |
c.first_connection_attempt = first_connection_attempt |
| 508 |
c.app.conf.broker_connection_retry_on_startup = broker_connection_retry_on_startup |
| 509 |
c.app.conf.broker_connection_retry = broker_connection_retry |
| 510 |
|
| 511 |
if broker_connection_retry is False: |
| 512 |
if broker_connection_retry_on_startup is None: |
| 513 |
with subtests.test("Deprecation warning when startup is None"): |
| 514 |
with pytest.deprecated_call(): |
| 515 |
c.ensure_connected(Mock()) |
| 516 |
|
| 517 |
with subtests.test("Does not retry when connect throws an error and retry is set to false"): |
| 518 |
conn = Mock() |
| 519 |
conn.connect.side_effect = ConnectionError() |
| 520 |
with pytest.raises(ConnectionError): |
| 521 |
c.ensure_connected(conn) |
| 522 |
|
| 523 |
def test_disable_prefetch_not_enabled(self): |
| 524 |
"""Test that disable_prefetch doesn't affect behavior when disabled""" |
| 525 |
self.app.conf.worker_disable_prefetch = False |
| 526 |
|
| 527 |
# Test the core logic by creating a mock consumer and Tasks instance |
| 528 |
from celery.worker.consumer.tasks import Tasks |
| 529 |
consumer = Mock() |
| 530 |
consumer.app = self.app |
| 531 |
consumer.pool = Mock() |
| 532 |
consumer.pool.num_processes = 4 |
| 533 |
consumer.controller = Mock() |
| 534 |
consumer.controller.max_concurrency = None |
| 535 |
consumer.initial_prefetch_count = 16 |
| 536 |
consumer.connection = Mock() |
| 537 |
consumer.connection.connection_errors = () |
| 538 |
consumer.connection.channel_errors = () |
| 539 |
consumer.connection.default_channel = Mock() |
| 540 |
consumer.connection.transport = Mock() |
| 541 |
consumer.connection.transport.driver_type = 'redis' |
| 542 |
consumer.update_strategies = Mock() |
| 543 |
consumer.on_decode_error = Mock() |
| 544 |
|
| 545 |
# Mock task consumer |
| 546 |
consumer.task_consumer = Mock() |
| 547 |
consumer.task_consumer.channel = Mock() |
| 548 |
consumer.task_consumer.channel.qos = Mock() |
| 549 |
original_can_consume = Mock(return_value=True) |
| 550 |
consumer.task_consumer.channel.qos.can_consume = original_can_consume |
| 551 |
consumer.task_consumer.qos = Mock() |
| 552 |
|
| 553 |
consumer.app.amqp = Mock() |
| 554 |
consumer.app.amqp.TaskConsumer = Mock(return_value=consumer.task_consumer) |
| 555 |
|
| 556 |
tasks_instance = Tasks(consumer) |
| 557 |
tasks_instance.start(consumer) |
| 558 |
|
| 559 |
# Should not modify can_consume method when disabled |
| 560 |
assert consumer.task_consumer.channel.qos.can_consume == original_can_consume |
| 561 |
|
| 562 |
def test_disable_prefetch_enabled_basic(self): |
| 563 |
"""Test that disable_prefetch modifies can_consume when enabled""" |
| 564 |
self.app.conf.worker_disable_prefetch = True |
| 565 |
|
| 566 |
# Test the core logic by creating a mock consumer and Tasks instance |
| 567 |
from celery.worker.consumer.tasks import Tasks |
| 568 |
consumer = Mock() |
| 569 |
consumer.app = self.app |
| 570 |
consumer.pool = Mock() |
| 571 |
consumer.pool.num_processes = 4 |
| 572 |
consumer.controller = Mock() |
| 573 |
consumer.controller.max_concurrency = None |
| 574 |
consumer.initial_prefetch_count = 16 |
| 575 |
consumer.connection = Mock() |
| 576 |
consumer.connection.connection_errors = () |
| 577 |
consumer.connection.channel_errors = () |
| 578 |
consumer.connection.default_channel = Mock() |
| 579 |
consumer.connection.transport = Mock() |
| 580 |
consumer.connection.transport.driver_type = 'redis' |
| 581 |
consumer.update_strategies = Mock() |
| 582 |
consumer.on_decode_error = Mock() |
| 583 |
|
| 584 |
# Mock task consumer |
| 585 |
consumer.task_consumer = Mock() |
| 586 |
consumer.task_consumer.channel = Mock() |
| 587 |
consumer.task_consumer.channel.qos = Mock() |
| 588 |
original_can_consume = Mock(return_value=True) |
| 589 |
consumer.task_consumer.channel.qos.can_consume = original_can_consume |
| 590 |
consumer.task_consumer.qos = Mock() |
| 591 |
|
| 592 |
consumer.app.amqp = Mock() |
| 593 |
consumer.app.amqp.TaskConsumer = Mock(return_value=consumer.task_consumer) |
| 594 |
|
| 595 |
tasks_instance = Tasks(consumer) |
| 596 |
|
| 597 |
with patch('celery.worker.state.reserved_requests', []): |
| 598 |
tasks_instance.start(consumer) |
| 599 |
|
| 600 |
# Should modify can_consume method when enabled |
| 601 |
assert callable(consumer.task_consumer.channel.qos.can_consume) |
| 602 |
assert consumer.task_consumer.channel.qos.can_consume != original_can_consume |
| 603 |
|
| 604 |
def test_disable_prefetch_respects_reserved_requests_limit(self): |
| 605 |
"""Test that disable_prefetch respects reserved requests limit""" |
| 606 |
self.app.conf.worker_disable_prefetch = True |
| 607 |
|
| 608 |
# Test the core logic by creating a mock consumer and Tasks instance |
| 609 |
from celery.worker.consumer.tasks import Tasks |
| 610 |
consumer = Mock() |
| 611 |
consumer.app = self.app |
| 612 |
consumer.pool = Mock() |
| 613 |
consumer.pool.num_processes = 4 |
| 614 |
consumer.controller = Mock() |
| 615 |
consumer.controller.max_concurrency = None |
| 616 |
consumer.initial_prefetch_count = 16 |
| 617 |
consumer.connection = Mock() |
| 618 |
consumer.connection.connection_errors = () |
| 619 |
consumer.connection.channel_errors = () |
| 620 |
consumer.connection.default_channel = Mock() |
| 621 |
consumer.connection.transport = Mock() |
| 622 |
consumer.connection.transport.driver_type = 'redis' |
| 623 |
consumer.update_strategies = Mock() |
| 624 |
consumer.on_decode_error = Mock() |
| 625 |
|
| 626 |
# Mock task consumer |
| 627 |
consumer.task_consumer = Mock() |
| 628 |
consumer.task_consumer.channel = Mock() |
| 629 |
consumer.task_consumer.channel.qos = Mock() |
| 630 |
consumer.task_consumer.channel.qos.can_consume = Mock(return_value=True) |
| 631 |
consumer.task_consumer.qos = Mock() |
| 632 |
|
| 633 |
consumer.app.amqp = Mock() |
| 634 |
consumer.app.amqp.TaskConsumer = Mock(return_value=consumer.task_consumer) |
| 635 |
|
| 636 |
tasks_instance = Tasks(consumer) |
| 637 |
|
| 638 |
# Mock 4 reserved requests (at limit of 4) |
| 639 |
mock_requests = [Mock(), Mock(), Mock(), Mock()] |
| 640 |
with patch('celery.worker.state.reserved_requests', mock_requests): |
| 641 |
tasks_instance.start(consumer) |
| 642 |
|
| 643 |
# Should not be able to consume when at limit |
| 644 |
assert consumer.task_consumer.channel.qos.can_consume() is False |
| 645 |
|
| 646 |
def test_disable_prefetch_respects_autoscale_max_concurrency(self): |
| 647 |
"""Test that disable_prefetch respects autoscale max_concurrency limit""" |
| 648 |
self.app.conf.worker_disable_prefetch = True |
| 649 |
|
| 650 |
# Test the core logic by creating a mock consumer and Tasks instance |
| 651 |
from celery.worker.consumer.tasks import Tasks |
| 652 |
consumer = Mock() |
| 653 |
consumer.app = self.app |
| 654 |
consumer.pool = Mock() |
| 655 |
consumer.pool.num_processes = 4 |
| 656 |
consumer.controller = Mock() |
| 657 |
consumer.controller.max_concurrency = 2 # Lower than pool processes |
| 658 |
consumer.initial_prefetch_count = 16 |
| 659 |
consumer.connection = Mock() |
| 660 |
consumer.connection.connection_errors = () |
| 661 |
consumer.connection.channel_errors = () |
| 662 |
consumer.connection.default_channel = Mock() |
| 663 |
consumer.connection.transport = Mock() |
| 664 |
consumer.connection.transport.driver_type = 'redis' |
| 665 |
consumer.update_strategies = Mock() |
| 666 |
consumer.on_decode_error = Mock() |
| 667 |
|
| 668 |
# Mock task consumer |
| 669 |
consumer.task_consumer = Mock() |
| 670 |
consumer.task_consumer.channel = Mock() |
| 671 |
consumer.task_consumer.channel.qos = Mock() |
| 672 |
consumer.task_consumer.channel.qos.can_consume = Mock(return_value=True) |
| 673 |
consumer.task_consumer.qos = Mock() |
| 674 |
|
| 675 |
consumer.app.amqp = Mock() |
| 676 |
consumer.app.amqp.TaskConsumer = Mock(return_value=consumer.task_consumer) |
| 677 |
|
| 678 |
tasks_instance = Tasks(consumer) |
| 679 |
|
| 680 |
# Mock 2 reserved requests (at autoscale limit of 2) |
| 681 |
mock_requests = [Mock(), Mock()] |
| 682 |
with patch('celery.worker.state.reserved_requests', mock_requests): |
| 683 |
tasks_instance.start(consumer) |
| 684 |
|
| 685 |
# Should not be able to consume when at autoscale limit |
| 686 |
assert consumer.task_consumer.channel.qos.can_consume() is False |
| 687 |
|
| 688 |
def test_disable_prefetch_ignored_for_non_redis_brokers(self): |
| 689 |
"""Test that disable_prefetch is ignored for non-Redis brokers.""" |
| 690 |
self.app.conf.worker_disable_prefetch = True |
| 691 |
|
| 692 |
# Test the core logic by creating a mock consumer and Tasks instance |
| 693 |
from celery.worker.consumer.tasks import Tasks |
| 694 |
consumer = Mock() |
| 695 |
consumer.app = self.app |
| 696 |
consumer.pool = Mock() |
| 697 |
consumer.pool.num_processes = 4 |
| 698 |
consumer.controller = Mock() |
| 699 |
consumer.controller.max_concurrency = None |
| 700 |
consumer.initial_prefetch_count = 16 |
| 701 |
consumer.connection = Mock() |
| 702 |
consumer.connection.connection_errors = () |
| 703 |
consumer.connection.channel_errors = () |
| 704 |
consumer.connection.default_channel = Mock() |
| 705 |
consumer.connection.transport = Mock() |
| 706 |
consumer.connection.transport.driver_type = 'amqp' # RabbitMQ |
| 707 |
consumer.connection.qos_semantics_matches_spec = True |
| 708 |
consumer.update_strategies = Mock() |
| 709 |
consumer.on_decode_error = Mock() |
| 710 |
|
| 711 |
# Mock task consumer |
| 712 |
consumer.task_consumer = Mock() |
| 713 |
consumer.task_consumer.channel = Mock() |
| 714 |
consumer.task_consumer.channel.qos = Mock() |
| 715 |
original_can_consume = Mock(return_value=True) |
| 716 |
consumer.task_consumer.channel.qos.can_consume = original_can_consume |
| 717 |
consumer.task_consumer.qos = Mock() |
| 718 |
|
| 719 |
consumer.app.amqp = Mock() |
| 720 |
consumer.app.amqp.TaskConsumer = Mock(return_value=consumer.task_consumer) |
| 721 |
consumer.app.amqp.queues = {} # Empty dict for quorum queue detection |
| 722 |
|
| 723 |
tasks_instance = Tasks(consumer) |
| 724 |
tasks_instance.start(consumer) |
| 725 |
|
| 726 |
# Should not modify can_consume method for non-Redis brokers |
| 727 |
assert consumer.task_consumer.channel.qos.can_consume == original_can_consume |
| 728 |
|
| 729 |
|
| 730 |
@pytest.mark.parametrize( |
| 731 |
"broker_connection_retry_on_startup,is_connection_loss_on_startup", |
| 732 |
[ |
| 733 |
pytest.param(False, True, id='shutdown on connection loss on startup'), |
| 734 |
pytest.param(None, True, id='shutdown on connection loss on startup when retry on startup is undefined'), |
| 735 |
pytest.param(False, False, id='shutdown on connection loss not on startup but startup is defined as false'), |
| 736 |
pytest.param(None, False, id='shutdown on connection loss not on startup and startup is not defined'), |
| 737 |
pytest.param(True, False, id='shutdown on connection loss not on startup but startup is defined as true'), |
| 738 |
] |
| 739 |
) |
| 740 |
class test_Consumer_WorkerShutdown(ConsumerTestCase): |
| 741 |
|
| 742 |
def test_start_raises_connection_error(self, |
| 743 |
broker_connection_retry_on_startup, |
| 744 |
is_connection_loss_on_startup, |
| 745 |
caplog, subtests): |
| 746 |
c = self.get_consumer() |
| 747 |
c.first_connection_attempt = True if is_connection_loss_on_startup else False |
| 748 |
c.app.conf['broker_connection_retry'] = False |
| 749 |
c.app.conf['broker_connection_retry_on_startup'] = broker_connection_retry_on_startup |
| 750 |
c.blueprint.start.side_effect = ConnectionError() |
| 751 |
|
| 752 |
with subtests.test("Consumer raises WorkerShutdown on connection restart"): |
| 753 |
with pytest.raises(WorkerShutdown): |
| 754 |
c.start() |
| 755 |
|
| 756 |
record = caplog.records[0] |
| 757 |
with subtests.test("Critical error log message is outputted to the screen"): |
| 758 |
assert record.levelname == "CRITICAL" |
| 759 |
action = "establish" if is_connection_loss_on_startup else "re-establish" |
| 760 |
expected_prefix = f"Retrying to {action}" |
| 761 |
assert record.msg.startswith(expected_prefix) |
| 762 |
conn_type_name = c._get_connection_retry_type( |
| 763 |
is_connection_loss_on_startup |
| 764 |
) |
| 765 |
expected_connection_retry_type = f"app.conf.{conn_type_name}=False" |
| 766 |
assert expected_connection_retry_type in record.msg |
| 767 |
|
| 768 |
|
| 769 |
class test_Consumer_PerformPendingOperations(ConsumerTestCase): |
| 770 |
|
| 771 |
def test_perform_pending_operations_all_success(self): |
| 772 |
""" |
| 773 |
Test that all pending operations are processed successfully when `once=False`. |
| 774 |
""" |
| 775 |
c = self.get_consumer(no_hub=True) |
| 776 |
|
| 777 |
# Create mock operations |
| 778 |
mock_operation_1 = Mock() |
| 779 |
mock_operation_2 = Mock() |
| 780 |
|
| 781 |
# Add mock operations to _pending_operations |
| 782 |
c._pending_operations = [mock_operation_1, mock_operation_2] |
| 783 |
|
| 784 |
# Call perform_pending_operations |
| 785 |
c.perform_pending_operations() |
| 786 |
|
| 787 |
# Assert that all operations were called |
| 788 |
mock_operation_1.assert_called_once() |
| 789 |
mock_operation_2.assert_called_once() |
| 790 |
|
| 791 |
# Ensure all pending operations are cleared |
| 792 |
assert len(c._pending_operations) == 0 |
| 793 |
|
| 794 |
def test_perform_pending_operations_with_exception(self): |
| 795 |
""" |
| 796 |
Test that pending operations are processed even if one raises an exception, and |
| 797 |
the exception is logged when `once=False`. |
| 798 |
""" |
| 799 |
c = self.get_consumer(no_hub=True) |
| 800 |
|
| 801 |
# Mock operations: one failing, one successful |
| 802 |
mock_operation_fail = Mock(side_effect=Exception("Test Exception")) |
| 803 |
mock_operation_success = Mock() |
| 804 |
|
| 805 |
# Add operations to _pending_operations |
| 806 |
c._pending_operations = [mock_operation_fail, mock_operation_success] |
| 807 |
|
| 808 |
# Patch logger to avoid logging during the test |
| 809 |
with patch('celery.worker.consumer.consumer.logger.exception') as mock_logger: |
| 810 |
# Call perform_pending_operations |
| 811 |
c.perform_pending_operations() |
| 812 |
|
| 813 |
# Assert that both operations were attempted |
| 814 |
mock_operation_fail.assert_called_once() |
| 815 |
mock_operation_success.assert_called_once() |
| 816 |
|
| 817 |
# Ensure the exception was logged |
| 818 |
mock_logger.assert_called_once() |
| 819 |
|
| 820 |
# Ensure all pending operations are cleared |
| 821 |
assert len(c._pending_operations) == 0 |
| 822 |
|
| 823 |
|
| 824 |
class test_Heart: |
| 825 |
|
| 826 |
def test_start(self): |
| 827 |
c = Mock() |
| 828 |
c.timer = Mock() |
| 829 |
c.event_dispatcher = Mock() |
| 830 |
|
| 831 |
with patch('celery.worker.heartbeat.Heart') as hcls: |
| 832 |
h = Heart(c) |
| 833 |
assert h.enabled |
| 834 |
assert h.heartbeat_interval is None |
| 835 |
assert c.heart is None |
| 836 |
|
| 837 |
h.start(c) |
| 838 |
assert c.heart |
| 839 |
hcls.assert_called_with(c.timer, c.event_dispatcher, |
| 840 |
h.heartbeat_interval) |
| 841 |
c.heart.start.assert_called_with() |
| 842 |
|
| 843 |
def test_start_heartbeat_interval(self): |
| 844 |
c = Mock() |
| 845 |
c.timer = Mock() |
| 846 |
c.event_dispatcher = Mock() |
| 847 |
|
| 848 |
with patch('celery.worker.heartbeat.Heart') as hcls: |
| 849 |
h = Heart(c, False, 20) |
| 850 |
assert h.enabled |
| 851 |
assert h.heartbeat_interval == 20 |
| 852 |
assert c.heart is None |
| 853 |
|
| 854 |
h.start(c) |
| 855 |
assert c.heart |
| 856 |
hcls.assert_called_with(c.timer, c.event_dispatcher, |
| 857 |
h.heartbeat_interval) |
| 858 |
c.heart.start.assert_called_with() |
| 859 |
|
| 860 |
|
| 861 |
class test_Tasks: |
| 862 |
|
| 863 |
def setup_method(self): |
| 864 |
self.c = Mock() |
| 865 |
self.c.app.conf.worker_detect_quorum_queues = True |
| 866 |
self.c.connection.qos_semantics_matches_spec = False |
| 867 |
|
| 868 |
def test_stop(self): |
| 869 |
c = self.c |
| 870 |
tasks = Tasks(c) |
| 871 |
assert c.task_consumer is None |
| 872 |
assert c.qos is None |
| 873 |
|
| 874 |
c.task_consumer = Mock() |
| 875 |
tasks.stop(c) |
| 876 |
|
| 877 |
def test_stop_already_stopped(self): |
| 878 |
c = self.c |
| 879 |
tasks = Tasks(c) |
| 880 |
tasks.stop(c) |
| 881 |
|
| 882 |
def test_detect_quorum_queues_positive(self): |
| 883 |
c = self.c |
| 884 |
self.c.connection.transport.driver_type = 'amqp' |
| 885 |
c.app.amqp.queues = {"celery": Mock(queue_arguments={"x-queue-type": "quorum"})} |
| 886 |
result, name = detect_quorum_queues(c.app, c.connection.transport.driver_type) |
| 887 |
assert result |
| 888 |
assert name == "celery" |
| 889 |
|
| 890 |
def test_detect_quorum_queues_negative(self): |
| 891 |
c = self.c |
| 892 |
self.c.connection.transport.driver_type = 'amqp' |
| 893 |
c.app.amqp.queues = {"celery": Mock(queue_arguments=None)} |
| 894 |
result, name = detect_quorum_queues(c.app, c.connection.transport.driver_type) |
| 895 |
assert not result |
| 896 |
assert name == "" |
| 897 |
|
| 898 |
def test_detect_quorum_queues_not_rabbitmq(self): |
| 899 |
c = self.c |
| 900 |
self.c.connection.transport.driver_type = 'redis' |
| 901 |
result, name = detect_quorum_queues(c.app, c.connection.transport.driver_type) |
| 902 |
assert not result |
| 903 |
assert name == "" |
| 904 |
|
| 905 |
def test_qos_global_worker_detect_quorum_queues_false(self): |
| 906 |
c = self.c |
| 907 |
c.app.conf.worker_detect_quorum_queues = False |
| 908 |
tasks = Tasks(c) |
| 909 |
assert tasks.qos_global(c) is True |
| 910 |
|
| 911 |
def test_qos_global_worker_detect_quorum_queues_true_no_quorum_queues(self): |
| 912 |
c = self.c |
| 913 |
c.app.amqp.queues = {"celery": Mock(queue_arguments=None)} |
| 914 |
tasks = Tasks(c) |
| 915 |
assert tasks.qos_global(c) is True |
| 916 |
|
| 917 |
def test_qos_global_worker_detect_quorum_queues_true_with_quorum_queues(self): |
| 918 |
c = self.c |
| 919 |
self.c.connection.transport.driver_type = 'amqp' |
| 920 |
c.app.amqp.queues = {"celery": Mock(queue_arguments={"x-queue-type": "quorum"})} |
| 921 |
tasks = Tasks(c) |
| 922 |
assert tasks.qos_global(c) is False |
| 923 |
|
| 924 |
def test_log_when_qos_is_false(self, caplog): |
| 925 |
c = self.c |
| 926 |
c.connection.transport.driver_type = 'amqp' |
| 927 |
c.app.conf.broker_native_delayed_delivery = True |
| 928 |
c.app.conf.worker_disable_prefetch = False # Prevent our warning from interfering |
| 929 |
c.app.amqp.queues = {"celery": Mock(queue_arguments={"x-queue-type": "quorum"})} |
| 930 |
tasks = Tasks(c) |
| 931 |
|
| 932 |
with caplog.at_level(logging.INFO): |
| 933 |
tasks.start(c) |
| 934 |
|
| 935 |
assert len(caplog.records) == 1 |
| 936 |
|
| 937 |
record = caplog.records[0] |
| 938 |
assert record.levelname == "INFO" |
| 939 |
assert record.msg == "Global QoS is disabled. Prefetch count in now static." |
| 940 |
|
| 941 |
def test_qos_with_worker_eta_task_limit(self): |
| 942 |
"""Test QoS is instantiated with worker_eta_task_limit as max_prefetch.""" |
| 943 |
c = self.c |
| 944 |
c.app.conf.worker_eta_task_limit = 100 |
| 945 |
c.initial_prefetch_count = 10 |
| 946 |
c.task_consumer = Mock() |
| 947 |
c.app.amqp.TaskConsumer = Mock(return_value=c.task_consumer) |
| 948 |
c.connection.default_channel.basic_qos = Mock() |
| 949 |
c.update_strategies = Mock() |
| 950 |
c.on_decode_error = Mock() |
| 951 |
|
| 952 |
tasks = Tasks(c) |
| 953 |
|
| 954 |
with patch('celery.worker.consumer.tasks.QoS') as mock_qos: |
| 955 |
tasks.start(c) |
| 956 |
|
| 957 |
# Verify QoS was called with max_prefetch set to worker_eta_task_limit |
| 958 |
mock_qos.assert_called_once() |
| 959 |
args, kwargs = mock_qos.call_args |
| 960 |
assert len(args) == 2 # callback and initial_value |
| 961 |
assert kwargs.get('max_prefetch') == 100 |
| 962 |
|
| 963 |
def test_qos_without_worker_eta_task_limit(self): |
| 964 |
"""Test QoS is instantiated with None max_prefetch when worker_eta_task_limit is None.""" |
| 965 |
c = self.c |
| 966 |
c.app.conf.worker_eta_task_limit = None |
| 967 |
c.initial_prefetch_count = 10 |
| 968 |
c.task_consumer = Mock() |
| 969 |
c.app.amqp.TaskConsumer = Mock(return_value=c.task_consumer) |
| 970 |
c.connection.default_channel.basic_qos = Mock() |
| 971 |
c.update_strategies = Mock() |
| 972 |
c.on_decode_error = Mock() |
| 973 |
|
| 974 |
tasks = Tasks(c) |
| 975 |
|
| 976 |
with patch('celery.worker.consumer.tasks.QoS') as mock_qos: |
| 977 |
tasks.start(c) |
| 978 |
|
| 979 |
# Verify QoS was called with max_prefetch set to None |
| 980 |
mock_qos.assert_called_once() |
| 981 |
args, kwargs = mock_qos.call_args |
| 982 |
assert len(args) == 2 # callback and initial_value |
| 983 |
assert kwargs.get('max_prefetch') is None |
| 984 |
|
| 985 |
def test_qos_with_zero_worker_eta_task_limit(self): |
| 986 |
"""Test that QoS respects zero as a valid worker_eta_task_limit value.""" |
| 987 |
c = self.c |
| 988 |
c.app.conf.worker_eta_task_limit = 0 |
| 989 |
c.initial_prefetch_count = 10 |
| 990 |
c.task_consumer = Mock() |
| 991 |
c.app.amqp.TaskConsumer = Mock(return_value=c.task_consumer) |
| 992 |
c.connection.default_channel.basic_qos = Mock() |
| 993 |
c.update_strategies = Mock() |
| 994 |
c.on_decode_error = Mock() |
| 995 |
|
| 996 |
tasks = Tasks(c) |
| 997 |
|
| 998 |
with patch('celery.worker.consumer.tasks.QoS') as mock_qos: |
| 999 |
tasks.start(c) |
| 1000 |
|
| 1001 |
# Verify QoS was called with max_prefetch set to 0 |
| 1002 |
mock_qos.assert_called_once() |
| 1003 |
args, kwargs = mock_qos.call_args |
| 1004 |
assert len(args) == 2 # callback and initial_value |
| 1005 |
assert kwargs.get('max_prefetch') == 0 |
| 1006 |
|
| 1007 |
|
| 1008 |
class test_Agent: |
| 1009 |
|
| 1010 |
def test_start(self): |
| 1011 |
c = Mock() |
| 1012 |
agent = Agent(c) |
| 1013 |
agent.instantiate = Mock() |
| 1014 |
agent.agent_cls = 'foo:Agent' |
| 1015 |
assert agent.create(c) is not None |
| 1016 |
agent.instantiate.assert_called_with(agent.agent_cls, c.connection) |
| 1017 |
|
| 1018 |
|
| 1019 |
class test_Mingle: |
| 1020 |
|
| 1021 |
def test_start_no_replies(self): |
| 1022 |
c = Mock() |
| 1023 |
c.app.connection_for_read = _amqp_connection() |
| 1024 |
mingle = Mingle(c) |
| 1025 |
I = c.app.control.inspect.return_value = Mock() |
| 1026 |
I.hello.return_value = {} |
| 1027 |
mingle.start(c) |
| 1028 |
|
| 1029 |
def test_start(self): |
| 1030 |
c = Mock() |
| 1031 |
c.app.connection_for_read = _amqp_connection() |
| 1032 |
mingle = Mingle(c) |
| 1033 |
assert mingle.enabled |
| 1034 |
|
| 1035 |
Aig = LimitedSet() |
| 1036 |
Big = LimitedSet() |
| 1037 |
Aig.add('Aig-1') |
| 1038 |
Aig.add('Aig-2') |
| 1039 |
Big.add('Big-1') |
| 1040 |
|
| 1041 |
I = c.app.control.inspect.return_value = Mock() |
| 1042 |
I.hello.return_value = { |
| 1043 |
'[email protected]': { |
| 1044 |
'clock': 312, |
| 1045 |
'revoked': Aig._data, |
| 1046 |
}, |
| 1047 |
'[email protected]': { |
| 1048 |
'clock': 29, |
| 1049 |
'revoked': Big._data, |
| 1050 |
}, |
| 1051 |
'[email protected]': { |
| 1052 |
'error': 'unknown method', |
| 1053 |
}, |
| 1054 |
} |
| 1055 |
|
| 1056 |
our_revoked = c.controller.state.revoked = LimitedSet() |
| 1057 |
|
| 1058 |
mingle.start(c) |
| 1059 |
I.hello.assert_called_with(c.hostname, our_revoked._data) |
| 1060 |
c.app.clock.adjust.assert_has_calls([ |
| 1061 |
call(312), call(29), |
| 1062 |
], any_order=True) |
| 1063 |
assert 'Aig-1' in our_revoked |
| 1064 |
assert 'Aig-2' in our_revoked |
| 1065 |
assert 'Big-1' in our_revoked |
| 1066 |
|
| 1067 |
|
| 1068 |
def _amqp_connection(): |
| 1069 |
connection = ContextMock(name='Connection') |
| 1070 |
connection.return_value = ContextMock(name='connection') |
| 1071 |
connection.return_value.transport.driver_type = 'amqp' |
| 1072 |
return connection |
| 1073 |
|
| 1074 |
|
| 1075 |
class test_Gossip: |
| 1076 |
|
| 1077 |
def test_init(self): |
| 1078 |
c = self.Consumer() |
| 1079 |
c.app.connection_for_read = _amqp_connection() |
| 1080 |
g = Gossip(c) |
| 1081 |
assert g.enabled |
| 1082 |
assert c.gossip is g |
| 1083 |
|
| 1084 |
def test_callbacks(self): |
| 1085 |
c = self.Consumer() |
| 1086 |
c.app.connection_for_read = _amqp_connection() |
| 1087 |
g = Gossip(c) |
| 1088 |
on_node_join = Mock(name='on_node_join') |
| 1089 |
on_node_join2 = Mock(name='on_node_join2') |
| 1090 |
on_node_leave = Mock(name='on_node_leave') |
| 1091 |
on_node_lost = Mock(name='on.node_lost') |
| 1092 |
g.on.node_join.add(on_node_join) |
| 1093 |
g.on.node_join.add(on_node_join2) |
| 1094 |
g.on.node_leave.add(on_node_leave) |
| 1095 |
g.on.node_lost.add(on_node_lost) |
| 1096 |
|
| 1097 |
worker = Mock(name='worker') |
| 1098 |
g.on_node_join(worker) |
| 1099 |
on_node_join.assert_called_with(worker) |
| 1100 |
on_node_join2.assert_called_with(worker) |
| 1101 |
g.on_node_leave(worker) |
| 1102 |
on_node_leave.assert_called_with(worker) |
| 1103 |
g.on_node_lost(worker) |
| 1104 |
on_node_lost.assert_called_with(worker) |
| 1105 |
|
| 1106 |
def test_election(self): |
| 1107 |
c = self.Consumer() |
| 1108 |
c.app.connection_for_read = _amqp_connection() |
| 1109 |
g = Gossip(c) |
| 1110 |
g.start(c) |
| 1111 |
g.election('id', 'topic', 'action') |
| 1112 |
assert g.consensus_replies['id'] == [] |
| 1113 |
g.dispatcher.send.assert_called_with( |
| 1114 |
'worker-elect', id='id', topic='topic', cver=1, action='action', |
| 1115 |
) |
| 1116 |
|
| 1117 |
def test_call_task(self): |
| 1118 |
c = self.Consumer() |
| 1119 |
c.app.connection_for_read = _amqp_connection() |
| 1120 |
g = Gossip(c) |
| 1121 |
g.start(c) |
| 1122 |
signature = g.app.signature = Mock(name='app.signature') |
| 1123 |
task = Mock() |
| 1124 |
g.call_task(task) |
| 1125 |
signature.assert_called_with(task) |
| 1126 |
signature.return_value.apply_async.assert_called_with() |
| 1127 |
|
| 1128 |
signature.return_value.apply_async.side_effect = MemoryError() |
| 1129 |
with patch('celery.worker.consumer.gossip.logger') as logger: |
| 1130 |
g.call_task(task) |
| 1131 |
logger.exception.assert_called() |
| 1132 |
|
| 1133 |
def Event(self, id='id', clock=312, |
| 1134 |
hostname='[email protected]', pid=4312, |
| 1135 |
topic='topic', action='action', cver=1): |
| 1136 |
return { |
| 1137 |
'id': id, |
| 1138 |
'clock': clock, |
| 1139 |
'hostname': hostname, |
| 1140 |
'pid': pid, |
| 1141 |
'topic': topic, |
| 1142 |
'action': action, |
| 1143 |
'cver': cver, |
| 1144 |
} |
| 1145 |
|
| 1146 |
def test_on_elect(self): |
| 1147 |
c = self.Consumer() |
| 1148 |
c.app.connection_for_read = _amqp_connection() |
| 1149 |
g = Gossip(c) |
| 1150 |
g.start(c) |
| 1151 |
|
| 1152 |
event = self.Event('id1') |
| 1153 |
g.on_elect(event) |
| 1154 |
in_heap = g.consensus_requests['id1'] |
| 1155 |
assert in_heap |
| 1156 |
g.dispatcher.send.assert_called_with('worker-elect-ack', id='id1') |
| 1157 |
|
| 1158 |
event.pop('clock') |
| 1159 |
with patch('celery.worker.consumer.gossip.logger') as logger: |
| 1160 |
g.on_elect(event) |
| 1161 |
logger.exception.assert_called() |
| 1162 |
|
| 1163 |
def Consumer(self, hostname='[email protected]', pid=4312): |
| 1164 |
c = Mock() |
| 1165 |
c.app.connection = _amqp_connection() |
| 1166 |
c.hostname = hostname |
| 1167 |
c.pid = pid |
| 1168 |
c.app.events.Receiver.return_value = Mock(accept=[]) |
| 1169 |
return c |
| 1170 |
|
| 1171 |
def setup_election(self, g, c): |
| 1172 |
g.start(c) |
| 1173 |
g.clock = self.app.clock |
| 1174 |
assert 'idx' not in g.consensus_replies |
| 1175 |
assert g.on_elect_ack({'id': 'idx'}) is None |
| 1176 |
|
| 1177 |
g.state.alive_workers.return_value = [ |
| 1178 |
'[email protected]', '[email protected]', '[email protected]', |
| 1179 |
] |
| 1180 |
g.consensus_replies['id1'] = [] |
| 1181 |
g.consensus_requests['id1'] = [] |
| 1182 |
e1 = self.Event('id1', 1, '[email protected]') |
| 1183 |
e2 = self.Event('id1', 2, '[email protected]') |
| 1184 |
e3 = self.Event('id1', 3, '[email protected]') |
| 1185 |
g.on_elect(e1) |
| 1186 |
g.on_elect(e2) |
| 1187 |
g.on_elect(e3) |
| 1188 |
assert len(g.consensus_requests['id1']) == 3 |
| 1189 |
|
| 1190 |
with patch('celery.worker.consumer.gossip.info'): |
| 1191 |
g.on_elect_ack(e1) |
| 1192 |
assert len(g.consensus_replies['id1']) == 1 |
| 1193 |
g.on_elect_ack(e2) |
| 1194 |
assert len(g.consensus_replies['id1']) == 2 |
| 1195 |
g.on_elect_ack(e3) |
| 1196 |
with pytest.raises(KeyError): |
| 1197 |
g.consensus_replies['id1'] |
| 1198 |
|
| 1199 |
def test_on_elect_ack_win(self): |
| 1200 |
c = self.Consumer(hostname='[email protected]') # I will win |
| 1201 |
c.app.connection_for_read = _amqp_connection() |
| 1202 |
g = Gossip(c) |
| 1203 |
handler = g.election_handlers['topic'] = Mock() |
| 1204 |
self.setup_election(g, c) |
| 1205 |
handler.assert_called_with('action') |
| 1206 |
|
| 1207 |
def test_on_elect_ack_lose(self): |
| 1208 |
c = self.Consumer(hostname='[email protected]') # I will lose |
| 1209 |
c.app.connection_for_read = _amqp_connection() |
| 1210 |
g = Gossip(c) |
| 1211 |
handler = g.election_handlers['topic'] = Mock() |
| 1212 |
self.setup_election(g, c) |
| 1213 |
handler.assert_not_called() |
| 1214 |
|
| 1215 |
def test_on_elect_ack_win_but_no_action(self): |
| 1216 |
c = self.Consumer(hostname='[email protected]') # I will win |
| 1217 |
c.app.connection_for_read = _amqp_connection() |
| 1218 |
g = Gossip(c) |
| 1219 |
g.election_handlers = {} |
| 1220 |
with patch('celery.worker.consumer.gossip.logger') as logger: |
| 1221 |
self.setup_election(g, c) |
| 1222 |
logger.exception.assert_called() |
| 1223 |
|
| 1224 |
def test_on_node_join(self): |
| 1225 |
c = self.Consumer() |
| 1226 |
c.app.connection_for_read = _amqp_connection() |
| 1227 |
g = Gossip(c) |
| 1228 |
with patch('celery.worker.consumer.gossip.debug') as debug: |
| 1229 |
g.on_node_join(c) |
| 1230 |
debug.assert_called_with('%s joined the party', '[email protected]') |
| 1231 |
|
| 1232 |
def test_on_node_leave(self): |
| 1233 |
c = self.Consumer() |
| 1234 |
c.app.connection_for_read = _amqp_connection() |
| 1235 |
g = Gossip(c) |
| 1236 |
with patch('celery.worker.consumer.gossip.debug') as debug: |
| 1237 |
g.on_node_leave(c) |
| 1238 |
debug.assert_called_with('%s left', '[email protected]') |
| 1239 |
|
| 1240 |
def test_on_node_lost(self): |
| 1241 |
c = self.Consumer() |
| 1242 |
c.app.connection_for_read = _amqp_connection() |
| 1243 |
g = Gossip(c) |
| 1244 |
with patch('celery.worker.consumer.gossip.info') as info: |
| 1245 |
g.on_node_lost(c) |
| 1246 |
info.assert_called_with('missed heartbeat from %s', '[email protected]') |
| 1247 |
|
| 1248 |
def test_register_timer(self): |
| 1249 |
c = self.Consumer() |
| 1250 |
c.app.connection_for_read = _amqp_connection() |
| 1251 |
g = Gossip(c) |
| 1252 |
g.register_timer() |
| 1253 |
c.timer.call_repeatedly.assert_called_with(g.interval, g.periodic) |
| 1254 |
tref = g._tref |
| 1255 |
g.register_timer() |
| 1256 |
tref.cancel.assert_called_with() |
| 1257 |
|
| 1258 |
def test_periodic(self): |
| 1259 |
c = self.Consumer() |
| 1260 |
c.app.connection_for_read = _amqp_connection() |
| 1261 |
g = Gossip(c) |
| 1262 |
g.on_node_lost = Mock() |
| 1263 |
state = g.state = Mock() |
| 1264 |
worker = Mock() |
| 1265 |
state.workers = {'foo': worker} |
| 1266 |
worker.alive = True |
| 1267 |
worker.hostname = 'foo' |
| 1268 |
g.periodic() |
| 1269 |
|
| 1270 |
worker.alive = False |
| 1271 |
g.periodic() |
| 1272 |
g.on_node_lost.assert_called_with(worker) |
| 1273 |
with pytest.raises(KeyError): |
| 1274 |
state.workers['foo'] |
| 1275 |
|
| 1276 |
def test_on_message__task(self): |
| 1277 |
c = self.Consumer() |
| 1278 |
c.app.connection_for_read = _amqp_connection() |
| 1279 |
g = Gossip(c) |
| 1280 |
assert g.enabled |
| 1281 |
message = Mock(name='message') |
| 1282 |
message.delivery_info = {'routing_key': 'task.failed'} |
| 1283 |
g.on_message(Mock(name='prepare'), message) |
| 1284 |
|
| 1285 |
def test_on_message(self): |
| 1286 |
c = self.Consumer() |
| 1287 |
c.app.connection_for_read = _amqp_connection() |
| 1288 |
g = Gossip(c) |
| 1289 |
assert g.enabled |
| 1290 |
prepare = Mock() |
| 1291 |
prepare.return_value = 'worker-online', {} |
| 1292 |
c.app.events.State.assert_called_with( |
| 1293 |
on_node_join=g.on_node_join, |
| 1294 |
on_node_leave=g.on_node_leave, |
| 1295 |
max_tasks_in_memory=1, |
| 1296 |
) |
| 1297 |
g.update_state = Mock() |
| 1298 |
worker = Mock() |
| 1299 |
g.on_node_join = Mock() |
| 1300 |
g.on_node_leave = Mock() |
| 1301 |
g.update_state.return_value = worker, 1 |
| 1302 |
message = Mock() |
| 1303 |
message.delivery_info = {'routing_key': 'worker-online'} |
| 1304 |
message.headers = {'hostname': 'other'} |
| 1305 |
|
| 1306 |
handler = g.event_handlers['worker-online'] = Mock() |
| 1307 |
g.on_message(prepare, message) |
| 1308 |
handler.assert_called_with(message.payload) |
| 1309 |
g.event_handlers = {} |
| 1310 |
|
| 1311 |
g.on_message(prepare, message) |
| 1312 |
|
| 1313 |
message.delivery_info = {'routing_key': 'worker-offline'} |
| 1314 |
prepare.return_value = 'worker-offline', {} |
| 1315 |
g.on_message(prepare, message) |
| 1316 |
|
| 1317 |
message.delivery_info = {'routing_key': 'worker-baz'} |
| 1318 |
prepare.return_value = 'worker-baz', {} |
| 1319 |
g.update_state.return_value = worker, 0 |
| 1320 |
g.on_message(prepare, message) |
| 1321 |
|
| 1322 |
message.headers = {'hostname': g.hostname} |
| 1323 |
g.on_message(prepare, message) |
| 1324 |
g.clock.forward.assert_called_with() |