blob: 14e82b601eadbef7062397a2c33c791bff43318c [file] [log] [blame]
Nathaniel Manistaae4fbcd2015-09-23 16:29:44 +00001#!/usr/bin/env python2.7
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
33import argparse
34import BaseHTTPServer
35import hashlib
36import os
37import socket
38import sys
39import time
40
Craig Tillerfe4939f2015-10-06 12:55:36 -070041
42# increment this number whenever making a change to ensure that
43# the changes are picked up by running CI servers
44# note that all changes must be backwards compatible
Jan Tattermusch3bd08272015-11-04 19:24:37 -080045_MY_VERSION = 7
Craig Tillerfe4939f2015-10-06 12:55:36 -070046
47
48if len(sys.argv) == 2 and sys.argv[1] == 'dump_version':
49 print _MY_VERSION
50 sys.exit(0)
51
52
Craig Tillerf53d9c82015-08-04 14:19:43 -070053argp = argparse.ArgumentParser(description='Server for httpcli_test')
54argp.add_argument('-p', '--port', default=12345, type=int)
Craig Tillerf0a293e2015-10-12 10:05:50 -070055argp.add_argument('-l', '--logfile', default=None, type=str)
Craig Tillerf53d9c82015-08-04 14:19:43 -070056args = argp.parse_args()
57
Craig Tillerf0a293e2015-10-12 10:05:50 -070058if args.logfile is not None:
Craig Tiller41a7bf52015-10-12 12:54:55 -070059 sys.stdin.close()
60 sys.stderr.close()
61 sys.stdout.close()
Craig Tillerf0a293e2015-10-12 10:05:50 -070062 sys.stderr = open(args.logfile, 'w')
63 sys.stdout = sys.stderr
64
Craig Tillerf53d9c82015-08-04 14:19:43 -070065print 'port server running on port %d' % args.port
66
67pool = []
68in_use = {}
69
Craig Tillerf53d9c82015-08-04 14:19:43 -070070
Craig Tillerc20b19d2015-09-22 13:06:06 -070071def refill_pool(max_timeout, req):
Craig Tillerf53d9c82015-08-04 14:19:43 -070072 """Scan for ports not marked for being in use"""
Craig Tillerae322af2015-09-13 18:41:21 +000073 for i in range(1025, 32767):
Craig Tillerf53d9c82015-08-04 14:19:43 -070074 if len(pool) > 100: break
75 if i in in_use:
76 age = time.time() - in_use[i]
Craig Tillerae322af2015-09-13 18:41:21 +000077 if age < max_timeout:
Craig Tillerf53d9c82015-08-04 14:19:43 -070078 continue
Craig Tillerc20b19d2015-09-22 13:06:06 -070079 req.log_message("kill old request %d" % i)
Craig Tillerf53d9c82015-08-04 14:19:43 -070080 del in_use[i]
81 s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
Craig Tillerae322af2015-09-13 18:41:21 +000082 s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
Craig Tillerf53d9c82015-08-04 14:19:43 -070083 try:
84 s.bind(('localhost', i))
Craig Tillerc20b19d2015-09-22 13:06:06 -070085 req.log_message("found available port %d" % i)
Craig Tillerf53d9c82015-08-04 14:19:43 -070086 pool.append(i)
87 except:
88 pass # we really don't care about failures
89 finally:
90 s.close()
91
92
Craig Tillerc20b19d2015-09-22 13:06:06 -070093def allocate_port(req):
Craig Tillerf53d9c82015-08-04 14:19:43 -070094 global pool
95 global in_use
Craig Tillerae322af2015-09-13 18:41:21 +000096 max_timeout = 600
97 while not pool:
Craig Tillerc20b19d2015-09-22 13:06:06 -070098 refill_pool(max_timeout, req)
Craig Tillerae322af2015-09-13 18:41:21 +000099 if not pool:
Craig Tillerc20b19d2015-09-22 13:06:06 -0700100 req.log_message("failed to find ports: retrying soon")
Craig Tillerae322af2015-09-13 18:41:21 +0000101 time.sleep(1)
102 max_timeout /= 2
Craig Tillerf53d9c82015-08-04 14:19:43 -0700103 port = pool[0]
104 pool = pool[1:]
105 in_use[port] = time.time()
106 return port
107
108
Craig Tilleref125592015-08-05 07:41:35 -0700109keep_running = True
110
111
Craig Tillerf53d9c82015-08-04 14:19:43 -0700112class Handler(BaseHTTPServer.BaseHTTPRequestHandler):
113
114 def do_GET(self):
Craig Tilleref125592015-08-05 07:41:35 -0700115 global keep_running
Craig Tillerf53d9c82015-08-04 14:19:43 -0700116 if self.path == '/get':
117 # allocate a new port, it will stay bound for ten minutes and until
118 # it's unused
119 self.send_response(200)
120 self.send_header('Content-Type', 'text/plain')
121 self.end_headers()
Craig Tillerc20b19d2015-09-22 13:06:06 -0700122 p = allocate_port(self)
Craig Tillerf53d9c82015-08-04 14:19:43 -0700123 self.log_message('allocated port %d' % p)
124 self.wfile.write('%d' % p)
Craig Tillerae322af2015-09-13 18:41:21 +0000125 elif self.path[0:6] == '/drop/':
126 self.send_response(200)
127 self.send_header('Content-Type', 'text/plain')
128 self.end_headers()
129 p = int(self.path[6:])
Craig Tillerd2c39712015-10-12 11:08:49 -0700130 if p in in_use:
131 del in_use[p]
132 pool.append(p)
133 self.log_message('drop known port %d' % p)
134 else:
135 self.log_message('drop unknown port %d' % p)
Craig Tillerfe4939f2015-10-06 12:55:36 -0700136 elif self.path == '/version_number':
Craig Tillerf53d9c82015-08-04 14:19:43 -0700137 # fetch a version string and the current process pid
138 self.send_response(200)
139 self.send_header('Content-Type', 'text/plain')
140 self.end_headers()
Craig Tilleref125592015-08-05 07:41:35 -0700141 self.wfile.write(_MY_VERSION)
Craig Tillerae322af2015-09-13 18:41:21 +0000142 elif self.path == '/dump':
Jan Tattermusch13e65df2015-09-21 09:30:49 -0700143 # yaml module is not installed on Macs and Windows machines by default
144 # so we import it lazily (/dump action is only used for debugging)
145 import yaml
Craig Tillerae322af2015-09-13 18:41:21 +0000146 self.send_response(200)
147 self.send_header('Content-Type', 'text/plain')
148 self.end_headers()
149 now = time.time()
150 self.wfile.write(yaml.dump({'pool': pool, 'in_use': dict((k, now - v) for k, v in in_use.iteritems())}))
Craig Tillerfe4939f2015-10-06 12:55:36 -0700151 elif self.path == '/quitquitquit':
Craig Tilleref125592015-08-05 07:41:35 -0700152 self.send_response(200)
153 self.end_headers()
154 keep_running = False
Craig Tillerf53d9c82015-08-04 14:19:43 -0700155
156
Craig Tilleref125592015-08-05 07:41:35 -0700157httpd = BaseHTTPServer.HTTPServer(('', args.port), Handler)
158while keep_running:
159 httpd.handle_request()
Craig Tillerf0a293e2015-10-12 10:05:50 -0700160 sys.stderr.flush()
Craig Tilleref125592015-08-05 07:41:35 -0700161
162print 'done'