Advertisement
Guest User

Untitled

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