camqadm.py 11 KB

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