blob: e9b3f7ff7957c4fdfbea8d1be2dbbbc96ba55176 [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
siddharthshukla0589e532016-07-07 16:08:01 +020033from __future__ import print_function
34
Craig Tillerf53d9c82015-08-04 14:19:43 -070035import argparse
siddharthshukla0589e532016-07-07 16:08:01 +020036from six.moves import BaseHTTPServer
Craig Tillerf53d9c82015-08-04 14:19:43 -070037import hashlib
38import os
39import socket
40import sys
41import time
42
Craig Tillerfe4939f2015-10-06 12:55:36 -070043
44# increment this number whenever making a change to ensure that
45# the changes are picked up by running CI servers
46# note that all changes must be backwards compatible
Ken Payson189d6852016-07-09 15:58:18 -070047_MY_VERSION = 9
Craig Tillerfe4939f2015-10-06 12:55:36 -070048
49
50if len(sys.argv) == 2 and sys.argv[1] == 'dump_version':
siddharthshukla0589e532016-07-07 16:08:01 +020051 print(_MY_VERSION)
Craig Tillerfe4939f2015-10-06 12:55:36 -070052 sys.exit(0)
53
54
Craig Tillerf53d9c82015-08-04 14:19:43 -070055argp = argparse.ArgumentParser(description='Server for httpcli_test')
56argp.add_argument('-p', '--port', default=12345, type=int)
Craig Tillerf0a293e2015-10-12 10:05:50 -070057argp.add_argument('-l', '--logfile', default=None, type=str)
Craig Tillerf53d9c82015-08-04 14:19:43 -070058args = argp.parse_args()
59
Craig Tillerf0a293e2015-10-12 10:05:50 -070060if args.logfile is not None:
Craig Tiller41a7bf52015-10-12 12:54:55 -070061 sys.stdin.close()
62 sys.stderr.close()
63 sys.stdout.close()
Craig Tillerf0a293e2015-10-12 10:05:50 -070064 sys.stderr = open(args.logfile, 'w')
65 sys.stdout = sys.stderr
66
siddharthshukla0589e532016-07-07 16:08:01 +020067print('port server running on port %d' % args.port)
Craig Tillerf53d9c82015-08-04 14:19:43 -070068
69pool = []
70in_use = {}
71
Craig Tillerf53d9c82015-08-04 14:19:43 -070072
Craig Tillerc20b19d2015-09-22 13:06:06 -070073def refill_pool(max_timeout, req):
Craig Tillerf53d9c82015-08-04 14:19:43 -070074 """Scan for ports not marked for being in use"""
Ken Paysonfa51de52016-06-30 23:50:48 -070075 for i in range(1025, 32766):
Craig Tillerf53d9c82015-08-04 14:19:43 -070076 if len(pool) > 100: break
77 if i in in_use:
78 age = time.time() - in_use[i]
Craig Tillerae322af2015-09-13 18:41:21 +000079 if age < max_timeout:
Craig Tillerf53d9c82015-08-04 14:19:43 -070080 continue
Craig Tillerc20b19d2015-09-22 13:06:06 -070081 req.log_message("kill old request %d" % i)
Craig Tillerf53d9c82015-08-04 14:19:43 -070082 del in_use[i]
83 s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
Craig Tillerae322af2015-09-13 18:41:21 +000084 s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
Craig Tillerf53d9c82015-08-04 14:19:43 -070085 try:
86 s.bind(('localhost', i))
Craig Tillerc20b19d2015-09-22 13:06:06 -070087 req.log_message("found available port %d" % i)
Craig Tillerf53d9c82015-08-04 14:19:43 -070088 pool.append(i)
89 except:
90 pass # we really don't care about failures
91 finally:
92 s.close()
93
94
Craig Tillerc20b19d2015-09-22 13:06:06 -070095def allocate_port(req):
Craig Tillerf53d9c82015-08-04 14:19:43 -070096 global pool
97 global in_use
Craig Tillerae322af2015-09-13 18:41:21 +000098 max_timeout = 600
99 while not pool:
Craig Tillerc20b19d2015-09-22 13:06:06 -0700100 refill_pool(max_timeout, req)
Craig Tillerae322af2015-09-13 18:41:21 +0000101 if not pool:
Craig Tillerc20b19d2015-09-22 13:06:06 -0700102 req.log_message("failed to find ports: retrying soon")
Craig Tillerae322af2015-09-13 18:41:21 +0000103 time.sleep(1)
104 max_timeout /= 2
Craig Tillerf53d9c82015-08-04 14:19:43 -0700105 port = pool[0]
106 pool = pool[1:]
107 in_use[port] = time.time()
108 return port
109
110
Craig Tilleref125592015-08-05 07:41:35 -0700111keep_running = True
112
113
Craig Tillerf53d9c82015-08-04 14:19:43 -0700114class Handler(BaseHTTPServer.BaseHTTPRequestHandler):
Ken Payson189d6852016-07-09 15:58:18 -0700115
116 def setup(self):
117 # If the client is unreachable for 5 seconds, close the connection
118 self.timeout = 5
119 BaseHTTPServer.BaseHTTPRequestHandler.setup(self)
Craig Tillerf53d9c82015-08-04 14:19:43 -0700120
121 def do_GET(self):
Craig Tilleref125592015-08-05 07:41:35 -0700122 global keep_running
Craig Tillerf53d9c82015-08-04 14:19:43 -0700123 if self.path == '/get':
124 # allocate a new port, it will stay bound for ten minutes and until
125 # it's unused
126 self.send_response(200)
127 self.send_header('Content-Type', 'text/plain')
128 self.end_headers()
Craig Tillerc20b19d2015-09-22 13:06:06 -0700129 p = allocate_port(self)
Craig Tillerf53d9c82015-08-04 14:19:43 -0700130 self.log_message('allocated port %d' % p)
131 self.wfile.write('%d' % p)
Craig Tillerae322af2015-09-13 18:41:21 +0000132 elif self.path[0:6] == '/drop/':
133 self.send_response(200)
134 self.send_header('Content-Type', 'text/plain')
135 self.end_headers()
136 p = int(self.path[6:])
Craig Tillerd2c39712015-10-12 11:08:49 -0700137 if p in in_use:
138 del in_use[p]
139 pool.append(p)
140 self.log_message('drop known port %d' % p)
141 else:
142 self.log_message('drop unknown port %d' % p)
Craig Tillerfe4939f2015-10-06 12:55:36 -0700143 elif self.path == '/version_number':
Craig Tillerf53d9c82015-08-04 14:19:43 -0700144 # fetch a version string and the current process pid
145 self.send_response(200)
146 self.send_header('Content-Type', 'text/plain')
147 self.end_headers()
Craig Tilleref125592015-08-05 07:41:35 -0700148 self.wfile.write(_MY_VERSION)
Craig Tillerae322af2015-09-13 18:41:21 +0000149 elif self.path == '/dump':
Jan Tattermusch13e65df2015-09-21 09:30:49 -0700150 # yaml module is not installed on Macs and Windows machines by default
151 # so we import it lazily (/dump action is only used for debugging)
152 import yaml
Craig Tillerae322af2015-09-13 18:41:21 +0000153 self.send_response(200)
154 self.send_header('Content-Type', 'text/plain')
155 self.end_headers()
156 now = time.time()
siddharthshukla0589e532016-07-07 16:08:01 +0200157 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 -0700158 elif self.path == '/quitquitquit':
Craig Tilleref125592015-08-05 07:41:35 -0700159 self.send_response(200)
160 self.end_headers()
161 keep_running = False
Craig Tillerf53d9c82015-08-04 14:19:43 -0700162
163
Craig Tilleref125592015-08-05 07:41:35 -0700164httpd = BaseHTTPServer.HTTPServer(('', args.port), Handler)
165while keep_running:
166 httpd.handle_request()
Craig Tillerf0a293e2015-10-12 10:05:50 -0700167 sys.stderr.flush()
Craig Tilleref125592015-08-05 07:41:35 -0700168
siddharthshukla0589e532016-07-07 16:08:01 +0200169print('done')