1 #!/usr/bin/env python2.7
2 # Copyright 2015 gRPC authors.
4 # Licensed under the Apache License, Version 2.0 (the "License");
5 # you may not use this file except in compliance with the License.
6 # You may obtain a copy of the License at
8 # http://www.apache.org/licenses/LICENSE-2.0
10 # Unless required by applicable law or agreed to in writing, software
11 # distributed under the License is distributed on an "AS IS" BASIS,
12 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 # See the License for the specific language governing permissions and
14 # limitations under the License.
15 """Manage TCP ports for unit tests; started by run_tests.py"""
17 from __future__ import print_function
20 from six.moves.BaseHTTPServer import HTTPServer, BaseHTTPRequestHandler
21 from six.moves.socketserver import ThreadingMixIn
31 # increment this number whenever making a change to ensure that
32 # the changes are picked up by running CI servers
33 # note that all changes must be backwards compatible
36 if len(sys.argv) == 2 and sys.argv[1] == 'dump_version':
40 argp = argparse.ArgumentParser(description='Server for httpcli_test')
41 argp.add_argument('-p', '--port', default=12345, type=int)
42 argp.add_argument('-l', '--logfile', default=None, type=str)
43 args = argp.parse_args()
45 if args.logfile is not None:
49 sys.stderr = open(args.logfile, 'w')
50 sys.stdout = sys.stderr
52 print('port server running on port %d' % args.port)
58 # Cronet restricts the following ports to be used (see
59 # https://cs.chromium.org/chromium/src/net/base/port_util.cc). When one of these
60 # ports is used in a Cronet test, the test would fail (see issue #12149). These
61 # ports must be excluded from pool.
62 cronet_restricted_ports = [
63 1, 7, 9, 11, 13, 15, 17, 19, 20, 21, 22, 23, 25, 37, 42, 43, 53, 77, 79, 87,
64 95, 101, 102, 103, 104, 109, 110, 111, 113, 115, 117, 119, 123, 135, 139,
65 143, 179, 389, 465, 512, 513, 514, 515, 526, 530, 531, 532, 540, 556, 563,
66 587, 601, 636, 993, 995, 2049, 3659, 4045, 6000, 6665, 6666, 6667, 6668,
71 def can_connect(port):
72 # this test is only really useful on unices where SO_REUSE_PORT is available
73 # so on Windows, where this test is expensive, skip it
74 if platform.system() == 'Windows': return False
77 s.connect(('localhost', port))
79 except socket.error as e:
85 def can_bind(port, proto):
86 s = socket.socket(proto, socket.SOCK_STREAM)
87 s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
89 s.bind(('localhost', port))
91 except socket.error as e:
97 def refill_pool(max_timeout, req):
98 """Scan for ports not marked for being in use"""
100 port for port in range(1025, 32766)
101 if port not in cronet_restricted_ports
105 if len(pool) > 100: break
107 age = time.time() - in_use[i]
108 if age < max_timeout:
110 req.log_message("kill old request %d" % i)
112 if can_bind(i, socket.AF_INET) and can_bind(
113 i, socket.AF_INET6) and not can_connect(i):
114 req.log_message("found available port %d" % i)
118 def allocate_port(req):
125 refill_pool(max_timeout, req)
127 req.log_message("failed to find ports: retrying soon")
134 in_use[port] = time.time()
142 class Handler(BaseHTTPRequestHandler):
145 # If the client is unreachable for 5 seconds, close the connection
147 BaseHTTPRequestHandler.setup(self)
152 if self.path == '/get':
153 # allocate a new port, it will stay bound for ten minutes and until
155 self.send_response(200)
156 self.send_header('Content-Type', 'text/plain')
158 p = allocate_port(self)
159 self.log_message('allocated port %d' % p)
160 self.wfile.write('%d' % p)
161 elif self.path[0:6] == '/drop/':
162 self.send_response(200)
163 self.send_header('Content-Type', 'text/plain')
165 p = int(self.path[6:])
174 self.log_message('drop %s port %d' % (k, p))
175 elif self.path == '/version_number':
176 # fetch a version string and the current process pid
177 self.send_response(200)
178 self.send_header('Content-Type', 'text/plain')
180 self.wfile.write(_MY_VERSION)
181 elif self.path == '/dump':
182 # yaml module is not installed on Macs and Windows machines by default
183 # so we import it lazily (/dump action is only used for debugging)
185 self.send_response(200)
186 self.send_header('Content-Type', 'text/plain')
192 'in_use': dict((k, now - v) for k, v in in_use.items())
195 self.wfile.write(out)
196 elif self.path == '/quitquitquit':
197 self.send_response(200)
199 self.server.shutdown()
202 class ThreadedHTTPServer(ThreadingMixIn, HTTPServer):
203 """Handle requests in a separate thread"""
206 ThreadedHTTPServer(('', args.port), Handler).serve_forever()