celeryctl.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350
  1. from __future__ import with_statement
  2. import sys
  3. from optparse import OptionParser, make_option as Option
  4. from pprint import pformat
  5. from textwrap import wrap
  6. from anyjson import deserialize
  7. from celery import __version__
  8. from celery.app import app_or_default, current_app
  9. from celery.bin.base import Command as CeleryCommand
  10. from celery.utils import term
  11. commands = {}
  12. class Error(Exception):
  13. pass
  14. def command(fun, name=None):
  15. commands[name or fun.__name__] = fun
  16. return fun
  17. class Command(object):
  18. help = ""
  19. args = ""
  20. version = __version__
  21. option_list = CeleryCommand.preload_options + (
  22. Option("--quiet", "-q", action="store_true", dest="quiet",
  23. default=False),
  24. Option("--no-color", "-C", dest="no_color", action="store_true",
  25. help="Don't colorize output."),
  26. )
  27. def __init__(self, app=None, no_color=False):
  28. self.app = app_or_default(app)
  29. self.colored = term.colored(enabled=not no_color)
  30. def __call__(self, *args, **kwargs):
  31. try:
  32. self.run(*args, **kwargs)
  33. except Error, exc:
  34. self.error(self.colored.red("Error: %s" % exc))
  35. def error(self, s):
  36. return self.out(s, fh=sys.stderr)
  37. def out(self, s, fh=sys.stdout):
  38. s = str(s)
  39. if not s.endswith("\n"):
  40. s += "\n"
  41. sys.stdout.write(s)
  42. def create_parser(self, prog_name, command):
  43. return OptionParser(prog=prog_name,
  44. usage=self.usage(command),
  45. version=self.version,
  46. option_list=self.option_list)
  47. def run_from_argv(self, prog_name, argv):
  48. self.prog_name = prog_name
  49. self.command = argv[0]
  50. self.arglist = argv[1:]
  51. self.parser = self.create_parser(self.prog_name, self.command)
  52. options, args = self.parser.parse_args(self.arglist)
  53. self.colored = term.colored(enabled=not options.no_color)
  54. self(*args, **options.__dict__)
  55. def run(self, *args, **kwargs):
  56. raise NotImplementedError()
  57. def usage(self, command):
  58. return "%%prog %s [options] %s" % (command, self.args)
  59. def prettify_list(self, n):
  60. c = self.colored
  61. if not n:
  62. return "- empty -"
  63. return "\n".join(str(c.reset(c.white("*"), " %s" % (item, )))
  64. for item in n)
  65. def prettify_dict_ok_error(self, n):
  66. c = self.colored
  67. if "ok" in n:
  68. return (c.green("OK"),
  69. indent(self.prettify(n["ok"])[1]))
  70. elif "error" in n:
  71. return (c.red("ERROR"),
  72. indent(self.prettify(n["error"])[1]))
  73. def prettify(self, n):
  74. OK = str(self.colored.green("OK"))
  75. if isinstance(n, list):
  76. return OK, self.prettify_list(n)
  77. if isinstance(n, dict):
  78. if "ok" in n or "error" in n:
  79. return self.prettify_dict_ok_error(n)
  80. if isinstance(n, basestring):
  81. return OK, unicode(n)
  82. return OK, pformat(n)
  83. class list_(Command):
  84. args = "<bindings>"
  85. def list_bindings(self, channel):
  86. fmt = lambda q, e, r: self.out("%s %s %s" % (q.ljust(28),
  87. e.ljust(28), r))
  88. fmt("Queue", "Exchange", "Routing Key")
  89. fmt("-" * 16, "-" * 16, "-" * 16)
  90. for binding in channel.list_bindings():
  91. fmt(*binding)
  92. def run(self, what, *_, **kw):
  93. topics = {"bindings": self.list_bindings}
  94. if what not in topics:
  95. raise ValueError("%r not in %r" % (what, topics.keys()))
  96. with self.app.broker_connection() as conn:
  97. self.app.amqp.get_task_consumer(conn).declare()
  98. with conn.channel() as channel:
  99. return topics[what](channel)
  100. list_ = command(list_, "list")
  101. class apply(Command):
  102. args = "<task_name>"
  103. option_list = Command.option_list + (
  104. Option("--args", "-a", dest="args"),
  105. Option("--kwargs", "-k", dest="kwargs"),
  106. Option("--eta", dest="eta"),
  107. Option("--countdown", dest="countdown", type="int"),
  108. Option("--expires", dest="expires"),
  109. Option("--serializer", dest="serializer", default="json"),
  110. Option("--queue", dest="queue"),
  111. Option("--exchange", dest="exchange"),
  112. Option("--routing-key", dest="routing_key"),
  113. )
  114. def run(self, name, *_, **kw):
  115. # Positional args.
  116. args = kw.get("args") or ()
  117. if isinstance(args, basestring):
  118. args = deserialize(args)
  119. # Keyword args.
  120. kwargs = kw.get("kwargs") or {}
  121. if isinstance(kwargs, basestring):
  122. kwargs = deserialize(kwargs)
  123. # Expires can be int.
  124. expires = kw.get("expires") or None
  125. try:
  126. expires = int(expires)
  127. except (TypeError, ValueError):
  128. pass
  129. res = self.app.send_task(name, args=args, kwargs=kwargs,
  130. countdown=kw.get("countdown"),
  131. serializer=kw.get("serializer"),
  132. queue=kw.get("queue"),
  133. exchange=kw.get("exchange"),
  134. routing_key=kw.get("routing_key"),
  135. eta=kw.get("eta"),
  136. expires=expires)
  137. self.out(res.task_id)
  138. apply = command(apply)
  139. def pluralize(n, text, suffix='s'):
  140. if n > 1:
  141. return text + suffix
  142. return text
  143. class purge(Command):
  144. def run(self, *args, **kwargs):
  145. app = current_app()
  146. queues = len(app.amqp.queues.keys())
  147. messages_removed = app.control.discard_all()
  148. if messages_removed:
  149. self.out("Purged %s %s from %s known task %s." % (
  150. messages_removed, pluralize(messages_removed, "message"),
  151. queues, pluralize(queues, "queue")))
  152. else:
  153. self.out("No messages purged from %s known %s" % (
  154. queues, pluralize(queues, "queue")))
  155. purge = command(purge)
  156. class result(Command):
  157. args = "<task_id>"
  158. option_list = Command.option_list + (
  159. Option("--task", "-t", dest="task"),
  160. )
  161. def run(self, task_id, *args, **kwargs):
  162. from celery import registry
  163. result_cls = self.app.AsyncResult
  164. task = kwargs.get("task")
  165. if task:
  166. result_cls = registry.tasks[task].AsyncResult
  167. result = result_cls(task_id)
  168. self.out(self.prettify(result.get())[1])
  169. result = command(result)
  170. class inspect(Command):
  171. choices = {"active": 1.0,
  172. "active_queues": 1.0,
  173. "scheduled": 1.0,
  174. "reserved": 1.0,
  175. "stats": 1.0,
  176. "revoked": 1.0,
  177. "registered_tasks": 1.0,
  178. "enable_events": 1.0,
  179. "disable_events": 1.0,
  180. "ping": 0.2,
  181. "add_consumer": 1.0,
  182. "cancel_consumer": 1.0}
  183. option_list = Command.option_list + (
  184. Option("--timeout", "-t", type="float", dest="timeout",
  185. default=None,
  186. help="Timeout in seconds (float) waiting for reply"),
  187. Option("--destination", "-d", dest="destination",
  188. help="Comma separated list of destination node names."))
  189. def usage(self, command):
  190. return "%%prog %s [options] %s [%s]" % (
  191. command, self.args, "|".join(self.choices.keys()))
  192. def run(self, *args, **kwargs):
  193. self.quiet = kwargs.get("quiet", False)
  194. if not args:
  195. raise Error("Missing inspect command. See --help")
  196. command = args[0]
  197. if command == "help":
  198. raise Error("Did you mean 'inspect --help'?")
  199. if command not in self.choices:
  200. raise Error("Unknown inspect command: %s" % command)
  201. destination = kwargs.get("destination")
  202. timeout = kwargs.get("timeout") or self.choices[command]
  203. if destination and isinstance(destination, basestring):
  204. destination = map(str.strip, destination.split(","))
  205. def on_reply(body):
  206. c = self.colored
  207. node = body.keys()[0]
  208. reply = body[node]
  209. status, preply = self.prettify(reply)
  210. self.say("->", c.cyan(node, ": ") + status, indent(preply))
  211. self.say("<-", command)
  212. i = self.app.control.inspect(destination=destination,
  213. timeout=timeout,
  214. callback=on_reply)
  215. replies = getattr(i, command)(*args[1:])
  216. if not replies:
  217. raise Error("No nodes replied within time constraint.")
  218. return replies
  219. def say(self, direction, title, body=""):
  220. c = self.colored
  221. if direction == "<-" and self.quiet:
  222. return
  223. dirstr = not self.quiet and c.bold(c.white(direction), " ") or ""
  224. self.out(c.reset(dirstr, title))
  225. if body and not self.quiet:
  226. self.out(body)
  227. inspect = command(inspect)
  228. def indent(s, n=4):
  229. i = [" " * n + l for l in s.split("\n")]
  230. return "\n".join("\n".join(wrap(j)) for j in i)
  231. class status(Command):
  232. option_list = inspect.option_list
  233. def run(self, *args, **kwargs):
  234. replies = inspect(app=self.app,
  235. no_color=kwargs.get("no_color", False)) \
  236. .run("ping", **dict(kwargs, quiet=True))
  237. if not replies:
  238. raise Error("No nodes replied within time constraint")
  239. nodecount = len(replies)
  240. if not kwargs.get("quiet", False):
  241. self.out("\n%s %s online." % (nodecount,
  242. nodecount > 1 and "nodes" or "node"))
  243. status = command(status)
  244. class help(Command):
  245. def usage(self, command):
  246. return "%%prog <command> [options] %s" % (self.args, )
  247. def run(self, *args, **kwargs):
  248. self.parser.print_help()
  249. usage = ["",
  250. "Type '%s <command> --help' for help on a "
  251. "specific command." % (self.prog_name, ),
  252. "",
  253. "Available commands:"]
  254. for command in list(sorted(commands.keys())):
  255. usage.append(" %s" % command)
  256. self.out("\n".join(usage))
  257. help = command(help)
  258. class celeryctl(CeleryCommand):
  259. commands = commands
  260. def execute(self, command, argv=None):
  261. try:
  262. cls = self.commands[command]
  263. except KeyError:
  264. cls, argv = self.commands["help"], ["help"]
  265. cls = self.commands.get(command) or self.commands["help"]
  266. try:
  267. cls(app=self.app).run_from_argv(self.prog_name, argv)
  268. except Error:
  269. return self.execute("help", argv)
  270. def handle_argv(self, prog_name, argv):
  271. self.prog_name = prog_name
  272. try:
  273. command = argv[0]
  274. except IndexError:
  275. command, argv = "help", ["help"]
  276. return self.execute(command, argv)
  277. def main():
  278. try:
  279. celeryctl().execute_from_commandline()
  280. except KeyboardInterrupt:
  281. pass
  282. if __name__ == "__main__": # pragma: no cover
  283. main()