dictserver.py 4.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159
  1. #!/usr/bin/env python
  2. # -*- coding: utf-8 -*-
  3. #
  4. """ DICT server """
  5. from __future__ import (absolute_import, division, print_function,
  6. unicode_literals)
  7. import argparse
  8. import os
  9. import sys
  10. import logging
  11. try: # Python 2
  12. import SocketServer as socketserver
  13. except ImportError: # Python 3
  14. import socketserver
  15. log = logging.getLogger(__name__)
  16. HOST = "localhost"
  17. # The strings that indicate the test framework is checking our aliveness
  18. VERIFIED_REQ = b"verifiedserver"
  19. VERIFIED_RSP = "WE ROOLZ: {pid}"
  20. def dictserver(options):
  21. """
  22. Starts up a TCP server with a DICT handler and serves DICT requests
  23. forever.
  24. """
  25. if options.pidfile:
  26. pid = os.getpid()
  27. with open(options.pidfile, "w") as f:
  28. f.write("{0}".format(pid))
  29. local_bind = (HOST, options.port)
  30. log.info("[DICT] Listening on %s", local_bind)
  31. # Need to set the allow_reuse on the class, not on the instance.
  32. socketserver.TCPServer.allow_reuse_address = True
  33. server = socketserver.TCPServer(local_bind, DictHandler)
  34. server.serve_forever()
  35. return ScriptRC.SUCCESS
  36. class DictHandler(socketserver.BaseRequestHandler):
  37. """Handler class for DICT connections.
  38. """
  39. def handle(self):
  40. """
  41. Simple function which responds to all queries with a 552.
  42. """
  43. try:
  44. # First, send a response to allow the server to continue.
  45. rsp = "220 dictserver <xnooptions> <msgid@msgid>\n"
  46. self.request.sendall(rsp.encode("utf-8"))
  47. # Receive the request.
  48. data = self.request.recv(1024).strip()
  49. log.debug("[DICT] Incoming data: %r", data)
  50. if VERIFIED_REQ in data:
  51. log.debug("[DICT] Received verification request from test "
  52. "framework")
  53. response_data = VERIFIED_RSP.format(pid=os.getpid())
  54. else:
  55. log.debug("[DICT] Received normal request")
  56. response_data = "No matches"
  57. # Send back a failure to find.
  58. response = "552 {0}\n".format(response_data)
  59. log.debug("[DICT] Responding with %r", response)
  60. self.request.sendall(response.encode("utf-8"))
  61. except IOError:
  62. log.exception("[DICT] IOError hit during request")
  63. def get_options():
  64. parser = argparse.ArgumentParser()
  65. parser.add_argument("--port", action="store", default=9016,
  66. type=int, help="port to listen on")
  67. parser.add_argument("--verbose", action="store", type=int, default=0,
  68. help="verbose output")
  69. parser.add_argument("--pidfile", action="store",
  70. help="file name for the PID")
  71. parser.add_argument("--logfile", action="store",
  72. help="file name for the log")
  73. parser.add_argument("--srcdir", action="store", help="test directory")
  74. parser.add_argument("--id", action="store", help="server ID")
  75. parser.add_argument("--ipv4", action="store_true", default=0,
  76. help="IPv4 flag")
  77. return parser.parse_args()
  78. def setup_logging(options):
  79. """
  80. Set up logging from the command line options
  81. """
  82. root_logger = logging.getLogger()
  83. add_stdout = False
  84. formatter = logging.Formatter("%(asctime)s %(levelname)-5.5s %(message)s")
  85. # Write out to a logfile
  86. if options.logfile:
  87. handler = logging.FileHandler(options.logfile, mode="w")
  88. handler.setFormatter(formatter)
  89. handler.setLevel(logging.DEBUG)
  90. root_logger.addHandler(handler)
  91. else:
  92. # The logfile wasn't specified. Add a stdout logger.
  93. add_stdout = True
  94. if options.verbose:
  95. # Add a stdout logger as well in verbose mode
  96. root_logger.setLevel(logging.DEBUG)
  97. add_stdout = True
  98. else:
  99. root_logger.setLevel(logging.INFO)
  100. if add_stdout:
  101. stdout_handler = logging.StreamHandler(sys.stdout)
  102. stdout_handler.setFormatter(formatter)
  103. stdout_handler.setLevel(logging.DEBUG)
  104. root_logger.addHandler(stdout_handler)
  105. class ScriptRC(object):
  106. """Enum for script return codes"""
  107. SUCCESS = 0
  108. FAILURE = 1
  109. EXCEPTION = 2
  110. class ScriptException(Exception):
  111. pass
  112. if __name__ == '__main__':
  113. # Get the options from the user.
  114. options = get_options()
  115. # Setup logging using the user options
  116. setup_logging(options)
  117. # Run main script.
  118. try:
  119. rc = dictserver(options)
  120. except Exception as e:
  121. log.exception(e)
  122. rc = ScriptRC.EXCEPTION
  123. log.info("[DICT] Returning %d", rc)
  124. sys.exit(rc)