test_loops.py 15 KB

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