camqadm.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381
  1. # -*- coding: utf-8 -*-
  2. """camqadm
  3. .. program:: camqadm
  4. """
  5. from __future__ import absolute_import
  6. import cmd
  7. import sys
  8. import shlex
  9. import pprint
  10. from itertools import count
  11. from amqplib import client_0_8 as amqp
  12. from celery.app import app_or_default
  13. from celery.utils import padlist
  14. from celery.bin.base import Command
  15. # Valid string -> bool coercions.
  16. BOOLS = {"1": True, "0": False,
  17. "on": True, "off": False,
  18. "yes": True, "no": False,
  19. "true": True, "False": False}
  20. # Map to coerce strings to other types.
  21. COERCE = {bool: lambda value: BOOLS[value.lower()]}
  22. HELP_HEADER = """
  23. Commands
  24. --------
  25. """.rstrip()
  26. EXAMPLE_TEXT = """
  27. Example:
  28. -> queue.delete myqueue yes no
  29. """
  30. def say(m):
  31. sys.stderr.write("%s\n" % (m, ))
  32. class Spec(object):
  33. """AMQP Command specification.
  34. Used to convert arguments to Python values and display various help
  35. and tooltips.
  36. :param args: see :attr:`args`.
  37. :keyword returns: see :attr:`returns`.
  38. .. attribute args::
  39. List of arguments this command takes. Should
  40. contain `(argument_name, argument_type)` tuples.
  41. .. attribute returns:
  42. Helpful human string representation of what this command returns.
  43. May be :const:`None`, to signify the return type is unknown.
  44. """
  45. def __init__(self, *args, **kwargs):
  46. self.args = args
  47. self.returns = kwargs.get("returns")
  48. def coerce(self, index, value):
  49. """Coerce value for argument at index.
  50. E.g. if :attr:`args` is `[("is_active", bool)]`:
  51. >>> coerce(0, "False")
  52. False
  53. """
  54. arg_info = self.args[index]
  55. arg_type = arg_info[1]
  56. # Might be a custom way to coerce the string value,
  57. # so look in the coercion map.
  58. return COERCE.get(arg_type, arg_type)(value)
  59. def str_args_to_python(self, arglist):
  60. """Process list of string arguments to values according to spec.
  61. e.g:
  62. >>> spec = Spec([("queue", str), ("if_unused", bool)])
  63. >>> spec.str_args_to_python("pobox", "true")
  64. ("pobox", True)
  65. """
  66. return tuple(self.coerce(index, value)
  67. for index, value in enumerate(arglist))
  68. def format_response(self, response):
  69. """Format the return value of this command in a human-friendly way."""
  70. if not self.returns:
  71. if response is None:
  72. return "ok."
  73. return response
  74. if callable(self.returns):
  75. return self.returns(response)
  76. return self.returns % (response, )
  77. def format_arg(self, name, type, default_value=None):
  78. if default_value is not None:
  79. return "%s:%s" % (name, default_value)
  80. return name
  81. def format_signature(self):
  82. return " ".join(self.format_arg(*padlist(list(arg), 3))
  83. for arg in self.args)
  84. def dump_message(message):
  85. if message is None:
  86. return "No messages in queue. basic.publish something."
  87. return {"body": message.body,
  88. "properties": message.properties,
  89. "delivery_info": message.delivery_info}
  90. def format_declare_queue(ret):
  91. return "ok. queue:%s messages:%s consumers:%s." % ret
  92. class AMQShell(cmd.Cmd):
  93. """AMQP API Shell.
  94. :keyword connect: Function used to connect to the server, must return
  95. connection object.
  96. :keyword silent: If :const:`True`, the commands won't have annoying
  97. output not relevant when running in non-shell mode.
  98. .. attribute: builtins
  99. Mapping of built-in command names -> method names
  100. .. attribute:: amqp
  101. Mapping of AMQP API commands and their :class:`Spec`.
  102. """
  103. conn = None
  104. chan = None
  105. prompt_fmt = "%d> "
  106. identchars = cmd.IDENTCHARS = "."
  107. needs_reconnect = False
  108. counter = 1
  109. inc_counter = count(2).next
  110. builtins = {"EOF": "do_exit",
  111. "exit": "do_exit",
  112. "help": "do_help"}
  113. amqp = {
  114. "exchange.declare": Spec(("exchange", str),
  115. ("type", str),
  116. ("passive", bool, "no"),
  117. ("durable", bool, "no"),
  118. ("auto_delete", bool, "no"),
  119. ("internal", bool, "no")),
  120. "exchange.delete": Spec(("exchange", str),
  121. ("if_unused", bool)),
  122. "queue.bind": Spec(("queue", str),
  123. ("exchange", str),
  124. ("routing_key", str)),
  125. "queue.declare": Spec(("queue", str),
  126. ("passive", bool, "no"),
  127. ("durable", bool, "no"),
  128. ("exclusive", bool, "no"),
  129. ("auto_delete", bool, "no"),
  130. returns=format_declare_queue),
  131. "queue.delete": Spec(("queue", str),
  132. ("if_unused", bool, "no"),
  133. ("if_empty", bool, "no"),
  134. returns="ok. %d messages deleted."),
  135. "queue.purge": Spec(("queue", str),
  136. returns="ok. %d messages deleted."),
  137. "basic.get": Spec(("queue", str),
  138. ("no_ack", bool, "off"),
  139. returns=dump_message),
  140. "basic.publish": Spec(("msg", amqp.Message),
  141. ("exchange", str),
  142. ("routing_key", str),
  143. ("mandatory", bool, "no"),
  144. ("immediate", bool, "no")),
  145. "basic.ack": Spec(("delivery_tag", int)),
  146. }
  147. def __init__(self, *args, **kwargs):
  148. self.connect = kwargs.pop("connect")
  149. self.silent = kwargs.pop("silent", False)
  150. cmd.Cmd.__init__(self, *args, **kwargs)
  151. self._reconnect()
  152. def say(self, m):
  153. """Say something to the user. Disabled if :attr:`silent`."""
  154. if not self.silent:
  155. say(m)
  156. def get_amqp_api_command(self, cmd, arglist):
  157. """With a command name and a list of arguments, convert the arguments
  158. to Python values and find the corresponding method on the AMQP channel
  159. object.
  160. :returns: tuple of `(method, processed_args)`.
  161. Example:
  162. >>> get_amqp_api_command("queue.delete", ["pobox", "yes", "no"])
  163. (<bound method Channel.queue_delete of
  164. <amqplib.client_0_8.channel.Channel object at 0x...>>,
  165. ('testfoo', True, False))
  166. """
  167. spec = self.amqp[cmd]
  168. args = spec.str_args_to_python(arglist)
  169. attr_name = cmd.replace(".", "_")
  170. if self.needs_reconnect:
  171. self._reconnect()
  172. return getattr(self.chan, attr_name), args, spec.format_response
  173. def do_exit(self, *args):
  174. """The `"exit"` command."""
  175. self.say("\n-> please, don't leave!")
  176. sys.exit(0)
  177. def display_command_help(self, cmd, short=False):
  178. spec = self.amqp[cmd]
  179. say("%s %s" % (cmd, spec.format_signature()))
  180. def do_help(self, *args):
  181. if not args:
  182. say(HELP_HEADER)
  183. for cmd_name in self.amqp.keys():
  184. self.display_command_help(cmd_name, short=True)
  185. say(EXAMPLE_TEXT)
  186. else:
  187. self.display_command_help(args[0])
  188. def default(self, line):
  189. say("unknown syntax: '%s'. how about some 'help'?" % line)
  190. def get_names(self):
  191. return set(self.builtins.keys() + self.amqp.keys())
  192. def completenames(self, text, *ignored):
  193. """Return all commands starting with `text`, for tab-completion."""
  194. names = self.get_names()
  195. first = [cmd for cmd in names
  196. if cmd.startswith(text.replace("_", "."))]
  197. if first:
  198. return first
  199. return [cmd for cmd in names
  200. if cmd.partition(".")[2].startswith(text)]
  201. def dispatch(self, cmd, argline):
  202. """Dispatch and execute the command.
  203. Lookup order is: :attr:`builtins` -> :attr:`amqp`.
  204. """
  205. arglist = shlex.split(argline)
  206. if cmd in self.builtins:
  207. return getattr(self, self.builtins[cmd])(*arglist)
  208. fun, args, formatter = self.get_amqp_api_command(cmd, arglist)
  209. return formatter(fun(*args))
  210. def parseline(self, line):
  211. """Parse input line.
  212. :returns: tuple of three items:
  213. `(command_name, arglist, original_line)`
  214. E.g::
  215. >>> parseline("queue.delete A 'B' C")
  216. ("queue.delete", "A 'B' C", "queue.delete A 'B' C")
  217. """
  218. parts = line.split()
  219. if parts:
  220. return parts[0], " ".join(parts[1:]), line
  221. return "", "", line
  222. def onecmd(self, line):
  223. """Parse line and execute command."""
  224. cmd, arg, line = self.parseline(line)
  225. if not line:
  226. return self.emptyline()
  227. if cmd is None:
  228. return self.default(line)
  229. self.lastcmd = line
  230. if cmd == '':
  231. return self.default(line)
  232. else:
  233. self.counter = self.inc_counter()
  234. try:
  235. self.respond(self.dispatch(cmd, arg))
  236. except (AttributeError, KeyError), exc:
  237. self.default(line)
  238. except Exception, exc:
  239. say(exc)
  240. self.needs_reconnect = True
  241. def respond(self, retval):
  242. """What to do with the return value of a command."""
  243. if retval is not None:
  244. if isinstance(retval, basestring):
  245. say(retval)
  246. else:
  247. pprint.pprint(retval)
  248. def _reconnect(self):
  249. """Re-establish connection to the AMQP server."""
  250. self.conn = self.connect(self.conn)
  251. self.chan = self.conn.channel()
  252. self.needs_reconnect = False
  253. @property
  254. def prompt(self):
  255. return self.prompt_fmt % self.counter
  256. class AMQPAdmin(object):
  257. """The celery :program:`camqadm` utility."""
  258. def __init__(self, *args, **kwargs):
  259. self.app = app_or_default(kwargs.get("app"))
  260. self.silent = bool(args)
  261. if "silent" in kwargs:
  262. self.silent = kwargs["silent"]
  263. self.args = args
  264. def connect(self, conn=None):
  265. if conn:
  266. conn.close()
  267. conn = self.app.broker_connection()
  268. self.say("-> connecting to %s." % conn.as_uri())
  269. conn.connect()
  270. self.say("-> connected.")
  271. return conn
  272. def run(self):
  273. shell = AMQShell(connect=self.connect)
  274. if self.args:
  275. return shell.onecmd(" ".join(self.args))
  276. try:
  277. return shell.cmdloop()
  278. except KeyboardInterrupt:
  279. self.say("(bibi)")
  280. pass
  281. def say(self, m):
  282. if not self.silent:
  283. say(m)
  284. class AMQPAdminCommand(Command):
  285. def run(self, *args, **options):
  286. options["app"] = self.app
  287. return AMQPAdmin(*args, **options).run()
  288. def camqadm(*args, **options):
  289. AMQPAdmin(*args, **options).run()
  290. def main():
  291. AMQPAdminCommand().execute_from_commandline()
  292. if __name__ == "__main__": # pragma: no cover
  293. main()