celery.py 36 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180
  1. # -*- coding: utf-8 -*-
  2. """
  3. The :program:`celery` umbrella command.
  4. .. program:: celery
  5. .. _preload-options:
  6. Preload Options
  7. ---------------
  8. These options are supported by all commands,
  9. and usually parsed before command-specific arguments.
  10. .. cmdoption:: -A, --app
  11. app instance to use (e.g. ``module.attr_name``)
  12. .. cmdoption:: -b, --broker
  13. URL to broker. default is ``amqp://guest@localhost//``
  14. .. cmdoption:: --loader
  15. name of custom loader class to use.
  16. .. cmdoption:: --config
  17. Name of the configuration module
  18. .. cmdoption:: -C, --no-color
  19. Disable colors in output.
  20. .. cmdoption:: -q, --quiet
  21. Give less verbose output (behavior depends on the sub command).
  22. .. cmdoption:: --help
  23. Show help and exit.
  24. .. _daemon-options:
  25. Daemon Options
  26. --------------
  27. These options are supported by commands that can detach
  28. into the background (daemon). They will be present
  29. in any command that also has a `--detach` option.
  30. .. cmdoption:: -f, --logfile
  31. Path to log file. If no logfile is specified, `stderr` is used.
  32. .. cmdoption:: --pidfile
  33. Optional file used to store the process pid.
  34. The program will not start if this file already exists
  35. and the pid is still alive.
  36. .. cmdoption:: --uid
  37. User id, or user name of the user to run as after detaching.
  38. .. cmdoption:: --gid
  39. Group id, or group name of the main group to change to after
  40. detaching.
  41. .. cmdoption:: --umask
  42. Effective umask (in octal) of the process after detaching. Inherits
  43. the umask of the parent process by default.
  44. .. cmdoption:: --workdir
  45. Optional directory to change to after detaching.
  46. .. cmdoption:: --executable
  47. Executable to use for the detached process.
  48. ``celery inspect``
  49. ------------------
  50. .. program:: celery inspect
  51. .. cmdoption:: -t, --timeout
  52. Timeout in seconds (float) waiting for reply
  53. .. cmdoption:: -d, --destination
  54. Comma separated list of destination node names.
  55. .. cmdoption:: -j, --json
  56. Use json as output format.
  57. ``celery control``
  58. ------------------
  59. .. program:: celery control
  60. .. cmdoption:: -t, --timeout
  61. Timeout in seconds (float) waiting for reply
  62. .. cmdoption:: -d, --destination
  63. Comma separated list of destination node names.
  64. .. cmdoption:: -j, --json
  65. Use json as output format.
  66. ``celery migrate``
  67. ------------------
  68. .. program:: celery migrate
  69. .. cmdoption:: -n, --limit
  70. Number of tasks to consume (int).
  71. .. cmdoption:: -t, -timeout
  72. Timeout in seconds (float) waiting for tasks.
  73. .. cmdoption:: -a, --ack-messages
  74. Ack messages from source broker.
  75. .. cmdoption:: -T, --tasks
  76. List of task names to filter on.
  77. .. cmdoption:: -Q, --queues
  78. List of queues to migrate.
  79. .. cmdoption:: -F, --forever
  80. Continually migrate tasks until killed.
  81. ``celery upgrade``
  82. ------------------
  83. .. program:: celery upgrade
  84. .. cmdoption:: --django
  85. Upgrade a Django project.
  86. .. cmdoption:: --compat
  87. Maintain backwards compatibility.
  88. .. cmdoption:: --no-backup
  89. Don't backup original files.
  90. ``celery shell``
  91. ----------------
  92. .. program:: celery shell
  93. .. cmdoption:: -I, --ipython
  94. Force :pypi:`iPython` implementation.
  95. .. cmdoption:: -B, --bpython
  96. Force :pypi:`bpython` implementation.
  97. .. cmdoption:: -P, --python
  98. Force default Python shell.
  99. .. cmdoption:: -T, --without-tasks
  100. Don't add tasks to locals.
  101. .. cmdoption:: --eventlet
  102. Use :pypi:`eventlet` monkey patches.
  103. .. cmdoption:: --gevent
  104. Use :pypi:`gevent` monkey patches.
  105. ``celery result``
  106. -----------------
  107. .. program:: celery result
  108. .. cmdoption:: -t, --task
  109. Name of task (if custom backend).
  110. .. cmdoption:: --traceback
  111. Show traceback if any.
  112. ``celery purge``
  113. ----------------
  114. .. program:: celery purge
  115. .. cmdoption:: -f, --force
  116. Don't prompt for verification before deleting messages (DANGEROUS)
  117. ``celery call``
  118. ---------------
  119. .. program:: celery call
  120. .. cmdoption:: -a, --args
  121. Positional arguments (json format).
  122. .. cmdoption:: -k, --kwargs
  123. Keyword arguments (json format).
  124. .. cmdoption:: --eta
  125. Scheduled time in ISO-8601 format.
  126. .. cmdoption:: --countdown
  127. ETA in seconds from now (float/int).
  128. .. cmdoption:: --expires
  129. Expiry time in float/int seconds, or a ISO-8601 date.
  130. .. cmdoption:: --serializer
  131. Specify serializer to use (default is json).
  132. .. cmdoption:: --queue
  133. Destination queue.
  134. .. cmdoption:: --exchange
  135. Destination exchange (defaults to the queue exchange).
  136. .. cmdoption:: --routing-key
  137. Destination routing key (defaults to the queue routing key).
  138. """
  139. from __future__ import absolute_import, unicode_literals, print_function
  140. import codecs
  141. import numbers
  142. import os
  143. import sys
  144. from functools import partial
  145. from importlib import import_module
  146. from kombu.utils import json
  147. from celery.app import defaults
  148. from celery.five import string_t, values
  149. from celery.platforms import EX_OK, EX_FAILURE, EX_UNAVAILABLE, EX_USAGE
  150. from celery.utils import term
  151. from celery.utils import text
  152. from celery.utils.functional import pass1
  153. from celery.utils.timeutils import maybe_iso8601
  154. # Cannot use relative imports here due to a Windows issue (#1111).
  155. from celery.bin.base import Command, Option, Extensions
  156. # Import commands from other modules
  157. from celery.bin.amqp import amqp
  158. from celery.bin.beat import beat
  159. from celery.bin.events import events
  160. from celery.bin.graph import graph
  161. from celery.bin.logtool import logtool
  162. from celery.bin.worker import worker
  163. __all__ = ['CeleryCommand', 'main']
  164. HELP = """
  165. ---- -- - - ---- Commands- -------------- --- ------------
  166. {commands}
  167. ---- -- - - --------- -- - -------------- --- ------------
  168. Type '{prog_name} <command> --help' for help using a specific command.
  169. """
  170. MIGRATE_PROGRESS_FMT = """\
  171. Migrating task {state.count}/{state.strtotal}: \
  172. {body[task]}[{body[id]}]\
  173. """
  174. command_classes = [
  175. ('Main', ['worker', 'events', 'beat', 'shell', 'multi', 'amqp'], 'green'),
  176. ('Remote Control', ['status', 'inspect', 'control'], 'blue'),
  177. ('Utils',
  178. ['purge', 'list', 'call', 'result', 'migrate', 'graph', 'upgrade'],
  179. None),
  180. ('Debugging', ['report', 'logtool'], 'red'),
  181. ]
  182. def determine_exit_status(ret):
  183. if isinstance(ret, numbers.Integral):
  184. return ret
  185. return EX_OK if ret else EX_FAILURE
  186. def main(argv=None):
  187. # Fix for setuptools generated scripts, so that it will
  188. # work with multiprocessing fork emulation.
  189. # (see multiprocessing.forking.get_preparation_data())
  190. try:
  191. if __name__ != '__main__': # pragma: no cover
  192. sys.modules['__main__'] = sys.modules[__name__]
  193. cmd = CeleryCommand()
  194. cmd.maybe_patch_concurrency()
  195. from billiard import freeze_support
  196. freeze_support()
  197. cmd.execute_from_commandline(argv)
  198. except KeyboardInterrupt:
  199. pass
  200. class multi(Command):
  201. """Start multiple worker instances."""
  202. respects_app_option = False
  203. def get_options(self):
  204. pass
  205. def run_from_argv(self, prog_name, argv, command=None):
  206. from celery.bin.multi import MultiTool
  207. multi = MultiTool(quiet=self.quiet, no_color=self.no_color)
  208. return multi.execute_from_commandline(
  209. [command] + argv, prog_name,
  210. )
  211. class list_(Command):
  212. """Get info from broker.
  213. Examples::
  214. celery list bindings
  215. NOTE: For RabbitMQ the management plugin is required.
  216. """
  217. args = '[bindings]'
  218. def list_bindings(self, management):
  219. try:
  220. bindings = management.get_bindings()
  221. except NotImplementedError:
  222. raise self.Error('Your transport cannot list bindings.')
  223. def fmt(q, e, r):
  224. return self.out('{0:<28} {1:<28} {2}'.format(q, e, r))
  225. fmt('Queue', 'Exchange', 'Routing Key')
  226. fmt('-' * 16, '-' * 16, '-' * 16)
  227. for b in bindings:
  228. fmt(b['destination'], b['source'], b['routing_key'])
  229. def run(self, what=None, *_, **kw):
  230. topics = {'bindings': self.list_bindings}
  231. available = ', '.join(topics)
  232. if not what:
  233. raise self.UsageError(
  234. 'You must specify one of {0}'.format(available))
  235. if what not in topics:
  236. raise self.UsageError(
  237. 'unknown topic {0!r} (choose one of: {1})'.format(
  238. what, available))
  239. with self.app.connection() as conn:
  240. self.app.amqp.TaskConsumer(conn).declare()
  241. topics[what](conn.manager)
  242. class call(Command):
  243. """Call a task by name.
  244. Examples::
  245. celery call tasks.add --args='[2, 2]'
  246. celery call tasks.add --args='[2, 2]' --countdown=10
  247. """
  248. args = '<task_name>'
  249. option_list = Command.option_list + (
  250. Option('--args', '-a', help='positional arguments (json).'),
  251. Option('--kwargs', '-k', help='keyword arguments (json).'),
  252. Option('--eta', help='scheduled time (ISO-8601).'),
  253. Option('--countdown', type='float',
  254. help='eta in seconds from now (float/int).'),
  255. Option('--expires', help='expiry time (ISO-8601/float/int).'),
  256. Option('--serializer', default='json', help='defaults to json.'),
  257. Option('--queue', help='custom queue name.'),
  258. Option('--exchange', help='custom exchange name.'),
  259. Option('--routing-key', help='custom routing key.'),
  260. )
  261. def run(self, name, *_, **kw):
  262. # Positional args.
  263. args = kw.get('args') or ()
  264. if isinstance(args, string_t):
  265. args = json.loads(args)
  266. # Keyword args.
  267. kwargs = kw.get('kwargs') or {}
  268. if isinstance(kwargs, string_t):
  269. kwargs = json.loads(kwargs)
  270. # Expires can be int/float.
  271. expires = kw.get('expires') or None
  272. try:
  273. expires = float(expires)
  274. except (TypeError, ValueError):
  275. # or a string describing an ISO 8601 datetime.
  276. try:
  277. expires = maybe_iso8601(expires)
  278. except (TypeError, ValueError):
  279. raise
  280. res = self.app.send_task(name, args=args, kwargs=kwargs,
  281. countdown=kw.get('countdown'),
  282. serializer=kw.get('serializer'),
  283. queue=kw.get('queue'),
  284. exchange=kw.get('exchange'),
  285. routing_key=kw.get('routing_key'),
  286. eta=maybe_iso8601(kw.get('eta')),
  287. expires=expires)
  288. self.out(res.id)
  289. class purge(Command):
  290. """Erase all messages from all known task queues.
  291. WARNING: There is no undo operation for this command.
  292. """
  293. warn_prelude = (
  294. '{warning}: This will remove all tasks from {queues}: {names}.\n'
  295. ' There is no undo for this operation!\n\n'
  296. '(to skip this prompt use the -f option)\n'
  297. )
  298. warn_prompt = 'Are you sure you want to delete all tasks'
  299. fmt_purged = 'Purged {mnum} {messages} from {qnum} known task {queues}.'
  300. fmt_empty = 'No messages purged from {qnum} {queues}'
  301. option_list = Command.option_list + (
  302. Option('--force', '-f', action='store_true',
  303. help='Do not prompt for verification'),
  304. )
  305. def run(self, force=False, **kwargs):
  306. names = list(sorted(self.app.amqp.queues.keys()))
  307. qnum = len(names)
  308. if not force:
  309. self.out(self.warn_prelude.format(
  310. warning=self.colored.red('WARNING'),
  311. queues=text.pluralize(qnum, 'queue'), names=', '.join(names),
  312. ))
  313. if self.ask(self.warn_prompt, ('yes', 'no'), 'no') != 'yes':
  314. return
  315. messages = self.app.control.purge()
  316. fmt = self.fmt_purged if messages else self.fmt_empty
  317. self.out(fmt.format(
  318. mnum=messages, qnum=qnum,
  319. messages=text.pluralize(messages, 'message'),
  320. queues=text.pluralize(qnum, 'queue')))
  321. class result(Command):
  322. """Gives the return value for a given task id.
  323. Examples::
  324. celery result 8f511516-e2f5-4da4-9d2f-0fb83a86e500
  325. celery result 8f511516-e2f5-4da4-9d2f-0fb83a86e500 -t tasks.add
  326. celery result 8f511516-e2f5-4da4-9d2f-0fb83a86e500 --traceback
  327. """
  328. args = '<task_id>'
  329. option_list = Command.option_list + (
  330. Option('--task', '-t', help='name of task (if custom backend)'),
  331. Option('--traceback', action='store_true',
  332. help='show traceback instead'),
  333. )
  334. def run(self, task_id, *args, **kwargs):
  335. result_cls = self.app.AsyncResult
  336. task = kwargs.get('task')
  337. traceback = kwargs.get('traceback', False)
  338. if task:
  339. result_cls = self.app.tasks[task].AsyncResult
  340. result = result_cls(task_id)
  341. if traceback:
  342. value = result.traceback
  343. else:
  344. value = result.get()
  345. self.out(self.pretty(value)[1])
  346. class _RemoteControl(Command):
  347. name = None
  348. choices = None
  349. leaf = False
  350. option_list = Command.option_list + (
  351. Option('--timeout', '-t', type='float',
  352. help='Timeout in seconds (float) waiting for reply'),
  353. Option('--destination', '-d',
  354. help='Comma separated list of destination node names.'),
  355. Option('--json', '-j', action='store_true',
  356. help='Use json as output format.'),
  357. )
  358. def __init__(self, *args, **kwargs):
  359. self.show_body = kwargs.pop('show_body', True)
  360. self.show_reply = kwargs.pop('show_reply', True)
  361. super(_RemoteControl, self).__init__(*args, **kwargs)
  362. @classmethod
  363. def get_command_info(self, command,
  364. indent=0, prefix='', color=None, help=False):
  365. if help:
  366. help = '|' + text.indent(self.choices[command][1], indent + 4)
  367. else:
  368. help = None
  369. try:
  370. # see if it uses args.
  371. meth = getattr(self, command)
  372. return text.join([
  373. '|' + text.indent('{0}{1} {2}'.format(
  374. prefix, color(command), meth.__doc__), indent),
  375. help,
  376. ])
  377. except AttributeError:
  378. return text.join([
  379. '|' + text.indent(prefix + str(color(command)), indent), help,
  380. ])
  381. @classmethod
  382. def list_commands(self, indent=0, prefix='', color=None, help=False):
  383. color = color if color else lambda x: x
  384. prefix = prefix + ' ' if prefix else ''
  385. return '\n'.join(self.get_command_info(c, indent, prefix, color, help)
  386. for c in sorted(self.choices))
  387. @property
  388. def epilog(self):
  389. return '\n'.join([
  390. '[Commands]',
  391. self.list_commands(indent=4, help=True)
  392. ])
  393. def usage(self, command):
  394. return '%prog {0} [options] {1} <command> [arg1 .. argN]'.format(
  395. command, self.args)
  396. def call(self, *args, **kwargs):
  397. raise NotImplementedError('call')
  398. def run(self, *args, **kwargs):
  399. if not args:
  400. raise self.UsageError(
  401. 'Missing {0.name} method. See --help'.format(self))
  402. return self.do_call_method(args, **kwargs)
  403. def do_call_method(self, args, **kwargs):
  404. method = args[0]
  405. if method == 'help':
  406. raise self.Error("Did you mean '{0.name} --help'?".format(self))
  407. if method not in self.choices:
  408. raise self.UsageError(
  409. 'Unknown {0.name} method {1}'.format(self, method))
  410. if self.app.connection_for_write().transport.driver_type == 'sql':
  411. raise self.Error('Broadcast not supported by SQL broker transport')
  412. output_json = kwargs.get('json')
  413. destination = kwargs.get('destination')
  414. timeout = kwargs.get('timeout') or self.choices[method][0]
  415. if destination and isinstance(destination, string_t):
  416. destination = [dest.strip() for dest in destination.split(',')]
  417. handler = getattr(self, method, self.call)
  418. callback = None if output_json else self.say_remote_command_reply
  419. replies = handler(method, *args[1:], timeout=timeout,
  420. destination=destination,
  421. callback=callback)
  422. if not replies:
  423. raise self.Error('No nodes replied within time constraint.',
  424. status=EX_UNAVAILABLE)
  425. if output_json:
  426. self.out(json.dumps(replies))
  427. return replies
  428. class inspect(_RemoteControl):
  429. """Inspect the worker at runtime.
  430. Availability: RabbitMQ (AMQP), Redis, and MongoDB transports.
  431. Examples::
  432. celery inspect active --timeout=5
  433. celery inspect scheduled -d worker1@example.com
  434. celery inspect revoked -d w1@e.com,w2@e.com
  435. """
  436. name = 'inspect'
  437. choices = {
  438. 'active': (1.0, 'dump active tasks (being processed)'),
  439. 'active_queues': (1.0, 'dump queues being consumed from'),
  440. 'scheduled': (1.0, 'dump scheduled tasks (eta/countdown/retry)'),
  441. 'reserved': (1.0, 'dump reserved tasks (waiting to be processed)'),
  442. 'stats': (1.0, 'dump worker statistics'),
  443. 'revoked': (1.0, 'dump of revoked task ids'),
  444. 'registered': (1.0, 'dump of registered tasks'),
  445. 'ping': (0.2, 'ping worker(s)'),
  446. 'clock': (1.0, 'get value of logical clock'),
  447. 'conf': (1.0, 'dump worker configuration'),
  448. 'report': (1.0, 'get bugreport info'),
  449. 'memsample': (1.0, 'sample memory (requires psutil)'),
  450. 'memdump': (1.0, 'dump memory samples (requires psutil)'),
  451. 'objgraph': (60.0, 'create object graph (requires objgraph)'),
  452. }
  453. def call(self, method, *args, **options):
  454. i = self.app.control.inspect(**options)
  455. return getattr(i, method)(*args)
  456. def objgraph(self, type_='Request', *args, **kwargs):
  457. return self.call('objgraph', type_, **kwargs)
  458. def conf(self, with_defaults=False, *args, **kwargs):
  459. return self.call('conf', with_defaults, **kwargs)
  460. class control(_RemoteControl):
  461. """Workers remote control.
  462. Availability: RabbitMQ (AMQP), Redis, and MongoDB transports.
  463. Examples::
  464. celery control enable_events --timeout=5
  465. celery control -d worker1@example.com enable_events
  466. celery control -d w1.e.com,w2.e.com enable_events
  467. celery control -d w1.e.com add_consumer queue_name
  468. celery control -d w1.e.com cancel_consumer queue_name
  469. celery control -d w1.e.com add_consumer queue exchange direct rkey
  470. """
  471. name = 'control'
  472. choices = {
  473. 'enable_events': (1.0, 'tell worker(s) to enable events'),
  474. 'disable_events': (1.0, 'tell worker(s) to disable events'),
  475. 'add_consumer': (1.0, 'tell worker(s) to start consuming a queue'),
  476. 'cancel_consumer': (1.0, 'tell worker(s) to stop consuming a queue'),
  477. 'rate_limit': (
  478. 1.0, 'tell worker(s) to modify the rate limit for a task type'),
  479. 'time_limit': (
  480. 1.0, 'tell worker(s) to modify the time limit for a task type.'),
  481. 'autoscale': (1.0, 'change autoscale settings'),
  482. 'pool_grow': (1.0, 'start more pool processes'),
  483. 'pool_shrink': (1.0, 'use less pool processes'),
  484. }
  485. def call(self, method, *args, **options):
  486. return getattr(self.app.control, method)(*args, reply=True, **options)
  487. def pool_grow(self, method, n=1, **kwargs):
  488. """[N=1]"""
  489. return self.call(method, int(n), **kwargs)
  490. def pool_shrink(self, method, n=1, **kwargs):
  491. """[N=1]"""
  492. return self.call(method, int(n), **kwargs)
  493. def autoscale(self, method, max=None, min=None, **kwargs):
  494. """[max] [min]"""
  495. return self.call(method, int(max), int(min), **kwargs)
  496. def rate_limit(self, method, task_name, rate_limit, **kwargs):
  497. """<task_name> <rate_limit> (e.g. 5/s | 5/m | 5/h)>"""
  498. return self.call(method, task_name, rate_limit, **kwargs)
  499. def time_limit(self, method, task_name, soft, hard=None, **kwargs):
  500. """<task_name> <soft_secs> [hard_secs]"""
  501. return self.call(method, task_name,
  502. float(soft), float(hard), **kwargs)
  503. def add_consumer(self, method, queue, exchange=None,
  504. exchange_type='direct', routing_key=None, **kwargs):
  505. """<queue> [exchange [type [routing_key]]]"""
  506. return self.call(method, queue, exchange,
  507. exchange_type, routing_key, **kwargs)
  508. def cancel_consumer(self, method, queue, **kwargs):
  509. """<queue>"""
  510. return self.call(method, queue, **kwargs)
  511. class status(Command):
  512. """Show list of workers that are online."""
  513. option_list = inspect.option_list
  514. def run(self, *args, **kwargs):
  515. I = inspect(
  516. app=self.app,
  517. no_color=kwargs.get('no_color', False),
  518. stdout=self.stdout, stderr=self.stderr,
  519. show_reply=False, show_body=False, quiet=True,
  520. )
  521. replies = I.run('ping', **kwargs)
  522. if not replies:
  523. raise self.Error('No nodes replied within time constraint',
  524. status=EX_UNAVAILABLE)
  525. nodecount = len(replies)
  526. if not kwargs.get('quiet', False):
  527. self.out('\n{0} {1} online.'.format(
  528. nodecount, text.pluralize(nodecount, 'node')))
  529. class migrate(Command):
  530. """Migrate tasks from one broker to another.
  531. Examples:
  532. .. code-block:: console
  533. $ celery migrate redis://localhost amqp://guest@localhost//
  534. $ celery migrate django:// redis://localhost
  535. NOTE: This command is experimental, make sure you have
  536. a backup of the tasks before you continue.
  537. """
  538. args = '<source_url> <dest_url>'
  539. option_list = Command.option_list + (
  540. Option('--limit', '-n', type='int',
  541. help='Number of tasks to consume (int)'),
  542. Option('--timeout', '-t', type='float', default=1.0,
  543. help='Timeout in seconds (float) waiting for tasks'),
  544. Option('--ack-messages', '-a', action='store_true',
  545. help='Ack messages from source broker.'),
  546. Option('--tasks', '-T',
  547. help='List of task names to filter on.'),
  548. Option('--queues', '-Q',
  549. help='List of queues to migrate.'),
  550. Option('--forever', '-F', action='store_true',
  551. help='Continually migrate tasks until killed.'),
  552. )
  553. progress_fmt = MIGRATE_PROGRESS_FMT
  554. def on_migrate_task(self, state, body, message):
  555. self.out(self.progress_fmt.format(state=state, body=body))
  556. def run(self, source, destination, **kwargs):
  557. from kombu import Connection
  558. from celery.contrib.migrate import migrate_tasks
  559. migrate_tasks(Connection(source),
  560. Connection(destination),
  561. callback=self.on_migrate_task,
  562. **kwargs)
  563. class shell(Command): # pragma: no cover
  564. """Start shell session with convenient access to celery symbols.
  565. The following symbols will be added to the main globals:
  566. - celery: the current application.
  567. - chord, group, chain, chunks,
  568. xmap, xstarmap subtask, Task
  569. - all registered tasks.
  570. """
  571. option_list = Command.option_list + (
  572. Option('--ipython', '-I',
  573. action='store_true', dest='force_ipython',
  574. help='force iPython.'),
  575. Option('--bpython', '-B',
  576. action='store_true', dest='force_bpython',
  577. help='force bpython.'),
  578. Option('--python', '-P',
  579. action='store_true', dest='force_python',
  580. help='force default Python shell.'),
  581. Option('--without-tasks', '-T', action='store_true',
  582. help="don't add tasks to locals."),
  583. Option('--eventlet', action='store_true',
  584. help='use eventlet.'),
  585. Option('--gevent', action='store_true', help='use gevent.'),
  586. )
  587. def run(self, force_ipython=False, force_bpython=False,
  588. force_python=False, without_tasks=False, eventlet=False,
  589. gevent=False, **kwargs):
  590. sys.path.insert(0, os.getcwd())
  591. if eventlet:
  592. import_module('celery.concurrency.eventlet')
  593. if gevent:
  594. import_module('celery.concurrency.gevent')
  595. import celery
  596. import celery.task.base
  597. self.app.loader.import_default_modules()
  598. self.locals = {'app': self.app,
  599. 'celery': self.app,
  600. 'Task': celery.Task,
  601. 'chord': celery.chord,
  602. 'group': celery.group,
  603. 'chain': celery.chain,
  604. 'chunks': celery.chunks,
  605. 'xmap': celery.xmap,
  606. 'xstarmap': celery.xstarmap,
  607. 'subtask': celery.subtask,
  608. 'signature': celery.signature}
  609. if not without_tasks:
  610. self.locals.update({
  611. task.__name__: task for task in values(self.app.tasks)
  612. if not task.name.startswith('celery.')
  613. })
  614. if force_python:
  615. return self.invoke_fallback_shell()
  616. elif force_bpython:
  617. return self.invoke_bpython_shell()
  618. elif force_ipython:
  619. return self.invoke_ipython_shell()
  620. return self.invoke_default_shell()
  621. def invoke_default_shell(self):
  622. try:
  623. import IPython # noqa
  624. except ImportError:
  625. try:
  626. import bpython # noqa
  627. except ImportError:
  628. return self.invoke_fallback_shell()
  629. else:
  630. return self.invoke_bpython_shell()
  631. else:
  632. return self.invoke_ipython_shell()
  633. def invoke_fallback_shell(self):
  634. import code
  635. try:
  636. import readline
  637. except ImportError:
  638. pass
  639. else:
  640. import rlcompleter
  641. readline.set_completer(
  642. rlcompleter.Completer(self.locals).complete)
  643. readline.parse_and_bind('tab:complete')
  644. code.interact(local=self.locals)
  645. def invoke_ipython_shell(self):
  646. for ip in (self._ipython, self._ipython_pre_10,
  647. self._ipython_terminal, self._ipython_010,
  648. self._no_ipython):
  649. try:
  650. return ip()
  651. except ImportError:
  652. pass
  653. def _ipython(self):
  654. from IPython import start_ipython
  655. start_ipython(argv=[], user_ns=self.locals)
  656. def _ipython_pre_10(self): # pragma: no cover
  657. from IPython.frontend.terminal.ipapp import TerminalIPythonApp
  658. app = TerminalIPythonApp.instance()
  659. app.initialize(argv=[])
  660. app.shell.user_ns.update(self.locals)
  661. app.start()
  662. def _ipython_terminal(self): # pragma: no cover
  663. from IPython.terminal import embed
  664. embed.TerminalInteractiveShell(user_ns=self.locals).mainloop()
  665. def _ipython_010(self): # pragma: no cover
  666. from IPython.Shell import IPShell
  667. IPShell(argv=[], user_ns=self.locals).mainloop()
  668. def _no_ipython(self): # pragma: no cover
  669. raise ImportError('no suitable ipython found')
  670. def invoke_bpython_shell(self):
  671. import bpython
  672. bpython.embed(self.locals)
  673. class upgrade(Command):
  674. """Perform upgrade between versions."""
  675. option_list = Command.option_list + (
  676. Option('--django', action='store_true',
  677. help='Upgrade Django project'),
  678. Option('--compat', action='store_true',
  679. help='Maintain backwards compatibility'),
  680. Option('--no-backup', action='store_true',
  681. help='Dont backup original files'),
  682. )
  683. choices = {'settings'}
  684. def usage(self, command):
  685. return '%prog <command> settings [filename] [options]'
  686. def run(self, *args, **kwargs):
  687. try:
  688. command = args[0]
  689. except IndexError:
  690. raise self.UsageError('missing upgrade type')
  691. if command not in self.choices:
  692. raise self.UsageError('unknown upgrade type: {0}'.format(command))
  693. return getattr(self, command)(*args, **kwargs)
  694. def settings(self, command, filename,
  695. no_backup=False, django=False, compat=False, **kwargs):
  696. lines = self._slurp(filename) if no_backup else self._backup(filename)
  697. keyfilter = self._compat_key if django or compat else pass1
  698. print('processing {0}...'.format(filename), file=self.stderr)
  699. with codecs.open(filename, 'w', 'utf-8') as write_fh:
  700. for line in lines:
  701. write_fh.write(self._to_new_key(line, keyfilter))
  702. def _slurp(self, filename):
  703. with codecs.open(filename, 'r', 'utf-8') as read_fh:
  704. return [line for line in read_fh]
  705. def _backup(self, filename, suffix='.orig'):
  706. lines = []
  707. backup_filename = ''.join([filename, suffix])
  708. print('writing backup to {0}...'.format(backup_filename),
  709. file=self.stderr)
  710. with codecs.open(filename, 'r', 'utf-8') as read_fh:
  711. with codecs.open(backup_filename, 'w', 'utf-8') as backup_fh:
  712. for line in read_fh:
  713. backup_fh.write(line)
  714. lines.append(line)
  715. return lines
  716. def _to_new_key(self, line, keyfilter=pass1, source=defaults._TO_NEW_KEY):
  717. # sort by length to avoid e.g. broker_transport overriding
  718. # broker_transport_options.
  719. for old_key in reversed(sorted(source, key=lambda x: len(x))):
  720. new_line = line.replace(old_key, keyfilter(source[old_key]))
  721. if line != new_line:
  722. return new_line # only one match per line.
  723. return line
  724. def _compat_key(self, key, namespace='CELERY'):
  725. key = key.upper()
  726. if not key.startswith(namespace):
  727. key = '_'.join([namespace, key])
  728. return key
  729. class help(Command):
  730. """Show help screen and exit."""
  731. def usage(self, command):
  732. return '%prog <command> [options] {0.args}'.format(self)
  733. def run(self, *args, **kwargs):
  734. self.parser.print_help()
  735. self.out(HELP.format(
  736. prog_name=self.prog_name,
  737. commands=CeleryCommand.list_commands(colored=self.colored),
  738. ))
  739. return EX_USAGE
  740. class report(Command):
  741. """Shows information useful to include in bug-reports."""
  742. def run(self, *args, **kwargs):
  743. self.out(self.app.bugreport())
  744. return EX_OK
  745. class CeleryCommand(Command):
  746. ext_fmt = '{self.namespace}.commands'
  747. commands = {
  748. 'amqp': amqp,
  749. 'beat': beat,
  750. 'call': call,
  751. 'control': control,
  752. 'events': events,
  753. 'graph': graph,
  754. 'help': help,
  755. 'inspect': inspect,
  756. 'list': list_,
  757. 'logtool': logtool,
  758. 'migrate': migrate,
  759. 'multi': multi,
  760. 'purge': purge,
  761. 'report': report,
  762. 'result': result,
  763. 'shell': shell,
  764. 'status': status,
  765. 'upgrade': upgrade,
  766. 'worker': worker,
  767. }
  768. enable_config_from_cmdline = True
  769. prog_name = 'celery'
  770. namespace = 'celery'
  771. @classmethod
  772. def register_command(cls, fun, name=None):
  773. cls.commands[name or fun.__name__] = fun
  774. return fun
  775. def execute(self, command, argv=None):
  776. try:
  777. cls = self.commands[command]
  778. except KeyError:
  779. cls, argv = self.commands['help'], ['help']
  780. cls = self.commands.get(command) or self.commands['help']
  781. try:
  782. return cls(
  783. app=self.app, on_error=self.on_error,
  784. no_color=self.no_color, quiet=self.quiet,
  785. on_usage_error=partial(self.on_usage_error, command=command),
  786. ).run_from_argv(self.prog_name, argv[1:], command=argv[0])
  787. except self.UsageError as exc:
  788. self.on_usage_error(exc)
  789. return exc.status
  790. except self.Error as exc:
  791. self.on_error(exc)
  792. return exc.status
  793. def on_usage_error(self, exc, command=None):
  794. if command:
  795. helps = '{self.prog_name} {command} --help'
  796. else:
  797. helps = '{self.prog_name} --help'
  798. self.error(self.colored.magenta('Error: {0}'.format(exc)))
  799. self.error("""Please try '{0}'""".format(helps.format(
  800. self=self, command=command,
  801. )))
  802. def _relocate_args_from_start(self, argv, index=0):
  803. if argv:
  804. rest = []
  805. while index < len(argv):
  806. value = argv[index]
  807. if value.startswith('--'):
  808. rest.append(value)
  809. elif value.startswith('-'):
  810. # we eat the next argument even though we don't know
  811. # if this option takes an argument or not.
  812. # instead we will assume what is the command name in the
  813. # return statements below.
  814. try:
  815. nxt = argv[index + 1]
  816. if nxt.startswith('-'):
  817. # is another option
  818. rest.append(value)
  819. else:
  820. # is (maybe) a value for this option
  821. rest.extend([value, nxt])
  822. index += 1
  823. except IndexError: # pragma: no cover
  824. rest.append(value)
  825. break
  826. else:
  827. break
  828. index += 1
  829. if argv[index:]: # pragma: no cover
  830. # if there are more arguments left then divide and swap
  831. # we assume the first argument in argv[i:] is the command
  832. # name.
  833. return argv[index:] + rest
  834. # if there are no more arguments then the last arg in rest'
  835. # must be the command.
  836. [rest.pop()] + rest
  837. return []
  838. def prepare_prog_name(self, name):
  839. if name == '__main__.py':
  840. return sys.modules['__main__'].__file__
  841. return name
  842. def handle_argv(self, prog_name, argv):
  843. self.prog_name = self.prepare_prog_name(prog_name)
  844. argv = self._relocate_args_from_start(argv)
  845. _, argv = self.prepare_args(None, argv)
  846. try:
  847. command = argv[0]
  848. except IndexError:
  849. command, argv = 'help', ['help']
  850. return self.execute(command, argv)
  851. def execute_from_commandline(self, argv=None):
  852. argv = sys.argv if argv is None else argv
  853. if 'multi' in argv[1:3]: # Issue 1008
  854. self.respects_app_option = False
  855. try:
  856. sys.exit(determine_exit_status(
  857. super(CeleryCommand, self).execute_from_commandline(argv)))
  858. except KeyboardInterrupt:
  859. sys.exit(EX_FAILURE)
  860. @classmethod
  861. def get_command_info(self, command, indent=0, color=None, colored=None):
  862. colored = term.colored() if colored is None else colored
  863. colored = colored.names[color] if color else lambda x: x
  864. obj = self.commands[command]
  865. cmd = 'celery {0}'.format(colored(command))
  866. if obj.leaf:
  867. return '|' + text.indent(cmd, indent)
  868. return text.join([
  869. ' ',
  870. '|' + text.indent('{0} --help'.format(cmd), indent),
  871. obj.list_commands(indent, 'celery {0}'.format(command), colored),
  872. ])
  873. @classmethod
  874. def list_commands(self, indent=0, colored=None):
  875. colored = term.colored() if colored is None else colored
  876. white = colored.white
  877. ret = []
  878. for cls, commands, color in command_classes:
  879. ret.extend([
  880. text.indent('+ {0}: '.format(white(cls)), indent),
  881. '\n'.join(
  882. self.get_command_info(command, indent + 4, color, colored)
  883. for command in commands),
  884. ''
  885. ])
  886. return '\n'.join(ret).strip()
  887. def with_pool_option(self, argv):
  888. if len(argv) > 1 and 'worker' in argv[0:3]:
  889. # this command supports custom pools
  890. # that may have to be loaded as early as possible.
  891. return (['-P'], ['--pool'])
  892. def on_concurrency_setup(self):
  893. self.load_extension_commands()
  894. def load_extension_commands(self):
  895. names = Extensions(self.ext_fmt.format(self=self),
  896. self.register_command).load()
  897. if names:
  898. command_classes.append(('Extensions', names, 'magenta'))
  899. def command(*args, **kwargs):
  900. """Deprecated: Use classmethod :meth:`CeleryCommand.register_command`
  901. instead."""
  902. _register = CeleryCommand.register_command
  903. return _register(args[0]) if args else _register
  904. if __name__ == '__main__': # pragma: no cover
  905. main()