nsc.py 5.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151
  1. """
  2. Name server control tool.
  3. Pyro - Python Remote Objects. Copyright by Irmen de Jong (irmen@razorvine.net).
  4. """
  5. from __future__ import print_function
  6. import sys
  7. import os
  8. import warnings
  9. from Pyro4 import errors, naming
  10. if sys.version_info < (3, 0):
  11. input = raw_input
  12. def handleCommand(nameserver, options, args):
  13. def printListResult(resultdict, title=""):
  14. print("--------START LIST %s" % title)
  15. for name, (uri, metadata) in sorted(resultdict.items()):
  16. print("%s --> %s" % (name, uri))
  17. if metadata:
  18. print(" metadata:", metadata)
  19. print("--------END LIST %s" % title)
  20. def cmd_ping():
  21. nameserver.ping()
  22. print("Name server ping ok.")
  23. def cmd_listprefix():
  24. if len(args) == 1:
  25. printListResult(nameserver.list(return_metadata=True))
  26. else:
  27. printListResult(nameserver.list(prefix=args[1], return_metadata=True), "- prefix '%s'" % args[1])
  28. def cmd_listregex():
  29. if len(args) != 2:
  30. raise SystemExit("requires one argument: pattern")
  31. printListResult(nameserver.list(regex=args[1], return_metadata=True), "- regex '%s'" % args[1])
  32. def cmd_lookup():
  33. if len(args) != 2:
  34. raise SystemExit("requires one argument: name")
  35. uri, metadata = nameserver.lookup(args[1], return_metadata=True)
  36. print(uri)
  37. if metadata:
  38. print("metadata:", metadata)
  39. def cmd_register():
  40. if len(args) != 3:
  41. raise SystemExit("requires two arguments: name uri")
  42. nameserver.register(args[1], args[2], safe=True)
  43. print("Registered %s" % args[1])
  44. def cmd_remove():
  45. if len(args) != 2:
  46. raise SystemExit("requires one argument: name")
  47. count = nameserver.remove(args[1])
  48. if count > 0:
  49. print("Removed %s" % args[1])
  50. else:
  51. print("Nothing removed")
  52. def cmd_removeregex():
  53. if len(args) != 2:
  54. raise SystemExit("requires one argument: pattern")
  55. sure = input("Potentially removing lots of items from the Name server. Are you sure (y/n)?").strip()
  56. if sure in ('y', 'Y'):
  57. count = nameserver.remove(regex=args[1])
  58. print("%d items removed." % count)
  59. def cmd_setmeta():
  60. if len(args) < 2:
  61. raise SystemExit("requires at least 2 arguments: uri and zero or more meta tags")
  62. metadata = set(args[2:])
  63. nameserver.set_metadata(args[1], metadata)
  64. if metadata:
  65. print("Metadata updated")
  66. else:
  67. print("Metadata cleared")
  68. def cmd_listmeta_all():
  69. if len(args) < 2:
  70. raise SystemExit("requires at least one metadata tag argument")
  71. metadata = set(args[1:])
  72. printListResult(nameserver.list(metadata_all=metadata, return_metadata=True), " - searched by metadata")
  73. def cmd_listmeta_any():
  74. if len(args) < 2:
  75. raise SystemExit("requires at least one metadata tag argument")
  76. metadata = set(args[1:])
  77. printListResult(nameserver.list(metadata_any=metadata, return_metadata=True), " - searched by metadata")
  78. commands = {
  79. "ping": cmd_ping,
  80. "list": cmd_listprefix,
  81. "listmatching": cmd_listregex,
  82. "listmeta_all": cmd_listmeta_all,
  83. "listmeta_any": cmd_listmeta_any,
  84. "lookup": cmd_lookup,
  85. "register": cmd_register,
  86. "remove": cmd_remove,
  87. "removematching": cmd_removeregex,
  88. "setmeta": cmd_setmeta
  89. }
  90. try:
  91. commands[args[0]]()
  92. except Exception as x:
  93. print("Error: %s - %s" % (type(x).__name__, x))
  94. def main(args=None):
  95. from optparse import OptionParser
  96. usage = "usage: %prog [options] command [arguments]\nCommands: " \
  97. "register remove removematching lookup list listmatching\n listmeta_all listmeta_any setmeta ping"
  98. parser = OptionParser(usage=usage)
  99. parser.add_option("-n", "--host", dest="host", help="hostname of the NS")
  100. parser.add_option("-p", "--port", dest="port", type="int",
  101. help="port of the NS (or bc-port if host isn't specified)")
  102. parser.add_option("-u", "--unixsocket", help="Unix domain socket name of the NS")
  103. parser.add_option("-k", "--key", help="the HMAC key to use (deprecated)")
  104. parser.add_option("-v", "--verbose", action="store_true", dest="verbose", help="verbose output")
  105. options, args = parser.parse_args(args)
  106. if options.key:
  107. warnings.warn("using -k to supply HMAC key on the command line is a security problem "
  108. "and is deprecated since Pyro 4.72. See the documentation for an alternative.")
  109. if "PYRO_HMAC_KEY" in os.environ:
  110. if options.key:
  111. raise SystemExit("error: don't use -k and PYRO_HMAC_KEY at the same time")
  112. options.key = os.environ["PYRO_HMAC_KEY"]
  113. if not args or args[0] not in ("register", "remove", "removematching", "list", "listmatching", "lookup",
  114. "listmeta_all", "listmeta_any", "setmeta", "ping"):
  115. parser.error("invalid or missing command")
  116. if options.verbose:
  117. print("Locating name server...")
  118. if options.unixsocket:
  119. options.host = "./u:" + options.unixsocket
  120. try:
  121. nameserver = naming.locateNS(options.host, options.port, hmac_key=options.key)
  122. except errors.PyroError as x:
  123. print("Error: %s" % x)
  124. return
  125. if options.verbose:
  126. print("Name server found: %s" % nameserver._pyroUri)
  127. handleCommand(nameserver, options, args)
  128. if options.verbose:
  129. print("Done.")
  130. if __name__ == "__main__":
  131. main()