blob: 522cbed9e1c56f50d9a186547ffb20a31b5e8860 [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 Tillerea525eb2017-04-24 17:50:32 +000042from SocketServer import ThreadingMixIn
43import threading
Craig Tillerf53d9c82015-08-04 14:19:43 -070044
Craig Tillerfe4939f2015-10-06 12:55:36 -070045
46# increment this number whenever making a change to ensure that
47# the changes are picked up by running CI servers
48# note that all changes must be backwards compatible
Craig Tillerec495242017-04-24 20:55:43 +000049_MY_VERSION = 11
Craig Tillerfe4939f2015-10-06 12:55:36 -070050
51
52if len(sys.argv) == 2 and sys.argv[1] == 'dump_version':
siddharthshukla0589e532016-07-07 16:08:01 +020053 print(_MY_VERSION)
Craig Tillerfe4939f2015-10-06 12:55:36 -070054 sys.exit(0)
55
56
Craig Tillerf53d9c82015-08-04 14:19:43 -070057argp = argparse.ArgumentParser(description='Server for httpcli_test')
58argp.add_argument('-p', '--port', default=12345, type=int)
Craig Tillerf0a293e2015-10-12 10:05:50 -070059argp.add_argument('-l', '--logfile', default=None, type=str)
Craig Tillerf53d9c82015-08-04 14:19:43 -070060args = argp.parse_args()
61
Craig Tillerf0a293e2015-10-12 10:05:50 -070062if args.logfile is not None:
Craig Tiller41a7bf52015-10-12 12:54:55 -070063 sys.stdin.close()
64 sys.stderr.close()
65 sys.stdout.close()
Craig Tillerf0a293e2015-10-12 10:05:50 -070066 sys.stderr = open(args.logfile, 'w')
67 sys.stdout = sys.stderr
68
siddharthshukla0589e532016-07-07 16:08:01 +020069print('port server running on port %d' % args.port)
Craig Tillerf53d9c82015-08-04 14:19:43 -070070
71pool = []
72in_use = {}
Craig Tillerec495242017-04-24 20:55:43 +000073mu = threading.Lock()
Craig Tillerf53d9c82015-08-04 14:19:43 -070074
Craig Tillerf53d9c82015-08-04 14:19:43 -070075
Craig Tillerc20b19d2015-09-22 13:06:06 -070076def refill_pool(max_timeout, req):
Craig Tillerf53d9c82015-08-04 14:19:43 -070077 """Scan for ports not marked for being in use"""
Ken Paysonfa51de52016-06-30 23:50:48 -070078 for i in range(1025, 32766):
Craig Tillerf53d9c82015-08-04 14:19:43 -070079 if len(pool) > 100: break
80 if i in in_use:
81 age = time.time() - in_use[i]
Craig Tillerae322af2015-09-13 18:41:21 +000082 if age < max_timeout:
Craig Tillerf53d9c82015-08-04 14:19:43 -070083 continue
Craig Tillerc20b19d2015-09-22 13:06:06 -070084 req.log_message("kill old request %d" % i)
Craig Tillerf53d9c82015-08-04 14:19:43 -070085 del in_use[i]
86 s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
Craig Tillerae322af2015-09-13 18:41:21 +000087 s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
Craig Tillerf53d9c82015-08-04 14:19:43 -070088 try:
89 s.bind(('localhost', i))
Craig Tillerc20b19d2015-09-22 13:06:06 -070090 req.log_message("found available port %d" % i)
Craig Tillerf53d9c82015-08-04 14:19:43 -070091 pool.append(i)
92 except:
93 pass # we really don't care about failures
94 finally:
95 s.close()
96
97
Craig Tillerc20b19d2015-09-22 13:06:06 -070098def allocate_port(req):
Craig Tillerf53d9c82015-08-04 14:19:43 -070099 global pool
100 global in_use
Craig Tillerec495242017-04-24 20:55:43 +0000101 global mu
102 mu.acquire()
Craig Tillerae322af2015-09-13 18:41:21 +0000103 max_timeout = 600
104 while not pool:
Craig Tillerc20b19d2015-09-22 13:06:06 -0700105 refill_pool(max_timeout, req)
Craig Tillerae322af2015-09-13 18:41:21 +0000106 if not pool:
Craig Tillerc20b19d2015-09-22 13:06:06 -0700107 req.log_message("failed to find ports: retrying soon")
Craig Tillerec495242017-04-24 20:55:43 +0000108 mu.release()
Craig Tillerae322af2015-09-13 18:41:21 +0000109 time.sleep(1)
Craig Tillerec495242017-04-24 20:55:43 +0000110 mu.acquire()
Craig Tillerae322af2015-09-13 18:41:21 +0000111 max_timeout /= 2
Craig Tillerf53d9c82015-08-04 14:19:43 -0700112 port = pool[0]
113 pool = pool[1:]
114 in_use[port] = time.time()
Craig Tillerec495242017-04-24 20:55:43 +0000115 mu.release()
Craig Tillerf53d9c82015-08-04 14:19:43 -0700116 return port
117
118
Craig Tilleref125592015-08-05 07:41:35 -0700119keep_running = True
120
121
Craig Tillerea525eb2017-04-24 17:50:32 +0000122class Handler(BaseHTTPRequestHandler):
Ken Payson189d6852016-07-09 15:58:18 -0700123
124 def setup(self):
125 # If the client is unreachable for 5 seconds, close the connection
126 self.timeout = 5
Craig Tillerea525eb2017-04-24 17:50:32 +0000127 BaseHTTPRequestHandler.setup(self)
Craig Tillerf53d9c82015-08-04 14:19:43 -0700128
129 def do_GET(self):
Craig Tilleref125592015-08-05 07:41:35 -0700130 global keep_running
Craig Tillerf53d9c82015-08-04 14:19:43 -0700131 if self.path == '/get':
132 # allocate a new port, it will stay bound for ten minutes and until
133 # it's unused
134 self.send_response(200)
135 self.send_header('Content-Type', 'text/plain')
136 self.end_headers()
Craig Tillerc20b19d2015-09-22 13:06:06 -0700137 p = allocate_port(self)
Craig Tillerf53d9c82015-08-04 14:19:43 -0700138 self.log_message('allocated port %d' % p)
139 self.wfile.write('%d' % p)
Craig Tillerae322af2015-09-13 18:41:21 +0000140 elif self.path[0:6] == '/drop/':
141 self.send_response(200)
142 self.send_header('Content-Type', 'text/plain')
143 self.end_headers()
144 p = int(self.path[6:])
Craig Tillerd2c39712015-10-12 11:08:49 -0700145 if p in in_use:
146 del in_use[p]
147 pool.append(p)
148 self.log_message('drop known port %d' % p)
149 else:
150 self.log_message('drop unknown port %d' % p)
Craig Tillerfe4939f2015-10-06 12:55:36 -0700151 elif self.path == '/version_number':
Craig Tillerf53d9c82015-08-04 14:19:43 -0700152 # fetch a version string and the current process pid
153 self.send_response(200)
154 self.send_header('Content-Type', 'text/plain')
155 self.end_headers()
Craig Tilleref125592015-08-05 07:41:35 -0700156 self.wfile.write(_MY_VERSION)
Craig Tillerae322af2015-09-13 18:41:21 +0000157 elif self.path == '/dump':
Jan Tattermusch13e65df2015-09-21 09:30:49 -0700158 # yaml module is not installed on Macs and Windows machines by default
159 # so we import it lazily (/dump action is only used for debugging)
160 import yaml
Craig Tillerae322af2015-09-13 18:41:21 +0000161 self.send_response(200)
162 self.send_header('Content-Type', 'text/plain')
163 self.end_headers()
164 now = time.time()
siddharthshukla0589e532016-07-07 16:08:01 +0200165 self.wfile.write(yaml.dump({'pool': pool, 'in_use': dict((k, now - v) for k, v in in_use.items())}))
Craig Tillerfe4939f2015-10-06 12:55:36 -0700166 elif self.path == '/quitquitquit':
Craig Tilleref125592015-08-05 07:41:35 -0700167 self.send_response(200)
168 self.end_headers()
Craig Tillerea525eb2017-04-24 17:50:32 +0000169 sys.exit(0)
170
171class ThreadedHTTPServer(ThreadingMixIn, HTTPServer):
172 """Handle requests in a separate thread"""
Craig Tillerf53d9c82015-08-04 14:19:43 -0700173
174
Craig Tillerea525eb2017-04-24 17:50:32 +0000175httpd = ThreadedHTTPServer(('', args.port), Handler)
176httpd.serve_forever()
Craig Tilleref125592015-08-05 07:41:35 -0700177