celery.py 36 KB

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