port_server.py 4.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142
  1. #!/usr/bin/env python2.7
  2. # Copyright 2015, Google Inc.
  3. # All rights reserved.
  4. #
  5. # Redistribution and use in source and binary forms, with or without
  6. # modification, are permitted provided that the following conditions are
  7. # met:
  8. #
  9. # * Redistributions of source code must retain the above copyright
  10. # notice, this list of conditions and the following disclaimer.
  11. # * Redistributions in binary form must reproduce the above
  12. # copyright notice, this list of conditions and the following disclaimer
  13. # in the documentation and/or other materials provided with the
  14. # distribution.
  15. # * Neither the name of Google Inc. nor the names of its
  16. # contributors may be used to endorse or promote products derived from
  17. # this software without specific prior written permission.
  18. #
  19. # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  20. # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  21. # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  22. # A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  23. # OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  24. # SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  25. # LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  26. # DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  27. # THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  28. # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  29. # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  30. """Manage TCP ports for unit tests; started by run_tests.py"""
  31. import argparse
  32. import BaseHTTPServer
  33. import hashlib
  34. import os
  35. import socket
  36. import sys
  37. import time
  38. argp = argparse.ArgumentParser(description='Server for httpcli_test')
  39. argp.add_argument('-p', '--port', default=12345, type=int)
  40. args = argp.parse_args()
  41. print 'port server running on port %d' % args.port
  42. pool = []
  43. in_use = {}
  44. with open(__file__) as f:
  45. _MY_VERSION = hashlib.sha1(f.read()).hexdigest()
  46. def refill_pool(max_timeout, req):
  47. """Scan for ports not marked for being in use"""
  48. for i in range(1025, 32767):
  49. if len(pool) > 100: break
  50. if i in in_use:
  51. age = time.time() - in_use[i]
  52. if age < max_timeout:
  53. continue
  54. req.log_message("kill old request %d" % i)
  55. del in_use[i]
  56. s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
  57. s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
  58. try:
  59. s.bind(('localhost', i))
  60. req.log_message("found available port %d" % i)
  61. pool.append(i)
  62. except:
  63. pass # we really don't care about failures
  64. finally:
  65. s.close()
  66. def allocate_port(req):
  67. global pool
  68. global in_use
  69. max_timeout = 600
  70. while not pool:
  71. refill_pool(max_timeout, req)
  72. if not pool:
  73. req.log_message("failed to find ports: retrying soon")
  74. time.sleep(1)
  75. max_timeout /= 2
  76. port = pool[0]
  77. pool = pool[1:]
  78. in_use[port] = time.time()
  79. return port
  80. keep_running = True
  81. class Handler(BaseHTTPServer.BaseHTTPRequestHandler):
  82. def do_GET(self):
  83. global keep_running
  84. if self.path == '/get':
  85. # allocate a new port, it will stay bound for ten minutes and until
  86. # it's unused
  87. self.send_response(200)
  88. self.send_header('Content-Type', 'text/plain')
  89. self.end_headers()
  90. p = allocate_port(self)
  91. self.log_message('allocated port %d' % p)
  92. self.wfile.write('%d' % p)
  93. elif self.path[0:6] == '/drop/':
  94. self.send_response(200)
  95. self.send_header('Content-Type', 'text/plain')
  96. self.end_headers()
  97. p = int(self.path[6:])
  98. del in_use[p]
  99. pool.append(p)
  100. self.log_message('drop port %d' % p)
  101. elif self.path == '/version':
  102. # fetch a version string and the current process pid
  103. self.send_response(200)
  104. self.send_header('Content-Type', 'text/plain')
  105. self.end_headers()
  106. self.wfile.write(_MY_VERSION)
  107. elif self.path == '/dump':
  108. # yaml module is not installed on Macs and Windows machines by default
  109. # so we import it lazily (/dump action is only used for debugging)
  110. import yaml
  111. self.send_response(200)
  112. self.send_header('Content-Type', 'text/plain')
  113. self.end_headers()
  114. now = time.time()
  115. self.wfile.write(yaml.dump({'pool': pool, 'in_use': dict((k, now - v) for k, v in in_use.iteritems())}))
  116. elif self.path == '/quit':
  117. self.send_response(200)
  118. self.end_headers()
  119. keep_running = False
  120. httpd = BaseHTTPServer.HTTPServer(('', args.port), Handler)
  121. while keep_running:
  122. httpd.handle_request()
  123. print 'done'