test_loops.py 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484
  1. from __future__ import absolute_import, unicode_literals
  2. import errno
  3. import socket
  4. import pytest
  5. from case import Mock
  6. from kombu.asynchronous import ERR, READ, WRITE, Hub
  7. from kombu.exceptions import DecodeError
  8. from celery.bootsteps import CLOSE, RUN
  9. from celery.exceptions import (InvalidTaskError, WorkerLostError,
  10. WorkerShutdown, WorkerTerminate)
  11. from celery.five import Empty, python_2_unicode_compatible
  12. from celery.platforms import EX_FAILURE
  13. from celery.worker import state
  14. from celery.worker.consumer import Consumer
  15. from celery.worker.loops import _quick_drain, asynloop, synloop
  16. @python_2_unicode_compatible
  17. class PromiseEqual(object):
  18. def __init__(self, fun, *args, **kwargs):
  19. self.fun = fun
  20. self.args = args
  21. self.kwargs = kwargs
  22. def __eq__(self, other):
  23. return (other.fun == self.fun and
  24. other.args == self.args and
  25. other.kwargs == self.kwargs)
  26. def __repr__(self):
  27. return '<promise: {0.fun!r} {0.args!r} {0.kwargs!r}>'.format(self)
  28. class X(object):
  29. def __init__(self, app, heartbeat=None, on_task_message=None,
  30. transport_driver_type=None):
  31. hub = Hub()
  32. (
  33. self.obj,
  34. self.connection,
  35. self.consumer,
  36. self.blueprint,
  37. self.hub,
  38. self.qos,
  39. self.heartbeat,
  40. self.clock,
  41. ) = self.args = [Mock(name='obj'),
  42. Mock(name='connection'),
  43. Mock(name='consumer'),
  44. Mock(name='blueprint'),
  45. hub,
  46. Mock(name='qos'),
  47. heartbeat,
  48. Mock(name='clock')]
  49. self.connection.supports_heartbeats = True
  50. self.connection.get_heartbeat_interval.side_effect = (
  51. lambda: self.heartbeat
  52. )
  53. self.consumer.callbacks = []
  54. self.obj.strategies = {}
  55. self.connection.connection_errors = (socket.error,)
  56. if transport_driver_type:
  57. self.connection.transport.driver_type = transport_driver_type
  58. self.hub.readers = {}
  59. self.hub.timer = Mock(name='hub.timer')
  60. self.hub.timer._queue = [Mock()]
  61. self.hub.fire_timers = Mock(name='hub.fire_timers')
  62. self.hub.fire_timers.return_value = 1.7
  63. self.hub.poller = Mock(name='hub.poller')
  64. self.hub.close = Mock(name='hub.close()') # asynloop calls hub.close
  65. self.Hub = self.hub
  66. self.blueprint.state = RUN
  67. # need this for create_task_handler
  68. self._consumer = _consumer = Consumer(
  69. Mock(), timer=Mock(), controller=Mock(), app=app)
  70. _consumer.on_task_message = on_task_message or []
  71. self.obj.create_task_handler = _consumer.create_task_handler
  72. self.on_unknown_message = self.obj.on_unknown_message = Mock(
  73. name='on_unknown_message',
  74. )
  75. _consumer.on_unknown_message = self.on_unknown_message
  76. self.on_unknown_task = self.obj.on_unknown_task = Mock(
  77. name='on_unknown_task',
  78. )
  79. _consumer.on_unknown_task = self.on_unknown_task
  80. self.on_invalid_task = self.obj.on_invalid_task = Mock(
  81. name='on_invalid_task',
  82. )
  83. _consumer.on_invalid_task = self.on_invalid_task
  84. self.on_decode_error = self.obj.on_decode_error = Mock(
  85. name='on_decode_error',
  86. )
  87. _consumer.on_decode_error = self.on_decode_error
  88. _consumer.strategies = self.obj.strategies
  89. def timeout_then_error(self, mock):
  90. def first(*args, **kwargs):
  91. mock.side_effect = socket.error()
  92. raise socket.timeout()
  93. mock.side_effect = first
  94. def close_then_error(self, mock=None, mod=0, exc=None):
  95. mock = Mock() if mock is None else mock
  96. def first(*args, **kwargs):
  97. if not mod or mock.call_count > mod:
  98. self.close()
  99. raise (socket.error() if exc is None else exc)
  100. mock.side_effect = first
  101. return mock
  102. def close(self, *args, **kwargs):
  103. self.blueprint.state = CLOSE
  104. def closer(self, mock=None, mod=0):
  105. mock = Mock() if mock is None else mock
  106. def closing(*args, **kwargs):
  107. if not mod or mock.call_count >= mod:
  108. self.close()
  109. mock.side_effect = closing
  110. return mock
  111. def get_task_callback(*args, **kwargs):
  112. x = X(*args, **kwargs)
  113. x.blueprint.state = CLOSE
  114. asynloop(*x.args)
  115. return x, x.consumer.on_message
  116. class test_asynloop:
  117. def setup(self):
  118. @self.app.task(shared=False)
  119. def add(x, y):
  120. return x + y
  121. self.add = add
  122. def test_drain_after_consume(self):
  123. x, _ = get_task_callback(self.app, transport_driver_type='amqp')
  124. assert _quick_drain in [p.fun for p in x.hub._ready]
  125. def test_pool_did_not_start_at_startup(self):
  126. x = X(self.app)
  127. x.obj.restart_count = 0
  128. x.obj.pool.did_start_ok.return_value = False
  129. with pytest.raises(WorkerLostError):
  130. asynloop(*x.args)
  131. def test_setup_heartbeat(self):
  132. x = X(self.app, heartbeat=10)
  133. x.hub.timer.call_repeatedly = Mock(name='x.hub.call_repeatedly()')
  134. x.blueprint.state = CLOSE
  135. asynloop(*x.args)
  136. x.consumer.consume.assert_called_with()
  137. x.obj.on_ready.assert_called_with()
  138. x.hub.timer.call_repeatedly.assert_called_with(
  139. 10 / 2.0, x.connection.heartbeat_check, (2.0,),
  140. )
  141. def task_context(self, sig, **kwargs):
  142. x, on_task = get_task_callback(self.app, **kwargs)
  143. message = self.task_message_from_sig(self.app, sig)
  144. strategy = x.obj.strategies[sig.task] = Mock(name='strategy')
  145. return x, on_task, message, strategy
  146. def test_on_task_received(self):
  147. x, on_task, msg, strategy = self.task_context(self.add.s(2, 2))
  148. on_task(msg)
  149. strategy.assert_called_with(
  150. msg, None,
  151. PromiseEqual(x._consumer.call_soon, msg.ack_log_error),
  152. PromiseEqual(x._consumer.call_soon, msg.reject_log_error), [],
  153. )
  154. def test_on_task_received_executes_on_task_message(self):
  155. cbs = [Mock(), Mock(), Mock()]
  156. x, on_task, msg, strategy = self.task_context(
  157. self.add.s(2, 2), on_task_message=cbs,
  158. )
  159. on_task(msg)
  160. strategy.assert_called_with(
  161. msg, None,
  162. PromiseEqual(x._consumer.call_soon, msg.ack_log_error),
  163. PromiseEqual(x._consumer.call_soon, msg.reject_log_error),
  164. cbs,
  165. )
  166. def test_on_task_message_missing_name(self):
  167. x, on_task, msg, strategy = self.task_context(self.add.s(2, 2))
  168. msg.headers.pop('task')
  169. on_task(msg)
  170. x.on_unknown_message.assert_called_with(msg.decode(), msg)
  171. def test_on_task_pool_raises(self):
  172. x, on_task, msg, strategy = self.task_context(self.add.s(2, 2))
  173. strategy.side_effect = ValueError()
  174. with pytest.raises(ValueError):
  175. on_task(msg)
  176. def test_on_task_InvalidTaskError(self):
  177. x, on_task, msg, strategy = self.task_context(self.add.s(2, 2))
  178. exc = strategy.side_effect = InvalidTaskError()
  179. on_task(msg)
  180. x.on_invalid_task.assert_called_with(None, msg, exc)
  181. def test_on_task_DecodeError(self):
  182. x, on_task, msg, strategy = self.task_context(self.add.s(2, 2))
  183. exc = strategy.side_effect = DecodeError()
  184. on_task(msg)
  185. x.on_decode_error.assert_called_with(msg, exc)
  186. def test_should_terminate(self):
  187. x = X(self.app)
  188. # XXX why aren't the errors propagated?!?
  189. state.should_terminate = True
  190. try:
  191. with pytest.raises(WorkerTerminate):
  192. asynloop(*x.args)
  193. finally:
  194. state.should_terminate = None
  195. def test_should_terminate_hub_close_raises(self):
  196. x = X(self.app)
  197. # XXX why aren't the errors propagated?!?
  198. state.should_terminate = EX_FAILURE
  199. x.hub.close.side_effect = MemoryError()
  200. try:
  201. with pytest.raises(WorkerTerminate):
  202. asynloop(*x.args)
  203. finally:
  204. state.should_terminate = None
  205. def test_should_stop(self):
  206. x = X(self.app)
  207. state.should_stop = 303
  208. try:
  209. with pytest.raises(WorkerShutdown):
  210. asynloop(*x.args)
  211. finally:
  212. state.should_stop = None
  213. def test_updates_qos(self):
  214. x = X(self.app)
  215. x.qos.prev = 3
  216. x.qos.value = 3
  217. x.hub.on_tick.add(x.closer(mod=2))
  218. x.hub.timer._queue = [1]
  219. asynloop(*x.args)
  220. x.qos.update.assert_not_called()
  221. x = X(self.app)
  222. x.qos.prev = 1
  223. x.qos.value = 6
  224. x.hub.on_tick.add(x.closer(mod=2))
  225. asynloop(*x.args)
  226. x.qos.update.assert_called_with()
  227. x.hub.fire_timers.assert_called_with(propagate=(socket.error,))
  228. def test_poll_empty(self):
  229. x = X(self.app)
  230. x.hub.readers = {6: Mock()}
  231. x.hub.timer._queue = [1]
  232. x.close_then_error(x.hub.poller.poll)
  233. x.hub.fire_timers.return_value = 33.37
  234. poller = x.hub.poller
  235. poller.poll.return_value = []
  236. with pytest.raises(socket.error):
  237. asynloop(*x.args)
  238. poller.poll.assert_called_with(33.37)
  239. def test_poll_readable(self):
  240. x = X(self.app)
  241. reader = Mock(name='reader')
  242. x.hub.add_reader(6, reader, 6)
  243. x.hub.on_tick.add(x.close_then_error(Mock(name='tick'), mod=4))
  244. poller = x.hub.poller
  245. poller.poll.return_value = [(6, READ)]
  246. with pytest.raises(socket.error):
  247. asynloop(*x.args)
  248. reader.assert_called_with(6)
  249. poller.poll.assert_called()
  250. def test_poll_readable_raises_Empty(self):
  251. x = X(self.app)
  252. reader = Mock(name='reader')
  253. x.hub.add_reader(6, reader, 6)
  254. x.hub.on_tick.add(x.close_then_error(Mock(name='tick'), 2))
  255. poller = x.hub.poller
  256. poller.poll.return_value = [(6, READ)]
  257. reader.side_effect = Empty()
  258. with pytest.raises(socket.error):
  259. asynloop(*x.args)
  260. reader.assert_called_with(6)
  261. poller.poll.assert_called()
  262. def test_poll_writable(self):
  263. x = X(self.app)
  264. writer = Mock(name='writer')
  265. x.hub.add_writer(6, writer, 6)
  266. x.hub.on_tick.add(x.close_then_error(Mock(name='tick'), 2))
  267. poller = x.hub.poller
  268. poller.poll.return_value = [(6, WRITE)]
  269. with pytest.raises(socket.error):
  270. asynloop(*x.args)
  271. writer.assert_called_with(6)
  272. poller.poll.assert_called()
  273. def test_poll_writable_none_registered(self):
  274. x = X(self.app)
  275. writer = Mock(name='writer')
  276. x.hub.add_writer(6, writer, 6)
  277. x.hub.on_tick.add(x.close_then_error(Mock(name='tick'), 2))
  278. poller = x.hub.poller
  279. poller.poll.return_value = [(7, WRITE)]
  280. with pytest.raises(socket.error):
  281. asynloop(*x.args)
  282. poller.poll.assert_called()
  283. def test_poll_unknown_event(self):
  284. x = X(self.app)
  285. writer = Mock(name='reader')
  286. x.hub.add_writer(6, writer, 6)
  287. x.hub.on_tick.add(x.close_then_error(Mock(name='tick'), 2))
  288. poller = x.hub.poller
  289. poller.poll.return_value = [(6, 0)]
  290. with pytest.raises(socket.error):
  291. asynloop(*x.args)
  292. poller.poll.assert_called()
  293. def test_poll_keep_draining_disabled(self):
  294. x = X(self.app)
  295. x.hub.writers = {6: Mock()}
  296. poll = x.hub.poller.poll
  297. def se(*args, **kwargs):
  298. poll.side_effect = socket.error()
  299. poll.side_effect = se
  300. poller = x.hub.poller
  301. poll.return_value = [(6, 0)]
  302. with pytest.raises(socket.error):
  303. asynloop(*x.args)
  304. poller.poll.assert_called()
  305. def test_poll_err_writable(self):
  306. x = X(self.app)
  307. writer = Mock(name='writer')
  308. x.hub.add_writer(6, writer, 6, 48)
  309. x.hub.on_tick.add(x.close_then_error(Mock(), 2))
  310. poller = x.hub.poller
  311. poller.poll.return_value = [(6, ERR)]
  312. with pytest.raises(socket.error):
  313. asynloop(*x.args)
  314. writer.assert_called_with(6, 48)
  315. poller.poll.assert_called()
  316. def test_poll_write_generator(self):
  317. x = X(self.app)
  318. x.hub.remove = Mock(name='hub.remove()')
  319. def Gen():
  320. yield 1
  321. yield 2
  322. gen = Gen()
  323. x.hub.add_writer(6, gen)
  324. x.hub.on_tick.add(x.close_then_error(Mock(name='tick'), 2))
  325. x.hub.poller.poll.return_value = [(6, WRITE)]
  326. with pytest.raises(socket.error):
  327. asynloop(*x.args)
  328. assert gen.gi_frame.f_lasti != -1
  329. x.hub.remove.assert_not_called()
  330. def test_poll_write_generator_stopped(self):
  331. x = X(self.app)
  332. def Gen():
  333. raise StopIteration()
  334. yield
  335. gen = Gen()
  336. x.hub.add_writer(6, gen)
  337. x.hub.on_tick.add(x.close_then_error(Mock(name='tick'), 2))
  338. x.hub.poller.poll.return_value = [(6, WRITE)]
  339. x.hub.remove = Mock(name='hub.remove()')
  340. with pytest.raises(socket.error):
  341. asynloop(*x.args)
  342. assert gen.gi_frame is None
  343. def test_poll_write_generator_raises(self):
  344. x = X(self.app)
  345. def Gen():
  346. raise ValueError('foo')
  347. yield
  348. gen = Gen()
  349. x.hub.add_writer(6, gen)
  350. x.hub.remove = Mock(name='hub.remove()')
  351. x.hub.on_tick.add(x.close_then_error(Mock(name='tick'), 2))
  352. x.hub.poller.poll.return_value = [(6, WRITE)]
  353. with pytest.raises(ValueError):
  354. asynloop(*x.args)
  355. assert gen.gi_frame is None
  356. x.hub.remove.assert_called_with(6)
  357. def test_poll_err_readable(self):
  358. x = X(self.app)
  359. reader = Mock(name='reader')
  360. x.hub.add_reader(6, reader, 6, 24)
  361. x.hub.on_tick.add(x.close_then_error(Mock(), 2))
  362. poller = x.hub.poller
  363. poller.poll.return_value = [(6, ERR)]
  364. with pytest.raises(socket.error):
  365. asynloop(*x.args)
  366. reader.assert_called_with(6, 24)
  367. poller.poll.assert_called()
  368. def test_poll_raises_ValueError(self):
  369. x = X(self.app)
  370. x.hub.readers = {6: Mock()}
  371. poller = x.hub.poller
  372. x.close_then_error(poller.poll, exc=ValueError)
  373. asynloop(*x.args)
  374. poller.poll.assert_called()
  375. class test_synloop:
  376. def test_timeout_ignored(self):
  377. x = X(self.app)
  378. x.timeout_then_error(x.connection.drain_events)
  379. with pytest.raises(socket.error):
  380. synloop(*x.args)
  381. assert x.connection.drain_events.call_count == 2
  382. def test_updates_qos_when_changed(self):
  383. x = X(self.app)
  384. x.qos.prev = 2
  385. x.qos.value = 2
  386. x.timeout_then_error(x.connection.drain_events)
  387. with pytest.raises(socket.error):
  388. synloop(*x.args)
  389. x.qos.update.assert_not_called()
  390. x.qos.value = 4
  391. x.timeout_then_error(x.connection.drain_events)
  392. with pytest.raises(socket.error):
  393. synloop(*x.args)
  394. x.qos.update.assert_called_with()
  395. def test_ignores_socket_errors_when_closed(self):
  396. x = X(self.app)
  397. x.close_then_error(x.connection.drain_events)
  398. assert synloop(*x.args) is None
  399. class test_quick_drain:
  400. def setup(self):
  401. self.connection = Mock(name='connection')
  402. def test_drain(self):
  403. _quick_drain(self.connection, timeout=33.3)
  404. self.connection.drain_events.assert_called_with(timeout=33.3)
  405. def test_drain_error(self):
  406. exc = KeyError()
  407. exc.errno = 313
  408. self.connection.drain_events.side_effect = exc
  409. with pytest.raises(KeyError):
  410. _quick_drain(self.connection, timeout=33.3)
  411. def test_drain_error_EAGAIN(self):
  412. exc = KeyError()
  413. exc.errno = errno.EAGAIN
  414. self.connection.drain_events.side_effect = exc
  415. _quick_drain(self.connection, timeout=33.3)