Advertisement
AshrafHassan

Rabbit Curl After - 07/11/2015

Nov 8th, 2015
270
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Bash 32.99 KB | None | 0 0
  1. [stack@rdo01 ~]$ sudo vi /etc/hosts
  2. [stack@rdo01 ~]$ curl -k --noproxy localhost --retry 30 --retry-delay 6 -f -L http://guest:guest@localhost:15672/cli/rabbitmqadmin
  3. #!/usr/bin/env python
  4.  
  5. #   The contents of this file are subject to the Mozilla Public License
  6. #   Version 1.1 (the "License"); you may not use this file except in
  7. #   compliance with the License. You may obtain a copy of the License at
  8. #   http://www.mozilla.org/MPL/
  9. #
  10. #   Software distributed under the License is distributed on an "AS IS"
  11. #   basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the
  12. #   License for the specific language governing rights and limitations
  13. #   under the License.
  14. #
  15. #   The Original Code is RabbitMQ Management Plugin.
  16. #
  17. #   The Initial Developer of the Original Code is GoPivotal, Inc.
  18. #   Copyright (c) 2010-2014 GoPivotal, Inc.  All rights reserved.
  19.  
  20. import sys
  21. if sys.version_info[0] < 2 or sys.version_info[1] < 6:
  22.     print "Sorry, rabbitmqadmin requires at least Python 2.6."
  23.     sys.exit(1)
  24.  
  25. from ConfigParser import ConfigParser, NoSectionError
  26. from optparse import OptionParser, TitledHelpFormatter
  27. import httplib
  28. import urllib
  29. import urlparse
  30. import base64
  31. import json
  32. import os
  33. import socket
  34.  
  35. VERSION = '3.3.5'
  36.  
  37. LISTABLE = {'connections': {'vhost': False},
  38.             'channels':    {'vhost': False},
  39.             'exchanges':   {'vhost': True},
  40.             'queues':      {'vhost': True},
  41.             'bindings':    {'vhost': True},
  42.             'users':       {'vhost': False},
  43.             'vhosts':      {'vhost': False},
  44.             'permissions': {'vhost': False},
  45.             'nodes':       {'vhost': False},
  46.             'parameters':  {'vhost': False,
  47.                             'json':  ['value']},
  48.             'policies':    {'vhost': False,
  49.                             'json':  ['definition']}}
  50.  
  51. SHOWABLE = {'overview': {'vhost': False}}
  52.  
  53. PROMOTE_COLUMNS = ['vhost', 'name', 'type',
  54.                    'source', 'destination', 'destination_type', 'routing_key']
  55.  
  56. URIS = {
  57.     'exchange':   '/exchanges/{vhost}/{name}',
  58.     'queue':      '/queues/{vhost}/{name}',
  59.     'binding':    '/bindings/{vhost}/e/{source}/{destination_char}/{destination}',
  60.     'binding_del':'/bindings/{vhost}/e/{source}/{destination_char}/{destination}/{properties_key}',
  61.     'vhost':      '/vhosts/{name}',
  62.     'user':       '/users/{name}',
  63.     'permission': '/permissions/{vhost}/{user}',
  64.     'parameter':  '/parameters/{component}/{vhost}/{name}',
  65.     'policy':     '/policies/{vhost}/{name}'
  66.     }
  67.  
  68. DECLARABLE = {
  69.     'exchange':   {'mandatory': ['name', 'type'],
  70.                    'json':      ['arguments'],
  71.                    'optional':  {'auto_delete': 'false', 'durable': 'true',
  72.                                  'internal': 'false', 'arguments': {}}},
  73.     'queue':      {'mandatory': ['name'],
  74.                    'json':      ['arguments'],
  75.                    'optional':  {'auto_delete': 'false', 'durable': 'true',
  76.                                  'arguments': {}, 'node': None}},
  77.     'binding':    {'mandatory': ['source', 'destination'],
  78.                    'json':      ['arguments'],
  79.                    'optional':  {'destination_type': 'queue',
  80.                                  'routing_key': '', 'arguments': {}}},
  81.     'vhost':      {'mandatory': ['name'],
  82.                    'optional':  {'tracing': None}},
  83.     'user':       {'mandatory': ['name', 'password', 'tags'],
  84.                    'optional':  {}},
  85.     'permission': {'mandatory': ['vhost', 'user', 'configure', 'write', 'read'],
  86.                    'optional':  {}},
  87.     'parameter':  {'mandatory': ['component', 'name', 'value'],
  88.                    'json':      ['value'],
  89.                    'optional':  {}},
  90.     # Priority is 'json' to convert to int
  91.     'policy':     {'mandatory': ['name', 'pattern', 'definition'],
  92.                    'json':      ['definition', 'priority'],
  93.                    'optional':  {'priority' : 0, 'apply-to': None}}
  94.     }
  95.  
  96. DELETABLE = {
  97.     'exchange':   {'mandatory': ['name']},
  98.     'queue':      {'mandatory': ['name']},
  99.     'binding':    {'mandatory': ['source', 'destination_type', 'destination',
  100.                                  'properties_key']},
  101.     'vhost':      {'mandatory': ['name']},
  102.     'user':       {'mandatory': ['name']},
  103.     'permission': {'mandatory': ['vhost', 'user']},
  104.     'parameter':  {'mandatory': ['component', 'name']},
  105.     'policy':     {'mandatory': ['name']}
  106.     }
  107.  
  108. CLOSABLE = {
  109.     'connection': {'mandatory': ['name'],
  110.                    'optional':  {},
  111.                    'uri':       '/connections/{name}'}
  112.     }
  113.  
  114. PURGABLE = {
  115.     'queue': {'mandatory': ['name'],
  116.               'optional':  {},
  117.               'uri':       '/queues/{vhost}/{name}/contents'}
  118.     }
  119.  
  120. EXTRA_VERBS = {
  121.     'publish': {'mandatory': ['routing_key'],
  122.                 'optional':  {'payload': None,
  123.                               'exchange': 'amq.default',
  124.                               'payload_encoding': 'string'},
  125.                 'uri':       '/exchanges/{vhost}/{exchange}/publish'},
  126.     'get':     {'mandatory': ['queue'],
  127.                 'optional':  {'count': '1', 'requeue': 'true',
  128.                               'payload_file': None, 'encoding': 'auto'},
  129.                 'uri':       '/queues/{vhost}/{queue}/get'}
  130. }
  131.  
  132. for k in DECLARABLE:
  133.     DECLARABLE[k]['uri'] = URIS[k]
  134.  
  135. for k in DELETABLE:
  136.     DELETABLE[k]['uri'] = URIS[k]
  137.     DELETABLE[k]['optional'] = {}
  138. DELETABLE['binding']['uri'] = URIS['binding_del']
  139.  
  140. def short_usage():
  141.     return "rabbitmqadmin [options] subcommand"
  142.  
  143. def title(name):
  144.     return "\n%s\n%s\n\n" % (name, '=' * len(name))
  145.  
  146. def subcommands_usage():
  147.     usage = """Usage
  148. =====
  149.  """ + short_usage() + """
  150.  
  151.  where subcommand is one of:
  152. """ + title("Display")
  153.  
  154.     for l in LISTABLE:
  155.         usage += "  list {0} [<column>...]\n".format(l)
  156.     for s in SHOWABLE:
  157.         usage += "  show {0} [<column>...]\n".format(s)
  158.     usage += title("Object Manipulation")
  159.     usage += fmt_usage_stanza(DECLARABLE,  'declare')
  160.     usage += fmt_usage_stanza(DELETABLE,   'delete')
  161.     usage += fmt_usage_stanza(CLOSABLE,    'close')
  162.     usage += fmt_usage_stanza(PURGABLE,    'purge')
  163.     usage += title("Broker Definitions")
  164.     usage += """  export <file>
  165.  import <file>
  166. """
  167.     usage += title("Publishing and Consuming")
  168.     usage += fmt_usage_stanza(EXTRA_VERBS, '')
  169.     usage += """
  170.  * If payload is not specified on publish, standard input is used
  171.  
  172.  * If payload_file is not specified on get, the payload will be shown on
  173.    standard output along with the message metadata
  174.  
  175.  * If payload_file is specified on get, count must not be set
  176. """
  177.     return usage
  178.  
  179. def config_usage():
  180.     usage = "Usage\n=====\n" + short_usage()
  181.     usage += "\n" + title("Configuration File")
  182.     usage += """  It is possible to specify a configuration file from the command line.
  183.  Hosts can be configured easily in a configuration file and called
  184.  from the command line.
  185. """
  186.     usage += title("Example")
  187.     usage += """  # rabbitmqadmin.conf.example START
  188.  
  189.  [host_normal]
  190.  hostname = localhost
  191.  port = 15672
  192.  username = guest
  193.  password = guest
  194.  declare_vhost = / # Used as default for declare / delete only
  195.  vhost = /         # Used as default for declare / delete / list
  196.  
  197.  [host_ssl]
  198.  hostname = otherhost
  199.  port = 15672
  200.  username = guest
  201.  password = guest
  202.  ssl = True
  203.  ssl_key_file = /path/to/key.pem
  204.  ssl_cert_file = /path/to/cert.pem
  205.  
  206.  # rabbitmqadmin.conf.example END
  207. """
  208.     usage += title("Use")
  209.     usage += """  rabbitmqadmin -c rabbitmqadmin.conf.example -N host_normal ..."""
  210.     return usage
  211.  
  212. def more_help():
  213.     return """
  214. More Help
  215. =========
  216.  
  217. For more help use the help subcommand:
  218.  
  219.  rabbitmqadmin help subcommands  # For a list of available subcommands
  220.  rabbitmqadmin help config       # For help with the configuration file
  221. """
  222.  
  223. def fmt_usage_stanza(root, verb):
  224.     def fmt_args(args):
  225.         res = " ".join(["{0}=...".format(a) for a in args['mandatory']])
  226.         opts = " ".join("{0}=...".format(o) for o in args['optional'].keys())
  227.         if opts != "":
  228.             res += " [{0}]".format(opts)
  229.         return res
  230.  
  231.     text = ""
  232.     if verb != "":
  233.         verb = " " + verb
  234.     for k in root.keys():
  235.         text += " {0} {1} {2}\n".format(verb, k, fmt_args(root[k]))
  236.     return text
  237.  
  238. default_options = { "hostname"        : "localhost",
  239.                     "port"            : "15672",
  240.                     "declare_vhost"   : "/",
  241.                     "username"        : "guest",
  242.                     "password"        : "guest",
  243.                     "ssl"             : False,
  244.                     "verbose"         : True,
  245.                     "format"          : "table",
  246.                     "depth"           : 1,
  247.                     "bash_completion" : False }
  248.  
  249.  
  250. class MyFormatter(TitledHelpFormatter):
  251.     def format_epilog(self, epilog):
  252.         return epilog
  253.  
  254. parser = OptionParser(usage=short_usage(),
  255.                       formatter=MyFormatter(),
  256.                       epilog=more_help())
  257.  
  258. def make_parser():
  259.     def add(*args, **kwargs):
  260.         key = kwargs['dest']
  261.         if key in default_options:
  262.             default = " [default: %s]" % default_options[key]
  263.             kwargs['help'] = kwargs['help'] + default
  264.         parser.add_option(*args, **kwargs)
  265.  
  266.     add("-c", "--config", dest="config",
  267.         help="configuration file [default: ~/.rabbitmqadmin.conf]",
  268.         metavar="CONFIG")
  269.     add("-N", "--node", dest="node",
  270.         help="node described in the configuration file [default: 'default'" + \
  271.              " only if configuration file is specified]",
  272.         metavar="NODE")
  273.     add("-H", "--host", dest="hostname",
  274.         help="connect to host HOST" ,
  275.         metavar="HOST")
  276.     add("-P", "--port", dest="port",
  277.         help="connect to port PORT",
  278.         metavar="PORT")
  279.     add("-V", "--vhost", dest="vhost",
  280.         help="connect to vhost VHOST [default: all vhosts for list, '/' for declare]",
  281.         metavar="VHOST")
  282.     add("-u", "--username", dest="username",
  283.         help="connect using username USERNAME",
  284.         metavar="USERNAME")
  285.     add("-p", "--password", dest="password",
  286.         help="connect using password PASSWORD",
  287.         metavar="PASSWORD")
  288.     add("-q", "--quiet", action="store_false", dest="verbose",
  289.         help="suppress status messages")
  290.     add("-s", "--ssl", action="store_true", dest="ssl",
  291.         help="connect with ssl")
  292.     add("--ssl-key-file", dest="ssl_key_file",
  293.         help="PEM format key file for SSL")
  294.     add("--ssl-cert-file", dest="ssl_cert_file",
  295.         help="PEM format certificate file for SSL")
  296.     add("-f", "--format", dest="format",
  297.         help="format for listing commands - one of [" + ", ".join(FORMATS.keys())  + "]")
  298.     add("-S", "--sort", dest="sort", help="sort key for listing queries")
  299.     add("-R", "--sort-reverse", action="store_true", dest="sort_reverse",
  300.         help="reverse the sort order")
  301.     add("-d", "--depth", dest="depth",
  302.         help="maximum depth to recurse for listing tables")
  303.     add("--bash-completion", action="store_true",
  304.         dest="bash_completion",
  305.         help="Print bash completion script")
  306.     add("--version", action="store_true",
  307.         dest="version",
  308.         help="Display version and exit")
  309.  
  310. def default_config():
  311.     home = os.getenv('USERPROFILE') or os.getenv('HOME')
  312.     if home is not None:
  313.         config_file = home + os.sep + ".rabbitmqadmin.conf"
  314.         if os.path.isfile(config_file):
  315.             return config_file
  316.     return None
  317.  
  318. def make_configuration():
  319.     make_parser()
  320.     (options, args) = parser.parse_args()
  321.     setattr(options, "declare_vhost", None)
  322.     if options.version:
  323.         print_version()
  324.     if options.config is None:
  325.         config_file = default_config()
  326.         if config_file is not None:
  327.             setattr(options, "config", config_file)
  328.     else:
  329.         if not os.path.isfile(options.config):
  330.             assert_usage(False,
  331.                 "Could not read config file '%s'" % options.config)
  332.  
  333.     if options.node is None and options.config:
  334.         options.node = "default"
  335.     else:
  336.         options.node = options.node
  337.     for (key, val) in default_options.items():
  338.         if getattr(options, key) is None:
  339.             setattr(options, key, val)
  340.  
  341.     if options.config is not None:
  342.         config = ConfigParser()
  343.         try:
  344.             config.read(options.config)
  345.             new_conf = dict(config.items(options.node))
  346.         except NoSectionError, error:
  347.             if options.node == "default":
  348.                 pass
  349.             else:
  350.                 assert_usage(False, ("Could not read section '%s' in config file"  +
  351.                              " '%s':\n   %s") %
  352.                              (options.node, options.config, error))
  353.         else:
  354.             for key, val in new_conf.items():
  355.                 setattr(options, key, val)
  356.  
  357.     return (options, args)
  358.  
  359. def assert_usage(expr, error):
  360.     if not expr:
  361.         output("\nERROR: {0}\n".format(error))
  362.         output("{0} --help for help\n".format(os.path.basename(sys.argv[0])))
  363.         sys.exit(1)
  364.  
  365. def print_version():
  366.     output("rabbitmqadmin {0}".format(VERSION))
  367.     sys.exit(0)
  368.  
  369. def column_sort_key(col):
  370.     if col in PROMOTE_COLUMNS:
  371.         return (1, PROMOTE_COLUMNS.index(col))
  372.     else:
  373.         return (2, col)
  374.  
  375. def main():
  376.     (options, args) = make_configuration()
  377.     if options.bash_completion:
  378.         print_bash_completion()
  379.         exit(0)
  380.     assert_usage(len(args) > 0, 'Action not specified')
  381.     mgmt = Management(options, args[1:])
  382.     mode = "invoke_" + args[0]
  383.     assert_usage(hasattr(mgmt, mode),
  384.                  'Action {0} not understood'.format(args[0]))
  385.     method = getattr(mgmt, "invoke_%s" % args[0])
  386.     method()
  387.  
  388. def output(s):
  389.     print maybe_utf8(s, sys.stdout)
  390.  
  391. def die(s):
  392.     sys.stderr.write(maybe_utf8("*** {0}\n".format(s), sys.stderr))
  393.     exit(1)
  394.  
  395. def maybe_utf8(s, stream):
  396.     if stream.isatty():
  397.         # It will have an encoding, which Python will respect
  398.         return s
  399.     else:
  400.         # It won't have an encoding, and Python will pick ASCII by default
  401.         return s.encode('utf-8')
  402.  
  403. class Management:
  404.     def __init__(self, options, args):
  405.         self.options = options
  406.         self.args = args
  407.  
  408.     def get(self, path):
  409.         return self.http("GET", "/api%s" % path, "")
  410.  
  411.     def put(self, path, body):
  412.         return self.http("PUT", "/api%s" % path, body)
  413.  
  414.     def post(self, path, body):
  415.         return self.http("POST", "/api%s" % path, body)
  416.  
  417.     def delete(self, path):
  418.         return self.http("DELETE", "/api%s" % path, "")
  419.  
  420.     def http(self, method, path, body):
  421.         if self.options.ssl:
  422.             conn = httplib.HTTPSConnection(self.options.hostname,
  423.                                            self.options.port,
  424.                                            self.options.ssl_key_file,
  425.                                            self.options.ssl_cert_file)
  426.         else:
  427.             conn = httplib.HTTPConnection(self.options.hostname,
  428.                                           self.options.port)
  429.         headers = {"Authorization":
  430.                        "Basic " + base64.b64encode(self.options.username + ":" +
  431.                                                    self.options.password)}
  432.         if body != "":
  433.             headers["Content-Type"] = "application/json"
  434.         try:
  435.             conn.request(method, path, body, headers)
  436.         except socket.error, e:
  437.             die("Could not connect: {0}".format(e))
  438.         resp = conn.getresponse()
  439.         if resp.status == 400:
  440.             die(json.loads(resp.read())['reason'])
  441.         if resp.status == 401:
  442.             die("Access refused: {0}".format(path))
  443.         if resp.status == 404:
  444.             die("Not found: {0}".format(path))
  445.         if resp.status == 301:
  446.             url = urlparse.urlparse(resp.getheader('location'))
  447.             [host, port] = url.netloc.split(':')
  448.             self.options.hostname = host
  449.             self.options.port = int(port)
  450.             return self.http(method, url.path + '?' + url.query, body)
  451.         if resp.status < 200 or resp.status > 400:
  452.             raise Exception("Received %d %s for path %s\n%s"
  453.                             % (resp.status, resp.reason, path, resp.read()))
  454.         return resp.read()
  455.  
  456.     def verbose(self, string):
  457.         if self.options.verbose:
  458.             output(string)
  459.  
  460.     def get_arg(self):
  461.         assert_usage(len(self.args) == 1, 'Exactly one argument required')
  462.         return self.args[0]
  463.  
  464.     def invoke_help(self):
  465.         if len(self.args) == 0:
  466.             parser.print_help()
  467.         else:
  468.             help_cmd = self.get_arg()
  469.             if help_cmd == 'subcommands':
  470.                 usage = subcommands_usage()
  471.             elif help_cmd == 'config':
  472.                 usage = config_usage()
  473.             else:
  474.                 assert_usage(False, """help topic must be one of:
  475.  subcommands
  476.  config""")
  477.             print usage
  478.         exit(0)
  479.  
  480.     def invoke_publish(self):
  481.         (uri, upload) = self.parse_args(self.args, EXTRA_VERBS['publish'])
  482.         upload['properties'] = {} # TODO do we care here?
  483.         if not 'payload' in upload:
  484.             data = sys.stdin.read()
  485.             upload['payload'] = base64.b64encode(data)
  486.             upload['payload_encoding'] = 'base64'
  487.         resp = json.loads(self.post(uri, json.dumps(upload)))
  488.         if resp['routed']:
  489.             self.verbose("Message published")
  490.         else:
  491.             self.verbose("Message published but NOT routed")
  492.  
  493.     def invoke_get(self):
  494.         (uri, upload) = self.parse_args(self.args, EXTRA_VERBS['get'])
  495.         payload_file = 'payload_file' in upload and upload['payload_file'] or None
  496.         assert_usage(not payload_file or upload['count'] == '1',
  497.                      'Cannot get multiple messages using payload_file')
  498.         result = self.post(uri, json.dumps(upload))
  499.         if payload_file:
  500.             write_payload_file(payload_file, result)
  501.             columns = ['routing_key', 'exchange', 'message_count',
  502.                        'payload_bytes', 'redelivered']
  503.             format_list(result, columns, {}, self.options)
  504.         else:
  505.             format_list(result, [], {}, self.options)
  506.  
  507.     def invoke_export(self):
  508.         path = self.get_arg()
  509.         definitions = self.get("/definitions")
  510.         f = open(path, 'w')
  511.         f.write(definitions)
  512.         f.close()
  513.         self.verbose("Exported definitions for %s to \"%s\""
  514.                      % (self.options.hostname, path))
  515.  
  516.     def invoke_import(self):
  517.         path = self.get_arg()
  518.         f = open(path, 'r')
  519.         definitions = f.read()
  520.         f.close()
  521.         self.post("/definitions", definitions)
  522.         self.verbose("Imported definitions for %s from \"%s\""
  523.                      % (self.options.hostname, path))
  524.  
  525.     def invoke_list(self):
  526.         cols = self.args[1:]
  527.         (uri, obj_info) = self.list_show_uri(LISTABLE, 'list', cols)
  528.         format_list(self.get(uri), cols, obj_info, self.options)
  529.  
  530.     def invoke_show(self):
  531.         cols = self.args[1:]
  532.         (uri, obj_info) = self.list_show_uri(SHOWABLE, 'show', cols)
  533.         format_list('[{0}]'.format(self.get(uri)), cols, obj_info, self.options)
  534.  
  535.     def list_show_uri(self, obj_types, verb, cols):
  536.         obj_type = self.args[0]
  537.         assert_usage(obj_type in obj_types,
  538.                      "Don't know how to {0} {1}".format(verb, obj_type))
  539.         obj_info = obj_types[obj_type]
  540.         uri = "/%s" % obj_type
  541.         query = []
  542.         if obj_info['vhost'] and self.options.vhost:
  543.             uri += "/%s" % urllib.quote_plus(self.options.vhost)
  544.         if cols != []:
  545.             query.append("columns=" + ",".join(cols))
  546.         sort = self.options.sort
  547.         if sort:
  548.             query.append("sort=" + sort)
  549.         if self.options.sort_reverse:
  550.             query.append("sort_reverse=true")
  551.         query = "&".join(query)
  552.         if query != "":
  553.             uri += "?" + query
  554.         return (uri, obj_info)
  555.  
  556.     def invoke_declare(self):
  557.         (obj_type, uri, upload) = self.declare_delete_parse(DECLARABLE)
  558.         if obj_type == 'binding':
  559.             self.post(uri, json.dumps(upload))
  560.         else:
  561.             self.put(uri, json.dumps(upload))
  562.         self.verbose("{0} declared".format(obj_type))
  563.  
  564.     def invoke_delete(self):
  565.         (obj_type, uri, upload) = self.declare_delete_parse(DELETABLE)
  566.         self.delete(uri)
  567.         self.verbose("{0} deleted".format(obj_type))
  568.  
  569.     def invoke_close(self):
  570.         (obj_type, uri, upload) = self.declare_delete_parse(CLOSABLE)
  571.         self.delete(uri)
  572.         self.verbose("{0} closed".format(obj_type))
  573.  
  574.     def invoke_purge(self):
  575.         (obj_type, uri, upload) = self.declare_delete_parse(PURGABLE)
  576.         self.delete(uri)
  577.         self.verbose("{0} purged".format(obj_type))
  578.  
  579.     def declare_delete_parse(self, root):
  580.         assert_usage(len(self.args) > 0, 'Type not specified')
  581.         obj_type = self.args[0]
  582.         assert_usage(obj_type in root,
  583.                      'Type {0} not recognised'.format(obj_type))
  584.         obj = root[obj_type]
  585.         (uri, upload) = self.parse_args(self.args[1:], obj)
  586.         return (obj_type, uri, upload)
  587.  
  588.     def parse_args(self, args, obj):
  589.         mandatory =  obj['mandatory']
  590.         optional = obj['optional']
  591.         uri_template = obj['uri']
  592.         upload = {}
  593.         for k in optional.keys():
  594.             if optional[k]:
  595.                 upload[k] = optional[k]
  596.         for arg in args:
  597.             assert_usage("=" in arg,
  598.                          'Argument "{0}" not in format name=value'.format(arg))
  599.             (name, value) = arg.split("=", 1)
  600.             assert_usage(name in mandatory or name in optional.keys(),
  601.                          'Argument "{0}" not recognised'.format(name))
  602.             if 'json' in obj and name in obj['json']:
  603.                 upload[name] = self.parse_json(value)
  604.             else:
  605.                 upload[name] = value
  606.         for m in mandatory:
  607.             assert_usage(m in upload.keys(),
  608.                          'mandatory argument "{0}" required'.format(m))
  609.         if 'vhost' not in mandatory:
  610.             upload['vhost'] = self.options.vhost or self.options.declare_vhost
  611.         uri_args = {}
  612.         for k in upload:
  613.             v = upload[k]
  614.             if v and isinstance(v, basestring):
  615.                 uri_args[k] = urllib.quote_plus(v)
  616.                 if k == 'destination_type':
  617.                     uri_args['destination_char'] = v[0]
  618.         uri = uri_template.format(**uri_args)
  619.         return (uri, upload)
  620.  
  621.     def parse_json(self, text):
  622.         try:
  623.             return json.loads(text)
  624.         except ValueError:
  625.             print "Could not parse JSON:\n  {0}".format(text)
  626.             sys.exit(1)
  627.  
  628. def format_list(json_list, columns, args, options):
  629.     format = options.format
  630.     formatter = None
  631.     if format == "raw_json":
  632.         output(json_list)
  633.         return
  634.     elif format == "pretty_json":
  635.         enc = json.JSONEncoder(False, False, True, True, True, 2)
  636.         output(enc.encode(json.loads(json_list)))
  637.         return
  638.     else:
  639.         formatter = FORMATS[format]
  640.     assert_usage(formatter != None,
  641.                  "Format {0} not recognised".format(format))
  642.     formatter_instance = formatter(columns, args, options)
  643.     formatter_instance.display(json_list)
  644.  
  645. class Lister:
  646.     def verbose(self, string):
  647.         if self.options.verbose:
  648.             output(string)
  649.  
  650.     def display(self, json_list):
  651.         depth = sys.maxint
  652.         if len(self.columns) == 0:
  653.             depth = int(self.options.depth)
  654.         (columns, table) = self.list_to_table(json.loads(json_list), depth)
  655.         if len(table) > 0:
  656.             self.display_list(columns, table)
  657.         else:
  658.             self.verbose("No items")
  659.  
  660.     def list_to_table(self, items, max_depth):
  661.         columns = {}
  662.         column_ix = {}
  663.         row = None
  664.         table = []
  665.  
  666.         def add(prefix, depth, item, fun):
  667.             for key in item:
  668.                 column = prefix == '' and key or (prefix + '.' + key)
  669.                 subitem = item[key]
  670.                 if type(subitem) == dict:
  671.                     if self.obj_info.has_key('json') and key in self.obj_info['json']:
  672.                         fun(column, json.dumps(subitem))
  673.                     else:
  674.                         if depth < max_depth:
  675.                             add(column, depth + 1, subitem, fun)
  676.                 elif type(subitem) == list:
  677.                     # The first branch has slave nodes in queues in
  678.                     # mind (which come out looking decent); the second
  679.                     # one has applications in nodes (which look less
  680.                     # so, but what would look good?).
  681.                     if [x for x in subitem if type(x) != unicode] == []:
  682.                         serialised = " ".join(subitem)
  683.                     else:
  684.                         serialised = json.dumps(subitem)
  685.                     fun(column, serialised)
  686.                 else:
  687.                     fun(column, subitem)
  688.  
  689.         def add_to_columns(col, val):
  690.             columns[col] = True
  691.  
  692.         def add_to_row(col, val):
  693.             if col in column_ix:
  694.                 row[column_ix[col]] = unicode(val)
  695.  
  696.         if len(self.columns) == 0:
  697.             for item in items:
  698.                 add('', 1, item, add_to_columns)
  699.             columns = columns.keys()
  700.             columns.sort(key=column_sort_key)
  701.         else:
  702.             columns = self.columns
  703.  
  704.         for i in xrange(0, len(columns)):
  705.             column_ix[columns[i]] = i
  706.         for item in items:
  707.             row = len(columns) * ['']
  708.             add('', 1, item, add_to_row)
  709.             table.append(row)
  710.  
  711.         return (columns, table)
  712.  
  713. class TSVList(Lister):
  714.     def __init__(self, columns, obj_info, options):
  715.         self.columns = columns
  716.         self.obj_info = obj_info
  717.         self.options = options
  718.  
  719.     def display_list(self, columns, table):
  720.         head = "\t".join(columns)
  721.         self.verbose(head)
  722.  
  723.         for row in table:
  724.             line = "\t".join(row)
  725.             output(line)
  726.  
  727. class LongList(Lister):
  728.     def __init__(self, columns, obj_info, options):
  729.         self.columns = columns
  730.         self.obj_info = obj_info
  731.         self.options = options
  732.  
  733.     def display_list(self, columns, table):
  734.         sep = "\n" + "-" * 80 + "\n"
  735.         max_width = 0
  736.         for col in columns:
  737.             max_width = max(max_width, len(col))
  738.         fmt = "{0:>" + unicode(max_width) + "}: {1}"
  739.         output(sep)
  740.         for i in xrange(0, len(table)):
  741.             for j in xrange(0, len(columns)):
  742.                 output(fmt.format(columns[j], table[i][j]))
  743.             output(sep)
  744.  
  745. class TableList(Lister):
  746.     def __init__(self, columns, obj_info, options):
  747.         self.columns = columns
  748.         self.obj_info = obj_info
  749.         self.options = options
  750.  
  751.     def display_list(self, columns, table):
  752.         total = [columns]
  753.         total.extend(table)
  754.         self.ascii_table(total)
  755.  
  756.     def ascii_table(self, rows):
  757.         table = ""
  758.         col_widths = [0] * len(rows[0])
  759.         for i in xrange(0, len(rows[0])):
  760.             for j in xrange(0, len(rows)):
  761.                 col_widths[i] = max(col_widths[i], len(rows[j][i]))
  762.         self.ascii_bar(col_widths)
  763.         self.ascii_row(col_widths, rows[0], "^")
  764.         self.ascii_bar(col_widths)
  765.         for row in rows[1:]:
  766.             self.ascii_row(col_widths, row, "<")
  767.         self.ascii_bar(col_widths)
  768.  
  769.     def ascii_row(self, col_widths, row, align):
  770.         txt = "|"
  771.         for i in xrange(0, len(col_widths)):
  772.             fmt = " {0:" + align + unicode(col_widths[i]) + "} "
  773.             txt += fmt.format(row[i]) + "|"
  774.         output(txt)
  775.  
  776.     def ascii_bar(self, col_widths):
  777.         txt = "+"
  778.         for w in col_widths:
  779.             txt += ("-" * (w + 2)) + "+"
  780.         output(txt)
  781.  
  782. class KeyValueList(Lister):
  783.     def __init__(self, columns, obj_info, options):
  784.         self.columns = columns
  785.         self.obj_info = obj_info
  786.         self.options = options
  787.  
  788.     def display_list(self, columns, table):
  789.         for i in xrange(0, len(table)):
  790.             row = []
  791.             for j in xrange(0, len(columns)):
  792.                 row.append("{0}=\"{1}\"".format(columns[j], table[i][j]))
  793.             output(" ".join(row))
  794.  
  795. # TODO handle spaces etc in completable names
  796. class BashList(Lister):
  797.     def __init__(self, columns, obj_info, options):
  798.         self.columns = columns
  799.         self.obj_info = obj_info
  800.         self.options = options
  801.  
  802.     def display_list(self, columns, table):
  803.         ix = None
  804.         for i in xrange(0, len(columns)):
  805.             if columns[i] == 'name':
  806.                 ix = i
  807.         if ix is not None:
  808.             res = []
  809.             for row in table:
  810.                 res.append(row[ix])
  811.             output(" ".join(res))
  812.  
  813. FORMATS = {
  814.     'raw_json'    : None, # Special cased
  815.     'pretty_json' : None, # Ditto
  816.     'tsv'         : TSVList,
  817.     'long'        : LongList,
  818.     'table'       : TableList,
  819.     'kvp'         : KeyValueList,
  820.     'bash'        : BashList
  821. }
  822.  
  823. def write_payload_file(payload_file, json_list):
  824.     result = json.loads(json_list)[0]
  825.     payload = result['payload']
  826.     payload_encoding = result['payload_encoding']
  827.     f = open(payload_file, 'w')
  828.     if payload_encoding == 'base64':
  829.         data = base64.b64decode(payload)
  830.     else:
  831.         data = payload
  832.     f.write(data)
  833.     f.close()
  834.  
  835. def print_bash_completion():
  836.     script = """# This is a bash completion script for rabbitmqadmin.
  837. # Redirect it to a file, then source it or copy it to /etc/bash_completion.d
  838. # to get tab completion. rabbitmqadmin must be on your PATH for this to work.
  839. _rabbitmqadmin()
  840. {
  841.    local cur prev opts base
  842.    COMPREPLY=()
  843.    cur="${COMP_WORDS[COMP_CWORD]}"
  844.    prev="${COMP_WORDS[COMP_CWORD-1]}"
  845.  
  846.    opts="list show declare delete close purge import export get publish help"
  847.    fargs="--help --host --port --vhost --username --password --format --depth --sort --sort-reverse"
  848.  
  849.    case "${prev}" in
  850.        list)
  851.            COMPREPLY=( $(compgen -W '""" + " ".join(LISTABLE) + """' -- ${cur}) )
  852.            return 0
  853.            ;;
  854.        show)
  855.            COMPREPLY=( $(compgen -W '""" + " ".join(SHOWABLE) + """' -- ${cur}) )
  856.            return 0
  857.            ;;
  858.        declare)
  859.            COMPREPLY=( $(compgen -W '""" + " ".join(DECLARABLE.keys()) + """' -- ${cur}) )
  860.            return 0
  861.            ;;
  862.        delete)
  863.            COMPREPLY=( $(compgen -W '""" + " ".join(DELETABLE.keys()) + """' -- ${cur}) )
  864.            return 0
  865.            ;;
  866.        close)
  867.            COMPREPLY=( $(compgen -W '""" + " ".join(CLOSABLE.keys()) + """' -- ${cur}) )
  868.            return 0
  869.            ;;
  870.        purge)
  871.            COMPREPLY=( $(compgen -W '""" + " ".join(PURGABLE.keys()) + """' -- ${cur}) )
  872.            return 0
  873.            ;;
  874.        export)
  875.            COMPREPLY=( $(compgen -f ${cur}) )
  876.            return 0
  877.            ;;
  878.        import)
  879.            COMPREPLY=( $(compgen -f ${cur}) )
  880.            return 0
  881.            ;;
  882.        help)
  883.            opts="subcommands config"
  884.            COMPREPLY=( $(compgen -W "${opts}"  -- ${cur}) )
  885.            return 0
  886.            ;;
  887.        -H)
  888.            COMPREPLY=( $(compgen -A hostname ${cur}) )
  889.            return 0
  890.            ;;
  891.        --host)
  892.            COMPREPLY=( $(compgen -A hostname ${cur}) )
  893.            return 0
  894.            ;;
  895.        -V)
  896.            opts="$(rabbitmqadmin -q -f bash list vhosts)"
  897.            COMPREPLY=( $(compgen -W "${opts}"  -- ${cur}) )
  898.            return 0
  899.            ;;
  900.        --vhost)
  901.            opts="$(rabbitmqadmin -q -f bash list vhosts)"
  902.            COMPREPLY=( $(compgen -W "${opts}"  -- ${cur}) )
  903.            return 0
  904.            ;;
  905.        -u)
  906.            opts="$(rabbitmqadmin -q -f bash list users)"
  907.            COMPREPLY=( $(compgen -W "${opts}"  -- ${cur}) )
  908.            return 0
  909.            ;;
  910.        --username)
  911.            opts="$(rabbitmqadmin -q -f bash list users)"
  912.            COMPREPLY=( $(compgen -W "${opts}"  -- ${cur}) )
  913.            return 0
  914.            ;;
  915.        -f)
  916.            COMPREPLY=( $(compgen -W \"""" + " ".join(FORMATS.keys()) + """\"  -- ${cur}) )
  917.            return 0
  918.            ;;
  919.        --format)
  920.            COMPREPLY=( $(compgen -W \"""" + " ".join(FORMATS.keys()) + """\"  -- ${cur}) )
  921.            return 0
  922.            ;;
  923.  
  924. """
  925.    for l in LISTABLE:
  926.        key = l[0:len(l) - 1]
  927.        script += "        " + key + """)
  928.            opts="$(rabbitmqadmin -q -f bash list """ + l + """)"
  929.            COMPREPLY=( $(compgen -W "${opts}"  -- ${cur}) )
  930.            return 0
  931.            ;;
  932. """
  933.    script += """        *)
  934.        ;;
  935.    esac
  936.  
  937.   COMPREPLY=($(compgen -W "${opts} ${fargs}" -- ${cur}))
  938.   return 0
  939. }
  940. complete -F _rabbitmqadmin rabbitmqadmin
  941. """
  942.    output(script)
  943.  
  944. if __name__ == "__main__":
  945.    main()
  946. [stack@rdo01 ~]$
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement