test_control.py 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598
  1. from __future__ import absolute_import
  2. import sys
  3. import socket
  4. from collections import defaultdict
  5. from datetime import datetime, timedelta
  6. from kombu import pidbox
  7. from celery.datastructures import AttributeDict
  8. from celery.five import Queue as FastQueue
  9. from celery.utils import uuid
  10. from celery.utils.timer2 import Timer
  11. from celery.worker import WorkController as _WC
  12. from celery.worker import consumer
  13. from celery.worker import control
  14. from celery.worker import state as worker_state
  15. from celery.worker.job import Request
  16. from celery.worker.state import revoked
  17. from celery.worker.control import Panel
  18. from celery.worker.pidbox import Pidbox, gPidbox
  19. from celery.tests.case import AppCase, Mock, call, patch
  20. hostname = socket.gethostname()
  21. class WorkController(object):
  22. autoscaler = None
  23. def stats(self):
  24. return {'total': worker_state.total_count}
  25. class Consumer(consumer.Consumer):
  26. def __init__(self, app):
  27. self.app = app
  28. self.buffer = FastQueue()
  29. self.handle_task = self.buffer.put
  30. self.timer = Timer()
  31. self.event_dispatcher = Mock()
  32. self.controller = WorkController()
  33. self.task_consumer = Mock()
  34. self.prefetch_multiplier = 1
  35. self.initial_prefetch_count = 1
  36. from celery.concurrency.base import BasePool
  37. self.pool = BasePool(10)
  38. self.task_buckets = defaultdict(lambda: None)
  39. class test_Pidbox(AppCase):
  40. def test_shutdown(self):
  41. with patch('celery.worker.pidbox.ignore_errors') as eig:
  42. parent = Mock()
  43. pbox = Pidbox(parent)
  44. pbox._close_channel = Mock()
  45. self.assertIs(pbox.c, parent)
  46. pconsumer = pbox.consumer = Mock()
  47. cancel = pconsumer.cancel
  48. pbox.shutdown(parent)
  49. eig.assert_called_with(parent, cancel)
  50. pbox._close_channel.assert_called_with(parent)
  51. class test_Pidbox_green(AppCase):
  52. def test_stop(self):
  53. parent = Mock()
  54. g = gPidbox(parent)
  55. stopped = g._node_stopped = Mock()
  56. shutdown = g._node_shutdown = Mock()
  57. close_chan = g._close_channel = Mock()
  58. g.stop(parent)
  59. shutdown.set.assert_called_with()
  60. stopped.wait.assert_called_with()
  61. close_chan.assert_called_with(parent)
  62. self.assertIsNone(g._node_stopped)
  63. self.assertIsNone(g._node_shutdown)
  64. close_chan.reset()
  65. g.stop(parent)
  66. close_chan.assert_called_with(parent)
  67. def test_resets(self):
  68. parent = Mock()
  69. g = gPidbox(parent)
  70. g._resets = 100
  71. g.reset()
  72. self.assertEqual(g._resets, 101)
  73. def test_loop(self):
  74. parent = Mock()
  75. conn = parent.connect.return_value = self.app.connection()
  76. drain = conn.drain_events = Mock()
  77. g = gPidbox(parent)
  78. parent.connection = Mock()
  79. do_reset = g._do_reset = Mock()
  80. call_count = [0]
  81. def se(*args, **kwargs):
  82. if call_count[0] > 2:
  83. g._node_shutdown.set()
  84. g.reset()
  85. call_count[0] += 1
  86. drain.side_effect = se
  87. g.loop(parent)
  88. self.assertEqual(do_reset.call_count, 4)
  89. class test_ControlPanel(AppCase):
  90. def setup(self):
  91. self.panel = self.create_panel(consumer=Consumer(self.app))
  92. @self.app.task(rate_limit=200, shared=False)
  93. def mytask():
  94. pass
  95. self.mytask = mytask
  96. def create_state(self, **kwargs):
  97. kwargs.setdefault('app', self.app)
  98. kwargs.setdefault('hostname', hostname)
  99. return AttributeDict(kwargs)
  100. def create_panel(self, **kwargs):
  101. return self.app.control.mailbox.Node(hostname=hostname,
  102. state=self.create_state(**kwargs),
  103. handlers=Panel.data)
  104. def test_enable_events(self):
  105. consumer = Consumer(self.app)
  106. panel = self.create_panel(consumer=consumer)
  107. evd = consumer.event_dispatcher
  108. evd.groups = set()
  109. panel.handle('enable_events')
  110. self.assertIn('task', evd.groups)
  111. evd.groups = set(['task'])
  112. self.assertIn('already enabled', panel.handle('enable_events')['ok'])
  113. def test_disable_events(self):
  114. consumer = Consumer(self.app)
  115. panel = self.create_panel(consumer=consumer)
  116. evd = consumer.event_dispatcher
  117. evd.enabled = True
  118. evd.groups = set(['task'])
  119. panel.handle('disable_events')
  120. self.assertNotIn('task', evd.groups)
  121. self.assertIn('already disabled', panel.handle('disable_events')['ok'])
  122. def test_clock(self):
  123. consumer = Consumer(self.app)
  124. panel = self.create_panel(consumer=consumer)
  125. panel.state.app.clock.value = 313
  126. x = panel.handle('clock')
  127. self.assertEqual(x['clock'], 313)
  128. def test_hello(self):
  129. consumer = Consumer(self.app)
  130. panel = self.create_panel(consumer=consumer)
  131. panel.state.app.clock.value = 313
  132. worker_state.revoked.add('revoked1')
  133. try:
  134. x = panel.handle('hello', {'from_node': 'george@vandelay.com'})
  135. self.assertIn('revoked1', x['revoked'])
  136. self.assertEqual(x['clock'], 314) # incremented
  137. finally:
  138. worker_state.revoked.discard('revoked1')
  139. def test_conf(self):
  140. return
  141. consumer = Consumer(self.app)
  142. panel = self.create_panel(consumer=consumer)
  143. self.app.conf.SOME_KEY6 = 'hello world'
  144. x = panel.handle('dump_conf')
  145. self.assertIn('SOME_KEY6', x)
  146. def test_election(self):
  147. consumer = Consumer(self.app)
  148. panel = self.create_panel(consumer=consumer)
  149. consumer.gossip = Mock()
  150. panel.handle(
  151. 'election', {'id': 'id', 'topic': 'topic', 'action': 'action'},
  152. )
  153. consumer.gossip.election.assert_called_with('id', 'topic', 'action')
  154. def test_heartbeat(self):
  155. consumer = Consumer(self.app)
  156. panel = self.create_panel(consumer=consumer)
  157. consumer.event_dispatcher.enabled = True
  158. panel.handle('heartbeat')
  159. self.assertIn(('worker-heartbeat', ),
  160. consumer.event_dispatcher.send.call_args)
  161. def test_time_limit(self):
  162. panel = self.create_panel(consumer=Mock())
  163. r = panel.handle('time_limit', arguments=dict(
  164. task_name=self.mytask.name, hard=30, soft=10))
  165. self.assertEqual(
  166. (self.mytask.time_limit, self.mytask.soft_time_limit),
  167. (30, 10),
  168. )
  169. self.assertIn('ok', r)
  170. r = panel.handle('time_limit', arguments=dict(
  171. task_name=self.mytask.name, hard=None, soft=None))
  172. self.assertEqual(
  173. (self.mytask.time_limit, self.mytask.soft_time_limit),
  174. (None, None),
  175. )
  176. self.assertIn('ok', r)
  177. r = panel.handle('time_limit', arguments=dict(
  178. task_name='248e8afya9s8dh921eh928', hard=30))
  179. self.assertIn('error', r)
  180. def test_active_queues(self):
  181. import kombu
  182. x = kombu.Consumer(self.app.connection(),
  183. [kombu.Queue('foo', kombu.Exchange('foo'), 'foo'),
  184. kombu.Queue('bar', kombu.Exchange('bar'), 'bar')],
  185. auto_declare=False)
  186. consumer = Mock()
  187. consumer.task_consumer = x
  188. panel = self.create_panel(consumer=consumer)
  189. r = panel.handle('active_queues')
  190. self.assertListEqual(list(sorted(q['name'] for q in r)),
  191. ['bar', 'foo'])
  192. def test_dump_tasks(self):
  193. info = '\n'.join(self.panel.handle('dump_tasks'))
  194. self.assertIn('mytask', info)
  195. self.assertIn('rate_limit=200', info)
  196. def test_stats(self):
  197. prev_count, worker_state.total_count = worker_state.total_count, 100
  198. try:
  199. self.assertDictContainsSubset({'total': 100},
  200. self.panel.handle('stats'))
  201. finally:
  202. worker_state.total_count = prev_count
  203. def test_report(self):
  204. self.panel.handle('report')
  205. def test_active(self):
  206. r = Request({
  207. 'task': self.mytask.name,
  208. 'id': 'do re mi',
  209. 'args': (),
  210. 'kwargs': {},
  211. }, app=self.app)
  212. worker_state.active_requests.add(r)
  213. try:
  214. self.assertTrue(self.panel.handle('dump_active'))
  215. finally:
  216. worker_state.active_requests.discard(r)
  217. def test_pool_grow(self):
  218. class MockPool(object):
  219. def __init__(self, size=1):
  220. self.size = size
  221. def grow(self, n=1):
  222. self.size += n
  223. def shrink(self, n=1):
  224. self.size -= n
  225. @property
  226. def num_processes(self):
  227. return self.size
  228. consumer = Consumer(self.app)
  229. consumer.prefetch_multiplier = 8
  230. consumer.qos = Mock(name='qos')
  231. consumer.pool = MockPool(1)
  232. panel = self.create_panel(consumer=consumer)
  233. panel.handle('pool_grow')
  234. self.assertEqual(consumer.pool.size, 2)
  235. consumer.qos.increment_eventually.assert_called_with(8)
  236. self.assertEqual(consumer.initial_prefetch_count, 16)
  237. panel.handle('pool_shrink')
  238. self.assertEqual(consumer.pool.size, 1)
  239. consumer.qos.decrement_eventually.assert_called_with(8)
  240. self.assertEqual(consumer.initial_prefetch_count, 8)
  241. panel.state.consumer = Mock()
  242. panel.state.consumer.controller = Mock()
  243. sc = panel.state.consumer.controller.autoscaler = Mock()
  244. panel.handle('pool_grow')
  245. self.assertTrue(sc.force_scale_up.called)
  246. panel.handle('pool_shrink')
  247. self.assertTrue(sc.force_scale_down.called)
  248. def test_add__cancel_consumer(self):
  249. class MockConsumer(object):
  250. queues = []
  251. cancelled = []
  252. consuming = False
  253. def add_queue(self, queue):
  254. self.queues.append(queue.name)
  255. def consume(self):
  256. self.consuming = True
  257. def cancel_by_queue(self, queue):
  258. self.cancelled.append(queue)
  259. def consuming_from(self, queue):
  260. return queue in self.queues
  261. consumer = Consumer(self.app)
  262. consumer.task_consumer = MockConsumer()
  263. panel = self.create_panel(consumer=consumer)
  264. panel.handle('add_consumer', {'queue': 'MyQueue'})
  265. self.assertIn('MyQueue', consumer.task_consumer.queues)
  266. self.assertTrue(consumer.task_consumer.consuming)
  267. panel.handle('add_consumer', {'queue': 'MyQueue'})
  268. panel.handle('cancel_consumer', {'queue': 'MyQueue'})
  269. self.assertIn('MyQueue', consumer.task_consumer.cancelled)
  270. def test_revoked(self):
  271. worker_state.revoked.clear()
  272. worker_state.revoked.add('a1')
  273. worker_state.revoked.add('a2')
  274. try:
  275. self.assertEqual(sorted(self.panel.handle('dump_revoked')),
  276. ['a1', 'a2'])
  277. finally:
  278. worker_state.revoked.clear()
  279. def test_dump_schedule(self):
  280. consumer = Consumer(self.app)
  281. panel = self.create_panel(consumer=consumer)
  282. self.assertFalse(panel.handle('dump_schedule'))
  283. r = Request({
  284. 'task': self.mytask.name,
  285. 'id': 'CAFEBABE',
  286. 'args': (),
  287. 'kwargs': {},
  288. }, app=self.app)
  289. consumer.timer.schedule.enter_at(
  290. consumer.timer.Entry(lambda x: x, (r, )),
  291. datetime.now() + timedelta(seconds=10))
  292. consumer.timer.schedule.enter_at(
  293. consumer.timer.Entry(lambda x: x, (object(), )),
  294. datetime.now() + timedelta(seconds=10))
  295. self.assertTrue(panel.handle('dump_schedule'))
  296. def test_dump_reserved(self):
  297. consumer = Consumer(self.app)
  298. worker_state.reserved_requests.add(Request({
  299. 'task': self.mytask.name,
  300. 'id': uuid(),
  301. 'args': (2, 2),
  302. 'kwargs': {},
  303. }, app=self.app))
  304. try:
  305. panel = self.create_panel(consumer=consumer)
  306. response = panel.handle('dump_reserved', {'safe': True})
  307. self.assertDictContainsSubset(
  308. {'name': self.mytask.name,
  309. 'args': (2, 2),
  310. 'kwargs': {},
  311. 'hostname': socket.gethostname()},
  312. response[0],
  313. )
  314. worker_state.reserved_requests.clear()
  315. self.assertFalse(panel.handle('dump_reserved'))
  316. finally:
  317. worker_state.reserved_requests.clear()
  318. def test_rate_limit_invalid_rate_limit_string(self):
  319. e = self.panel.handle('rate_limit', arguments=dict(
  320. task_name='tasks.add', rate_limit='x1240301#%!'))
  321. self.assertIn('Invalid rate limit string', e.get('error'))
  322. def test_rate_limit(self):
  323. class xConsumer(object):
  324. reset = False
  325. def reset_rate_limits(self):
  326. self.reset = True
  327. consumer = xConsumer()
  328. panel = self.create_panel(app=self.app, consumer=consumer)
  329. task = self.app.tasks[self.mytask.name]
  330. panel.handle('rate_limit', arguments=dict(task_name=task.name,
  331. rate_limit='100/m'))
  332. self.assertEqual(task.rate_limit, '100/m')
  333. self.assertTrue(consumer.reset)
  334. consumer.reset = False
  335. panel.handle('rate_limit', arguments=dict(task_name=task.name,
  336. rate_limit=0))
  337. self.assertEqual(task.rate_limit, 0)
  338. self.assertTrue(consumer.reset)
  339. def test_rate_limit_nonexistant_task(self):
  340. self.panel.handle('rate_limit', arguments={
  341. 'task_name': 'xxxx.does.not.exist',
  342. 'rate_limit': '1000/s'})
  343. def test_unexposed_command(self):
  344. with self.assertRaises(KeyError):
  345. self.panel.handle('foo', arguments={})
  346. def test_revoke_with_name(self):
  347. tid = uuid()
  348. m = {'method': 'revoke',
  349. 'destination': hostname,
  350. 'arguments': {'task_id': tid,
  351. 'task_name': self.mytask.name}}
  352. self.panel.handle_message(m, None)
  353. self.assertIn(tid, revoked)
  354. def test_revoke_with_name_not_in_registry(self):
  355. tid = uuid()
  356. m = {'method': 'revoke',
  357. 'destination': hostname,
  358. 'arguments': {'task_id': tid,
  359. 'task_name': 'xxxxxxxxx33333333388888'}}
  360. self.panel.handle_message(m, None)
  361. self.assertIn(tid, revoked)
  362. def test_revoke(self):
  363. tid = uuid()
  364. m = {'method': 'revoke',
  365. 'destination': hostname,
  366. 'arguments': {'task_id': tid}}
  367. self.panel.handle_message(m, None)
  368. self.assertIn(tid, revoked)
  369. m = {'method': 'revoke',
  370. 'destination': 'does.not.exist',
  371. 'arguments': {'task_id': tid + 'xxx'}}
  372. self.panel.handle_message(m, None)
  373. self.assertNotIn(tid + 'xxx', revoked)
  374. def test_revoke_terminate(self):
  375. request = Mock()
  376. request.id = tid = uuid()
  377. worker_state.reserved_requests.add(request)
  378. try:
  379. r = control.revoke(Mock(), tid, terminate=True)
  380. self.assertIn(tid, revoked)
  381. self.assertTrue(request.terminate.call_count)
  382. self.assertIn('terminate:', r['ok'])
  383. # unknown task id only revokes
  384. r = control.revoke(Mock(), uuid(), terminate=True)
  385. self.assertIn('tasks unknown', r['ok'])
  386. finally:
  387. worker_state.reserved_requests.discard(request)
  388. def test_autoscale(self):
  389. self.panel.state.consumer = Mock()
  390. self.panel.state.consumer.controller = Mock()
  391. sc = self.panel.state.consumer.controller.autoscaler = Mock()
  392. sc.update.return_value = 10, 2
  393. m = {'method': 'autoscale',
  394. 'destination': hostname,
  395. 'arguments': {'max': '10', 'min': '2'}}
  396. r = self.panel.handle_message(m, None)
  397. self.assertIn('ok', r)
  398. self.panel.state.consumer.controller.autoscaler = None
  399. r = self.panel.handle_message(m, None)
  400. self.assertIn('error', r)
  401. def test_ping(self):
  402. m = {'method': 'ping',
  403. 'destination': hostname}
  404. r = self.panel.handle_message(m, None)
  405. self.assertEqual(r, {'ok': 'pong'})
  406. def test_shutdown(self):
  407. m = {'method': 'shutdown',
  408. 'destination': hostname}
  409. with self.assertRaises(SystemExit):
  410. self.panel.handle_message(m, None)
  411. def test_panel_reply(self):
  412. replies = []
  413. class _Node(pidbox.Node):
  414. def reply(self, data, exchange, routing_key, **kwargs):
  415. replies.append(data)
  416. panel = _Node(hostname=hostname,
  417. state=self.create_state(consumer=Consumer(self.app)),
  418. handlers=Panel.data,
  419. mailbox=self.app.control.mailbox)
  420. r = panel.dispatch('ping', reply_to={'exchange': 'x',
  421. 'routing_key': 'x'})
  422. self.assertEqual(r, {'ok': 'pong'})
  423. self.assertDictEqual(replies[0], {panel.hostname: {'ok': 'pong'}})
  424. def test_pool_restart(self):
  425. consumer = Consumer(self.app)
  426. consumer.controller = _WC(app=self.app)
  427. consumer.controller.consumer = consumer
  428. consumer.controller.pool.restart = Mock()
  429. consumer.reset_rate_limits = Mock(name='reset_rate_limits()')
  430. consumer.update_strategies = Mock(name='update_strategies()')
  431. consumer.event_dispatcher = Mock(name='evd')
  432. panel = self.create_panel(consumer=consumer)
  433. assert panel.state.consumer.controller.consumer is consumer
  434. panel.app = self.app
  435. _import = panel.app.loader.import_from_cwd = Mock()
  436. _reload = Mock()
  437. with self.assertRaises(ValueError):
  438. panel.handle('pool_restart', {'reloader': _reload})
  439. self.app.conf.CELERYD_POOL_RESTARTS = True
  440. panel.handle('pool_restart', {'reloader': _reload})
  441. self.assertTrue(consumer.controller.pool.restart.called)
  442. consumer.reset_rate_limits.assert_called_with()
  443. consumer.update_strategies.assert_called_with()
  444. self.assertFalse(_reload.called)
  445. self.assertFalse(_import.called)
  446. def test_pool_restart_import_modules(self):
  447. consumer = Consumer(self.app)
  448. consumer.controller = _WC(app=self.app)
  449. consumer.controller.consumer = consumer
  450. consumer.controller.pool.restart = Mock()
  451. consumer.reset_rate_limits = Mock(name='reset_rate_limits()')
  452. consumer.update_strategies = Mock(name='update_strategies()')
  453. panel = self.create_panel(consumer=consumer)
  454. panel.app = self.app
  455. assert panel.state.consumer.controller.consumer is consumer
  456. _import = consumer.controller.app.loader.import_from_cwd = Mock()
  457. _reload = Mock()
  458. self.app.conf.CELERYD_POOL_RESTARTS = True
  459. panel.handle('pool_restart', {'modules': ['foo', 'bar'],
  460. 'reloader': _reload})
  461. self.assertTrue(consumer.controller.pool.restart.called)
  462. consumer.reset_rate_limits.assert_called_with()
  463. consumer.update_strategies.assert_called_with()
  464. self.assertFalse(_reload.called)
  465. self.assertItemsEqual(
  466. [call('bar'), call('foo')],
  467. _import.call_args_list,
  468. )
  469. def test_pool_restart_reload_modules(self):
  470. consumer = Consumer(self.app)
  471. consumer.controller = _WC(app=self.app)
  472. consumer.controller.consumer = consumer
  473. consumer.controller.pool.restart = Mock()
  474. consumer.reset_rate_limits = Mock(name='reset_rate_limits()')
  475. consumer.update_strategies = Mock(name='update_strategies()')
  476. panel = self.create_panel(consumer=consumer)
  477. panel.app = self.app
  478. _import = panel.app.loader.import_from_cwd = Mock()
  479. _reload = Mock()
  480. self.app.conf.CELERYD_POOL_RESTARTS = True
  481. with patch.dict(sys.modules, {'foo': None}):
  482. panel.handle('pool_restart', {'modules': ['foo'],
  483. 'reload': False,
  484. 'reloader': _reload})
  485. self.assertTrue(consumer.controller.pool.restart.called)
  486. self.assertFalse(_reload.called)
  487. self.assertFalse(_import.called)
  488. _import.reset_mock()
  489. _reload.reset_mock()
  490. consumer.controller.pool.restart.reset_mock()
  491. panel.handle('pool_restart', {'modules': ['foo'],
  492. 'reload': True,
  493. 'reloader': _reload})
  494. self.assertTrue(consumer.controller.pool.restart.called)
  495. self.assertTrue(_reload.called)
  496. self.assertFalse(_import.called)