test_loops.py 15 KB

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