blob: 079ed70fbf3152c2a859cf44d60cc2088f94ded8 [file] [log] [blame]
Siddharth Shukla8e64d902017-03-12 19:50:18 +01001#!/usr/bin/env python
Craig Tillerf53d9c82015-08-04 14:19:43 -07002# 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
31"""Manage TCP ports for unit tests; started by run_tests.py"""
32
siddharthshukla0589e532016-07-07 16:08:01 +020033from __future__ import print_function
34
Craig Tillerf53d9c82015-08-04 14:19:43 -070035import argparse
Craig Tillerea525eb2017-04-24 17:50:32 +000036from BaseHTTPServer import HTTPServer, BaseHTTPRequestHandler
Craig Tillerf53d9c82015-08-04 14:19:43 -070037import hashlib
38import os
39import socket
40import sys
41import time
Craig Tillere1f53022017-05-04 19:53:19 +000042import random
Craig Tillerea525eb2017-04-24 17:50:32 +000043from SocketServer import ThreadingMixIn
44import threading
Craig Tillerf53d9c82015-08-04 14:19:43 -070045
Craig Tillerfe4939f2015-10-06 12:55:36 -070046
47# increment this number whenever making a change to ensure that
48# the changes are picked up by running CI servers
49# note that all changes must be backwards compatible
Craig Tillere1f53022017-05-04 19:53:19 +000050_MY_VERSION = 19
Craig Tillerfe4939f2015-10-06 12:55:36 -070051
52
53if len(sys.argv) == 2 and sys.argv[1] == 'dump_version':
siddharthshukla0589e532016-07-07 16:08:01 +020054 print(_MY_VERSION)
Craig Tillerfe4939f2015-10-06 12:55:36 -070055 sys.exit(0)
56
57
Craig Tillerf53d9c82015-08-04 14:19:43 -070058argp = argparse.ArgumentParser(description='Server for httpcli_test')
59argp.add_argument('-p', '--port', default=12345, type=int)
Craig Tillerf0a293e2015-10-12 10:05:50 -070060argp.add_argument('-l', '--logfile', default=None, type=str)
Craig Tillerf53d9c82015-08-04 14:19:43 -070061args = argp.parse_args()
62
Craig Tillerf0a293e2015-10-12 10:05:50 -070063if args.logfile is not None:
Craig Tiller41a7bf52015-10-12 12:54:55 -070064 sys.stdin.close()
65 sys.stderr.close()
66 sys.stdout.close()
Craig Tillerf0a293e2015-10-12 10:05:50 -070067 sys.stderr = open(args.logfile, 'w')
68 sys.stdout = sys.stderr
69
siddharthshukla0589e532016-07-07 16:08:01 +020070print('port server running on port %d' % args.port)
Craig Tillerf53d9c82015-08-04 14:19:43 -070071
72pool = []
73in_use = {}
Craig Tillerec495242017-04-24 20:55:43 +000074mu = threading.Lock()
Craig Tillerf53d9c82015-08-04 14:19:43 -070075
Craig Tillere1f53022017-05-04 19:53:19 +000076def can_connect(port):
77 s = socket.socket()
78 try:
79 s.connect(('localhost', port))
80 return True
81 except socket.error, e:
82 return False
83 finally:
84 s.close()
85
86def can_bind(port, proto):
87 s = socket.socket(proto, socket.SOCK_STREAM)
88 s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
89 try:
90 s.bind(('localhost', port))
91 return True
92 except socket.error, e:
93 return False
94 finally:
95 s.close()
96
Craig Tillerf53d9c82015-08-04 14:19:43 -070097
Craig Tillerc20b19d2015-09-22 13:06:06 -070098def refill_pool(max_timeout, req):
Craig Tillerf53d9c82015-08-04 14:19:43 -070099 """Scan for ports not marked for being in use"""
Craig Tillere1f53022017-05-04 19:53:19 +0000100 chk = list(range(1025, 32766))
101 random.shuffle(chk)
102 for i in chk:
Craig Tillerf53d9c82015-08-04 14:19:43 -0700103 if len(pool) > 100: break
104 if i in in_use:
105 age = time.time() - in_use[i]
Craig Tillerae322af2015-09-13 18:41:21 +0000106 if age < max_timeout:
Craig Tillerf53d9c82015-08-04 14:19:43 -0700107 continue
Craig Tillerc20b19d2015-09-22 13:06:06 -0700108 req.log_message("kill old request %d" % i)
Craig Tillerf53d9c82015-08-04 14:19:43 -0700109 del in_use[i]
Craig Tillere1f53022017-05-04 19:53:19 +0000110 if can_bind(i, socket.AF_INET) and can_bind(i, socket.AF_INET6) and not can_connect(i):
Craig Tillerc20b19d2015-09-22 13:06:06 -0700111 req.log_message("found available port %d" % i)
Craig Tillerf53d9c82015-08-04 14:19:43 -0700112 pool.append(i)
Craig Tillerf53d9c82015-08-04 14:19:43 -0700113
114
Craig Tillerc20b19d2015-09-22 13:06:06 -0700115def allocate_port(req):
Craig Tillerf53d9c82015-08-04 14:19:43 -0700116 global pool
117 global in_use
Craig Tillerec495242017-04-24 20:55:43 +0000118 global mu
119 mu.acquire()
Craig Tillerae322af2015-09-13 18:41:21 +0000120 max_timeout = 600
121 while not pool:
Craig Tillerc20b19d2015-09-22 13:06:06 -0700122 refill_pool(max_timeout, req)
Craig Tillerae322af2015-09-13 18:41:21 +0000123 if not pool:
Craig Tillerc20b19d2015-09-22 13:06:06 -0700124 req.log_message("failed to find ports: retrying soon")
Craig Tillerec495242017-04-24 20:55:43 +0000125 mu.release()
Craig Tillerae322af2015-09-13 18:41:21 +0000126 time.sleep(1)
Craig Tillerec495242017-04-24 20:55:43 +0000127 mu.acquire()
Craig Tillerae322af2015-09-13 18:41:21 +0000128 max_timeout /= 2
Craig Tillerf53d9c82015-08-04 14:19:43 -0700129 port = pool[0]
130 pool = pool[1:]
131 in_use[port] = time.time()
Craig Tillerec495242017-04-24 20:55:43 +0000132 mu.release()
Craig Tillerf53d9c82015-08-04 14:19:43 -0700133 return port
134
135
Craig Tilleref125592015-08-05 07:41:35 -0700136keep_running = True
137
138
Craig Tillerea525eb2017-04-24 17:50:32 +0000139class Handler(BaseHTTPRequestHandler):
Ken Payson189d6852016-07-09 15:58:18 -0700140
141 def setup(self):
142 # If the client is unreachable for 5 seconds, close the connection
143 self.timeout = 5
Craig Tillerea525eb2017-04-24 17:50:32 +0000144 BaseHTTPRequestHandler.setup(self)
Craig Tillerf53d9c82015-08-04 14:19:43 -0700145
146 def do_GET(self):
Craig Tilleref125592015-08-05 07:41:35 -0700147 global keep_running
Craig Tillere1f53022017-05-04 19:53:19 +0000148 global mu
Craig Tillerf53d9c82015-08-04 14:19:43 -0700149 if self.path == '/get':
150 # allocate a new port, it will stay bound for ten minutes and until
151 # it's unused
152 self.send_response(200)
153 self.send_header('Content-Type', 'text/plain')
154 self.end_headers()
Craig Tillerc20b19d2015-09-22 13:06:06 -0700155 p = allocate_port(self)
Craig Tillerf53d9c82015-08-04 14:19:43 -0700156 self.log_message('allocated port %d' % p)
157 self.wfile.write('%d' % p)
Craig Tillerae322af2015-09-13 18:41:21 +0000158 elif self.path[0:6] == '/drop/':
159 self.send_response(200)
160 self.send_header('Content-Type', 'text/plain')
161 self.end_headers()
162 p = int(self.path[6:])
Craig Tillere1f53022017-05-04 19:53:19 +0000163 mu.acquire()
Craig Tillerd2c39712015-10-12 11:08:49 -0700164 if p in in_use:
165 del in_use[p]
166 pool.append(p)
Craig Tillere1f53022017-05-04 19:53:19 +0000167 k = 'known'
Craig Tillerd2c39712015-10-12 11:08:49 -0700168 else:
Craig Tillere1f53022017-05-04 19:53:19 +0000169 k = 'unknown'
170 mu.release()
171 self.log_message('drop %s port %d' % (k, p))
Craig Tillerfe4939f2015-10-06 12:55:36 -0700172 elif self.path == '/version_number':
Craig Tillerf53d9c82015-08-04 14:19:43 -0700173 # fetch a version string and the current process pid
174 self.send_response(200)
175 self.send_header('Content-Type', 'text/plain')
176 self.end_headers()
Craig Tilleref125592015-08-05 07:41:35 -0700177 self.wfile.write(_MY_VERSION)
Craig Tillerae322af2015-09-13 18:41:21 +0000178 elif self.path == '/dump':
Jan Tattermusch13e65df2015-09-21 09:30:49 -0700179 # yaml module is not installed on Macs and Windows machines by default
180 # so we import it lazily (/dump action is only used for debugging)
181 import yaml
Craig Tillerae322af2015-09-13 18:41:21 +0000182 self.send_response(200)
183 self.send_header('Content-Type', 'text/plain')
184 self.end_headers()
Craig Tillere1f53022017-05-04 19:53:19 +0000185 mu.acquire()
Craig Tillerae322af2015-09-13 18:41:21 +0000186 now = time.time()
Craig Tillere1f53022017-05-04 19:53:19 +0000187 out = yaml.dump({'pool': pool, 'in_use': dict((k, now - v) for k, v in in_use.items())})
188 mu.release()
189 self.wfile.write(out)
Craig Tillerfe4939f2015-10-06 12:55:36 -0700190 elif self.path == '/quitquitquit':
Craig Tilleref125592015-08-05 07:41:35 -0700191 self.send_response(200)
192 self.end_headers()
Craig Tiller09ebed72017-04-25 10:19:10 -0700193 self.server.shutdown()
Craig Tillerea525eb2017-04-24 17:50:32 +0000194
195class ThreadedHTTPServer(ThreadingMixIn, HTTPServer):
196 """Handle requests in a separate thread"""
Craig Tillerf53d9c82015-08-04 14:19:43 -0700197
198
Craig Tiller09ebed72017-04-25 10:19:10 -0700199ThreadedHTTPServer(('', args.port), Handler).serve_forever()
Craig Tilleref125592015-08-05 07:41:35 -0700200