test_loops.py 15 KB

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