blob: 3f9aaa4f4d0a74616e24bf7b5543a74e74f0a818 [file] [log] [blame]
Roger Meier41ad4342015-03-24 22:30:40 +01001#
2# Licensed to the Apache Software Foundation (ASF) under one
3# or more contributor license agreements. See the NOTICE file
4# distributed with this work for additional information
5# regarding copyright ownership. The ASF licenses this file
6# to you under the Apache License, Version 2.0 (the
7# "License"); you may not use this file except in compliance
8# with the License. You may obtain a copy of the License at
9#
10# http://www.apache.org/licenses/LICENSE-2.0
11#
12# Unless required by applicable law or agreed to in writing,
13# software distributed under the License is distributed on an
14# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
15# KIND, either express or implied. See the License for the
16# specific language governing permissions and limitations
17# under the License.
18#
19
20import contextlib
21import multiprocessing
22import multiprocessing.managers
23import os
24import platform
25import random
Roger Meier41ad4342015-03-24 22:30:40 +010026import signal
Nobuaki Sukegawaa6ab1f52015-11-28 15:04:39 +090027import socket
Roger Meier41ad4342015-03-24 22:30:40 +010028import subprocess
Nobuaki Sukegawaa6ab1f52015-11-28 15:04:39 +090029import sys
Roger Meier41ad4342015-03-24 22:30:40 +010030import threading
31import time
Roger Meier41ad4342015-03-24 22:30:40 +010032
Nobuaki Sukegawa2de27002015-11-22 01:13:48 +090033from .compat import str_join
34from .test import TestEntry, domain_socket_path
35from .report import ExecReporter, SummaryReporter
Roger Meier41ad4342015-03-24 22:30:40 +010036
37RESULT_TIMEOUT = 128
38RESULT_ERROR = 64
39
40
41class ExecutionContext(object):
Nobuaki Sukegawa10308cb2016-02-03 01:57:03 +090042 def __init__(self, cmd, cwd, env, report):
43 self._log = multiprocessing.get_logger()
44 self.report = report
45 self.cmd = cmd
46 self.cwd = cwd
47 self.env = env
48 self.timer = None
49 self.expired = False
50 self.killed = False
Nobuaki Sukegawa59310f52016-02-18 01:41:46 +090051 self.proc = None
Roger Meier41ad4342015-03-24 22:30:40 +010052
Nobuaki Sukegawa10308cb2016-02-03 01:57:03 +090053 def _expire(self):
54 self._log.info('Timeout')
55 self.expired = True
56 self.kill()
Roger Meier41ad4342015-03-24 22:30:40 +010057
Nobuaki Sukegawa10308cb2016-02-03 01:57:03 +090058 def kill(self):
59 self._log.debug('Killing process : %d' % self.proc.pid)
60 self.killed = True
61 if platform.system() != 'Windows':
62 try:
63 os.killpg(self.proc.pid, signal.SIGKILL)
64 except Exception:
65 self._log.info('Failed to kill process group', exc_info=sys.exc_info())
66 try:
67 self.proc.kill()
68 except Exception:
69 self._log.info('Failed to kill process', exc_info=sys.exc_info())
Roger Meier41ad4342015-03-24 22:30:40 +010070
Nobuaki Sukegawa10308cb2016-02-03 01:57:03 +090071 def _popen_args(self):
72 args = {
73 'cwd': self.cwd,
74 'env': self.env,
75 'stdout': self.report.out,
76 'stderr': subprocess.STDOUT,
77 }
78 # make sure child processes doesn't remain after killing
79 if platform.system() == 'Windows':
80 DETACHED_PROCESS = 0x00000008
81 args.update(creationflags=DETACHED_PROCESS | subprocess.CREATE_NEW_PROCESS_GROUP)
82 else:
83 args.update(preexec_fn=os.setsid)
84 return args
Roger Meier41ad4342015-03-24 22:30:40 +010085
Nobuaki Sukegawa10308cb2016-02-03 01:57:03 +090086 def start(self, timeout=0):
87 joined = str_join(' ', self.cmd)
88 self._log.debug('COMMAND: %s', joined)
89 self._log.debug('WORKDIR: %s', self.cwd)
90 self._log.debug('LOGFILE: %s', self.report.logpath)
91 self.report.begin()
92 self.proc = subprocess.Popen(self.cmd, **self._popen_args())
93 if timeout > 0:
94 self.timer = threading.Timer(timeout, self._expire)
95 self.timer.start()
96 return self._scoped()
Roger Meier41ad4342015-03-24 22:30:40 +010097
Nobuaki Sukegawa10308cb2016-02-03 01:57:03 +090098 @contextlib.contextmanager
99 def _scoped(self):
100 yield self
101 self._log.debug('Killing scoped process')
102 if self.proc.poll() is None:
103 self.kill()
104 self.report.killed()
105 else:
106 self._log.debug('Process died unexpectedly')
107 self.report.died()
Roger Meier41ad4342015-03-24 22:30:40 +0100108
Nobuaki Sukegawa10308cb2016-02-03 01:57:03 +0900109 def wait(self):
110 self.proc.communicate()
111 if self.timer:
112 self.timer.cancel()
113 self.report.end(self.returncode)
Roger Meier41ad4342015-03-24 22:30:40 +0100114
Nobuaki Sukegawa10308cb2016-02-03 01:57:03 +0900115 @property
116 def returncode(self):
117 return self.proc.returncode if self.proc else None
Roger Meier41ad4342015-03-24 22:30:40 +0100118
119
Nobuaki Sukegawa378b7272016-01-03 17:04:50 +0900120def exec_context(port, logdir, test, prog):
Nobuaki Sukegawa10308cb2016-02-03 01:57:03 +0900121 report = ExecReporter(logdir, test, prog)
122 prog.build_command(port)
123 return ExecutionContext(prog.command, prog.workdir, prog.env, report)
Roger Meier41ad4342015-03-24 22:30:40 +0100124
125
Nobuaki Sukegawa5e432ec2016-01-24 01:34:29 +0900126def run_test(testdir, logdir, test_dict, max_retry, async=True):
Nobuaki Sukegawa59310f52016-02-18 01:41:46 +0900127 logger = multiprocessing.get_logger()
128
129 def ensure_socket_open(proc, port, max_delay):
130 sleeped = 0.1
131 time.sleep(sleeped)
Nobuaki Sukegawa59310f52016-02-18 01:41:46 +0900132 sleep_step = 0.2
Nobuaki Sukegawae9b32342016-02-27 03:44:02 +0900133 while True:
134 # Create sockets every iteration because refused sockets cannot be
135 # reused on some systems.
136 sock4 = socket.socket()
137 sock6 = socket.socket(family=socket.AF_INET6)
138 try:
139 if sock4.connect_ex(('127.0.0.1', port)) == 0 \
140 or sock6.connect_ex(('::1', port)) == 0:
141 return True
Nobuaki Sukegawa59310f52016-02-18 01:41:46 +0900142 if proc.poll() is not None:
143 logger.warn('server process is exited')
144 return False
145 if sleeped > max_delay:
146 logger.warn('sleeped for %f seconds but server port is not open' % sleeped)
147 return False
148 time.sleep(sleep_step)
149 sleeped += sleep_step
Nobuaki Sukegawae9b32342016-02-27 03:44:02 +0900150 finally:
151 sock4.close()
152 sock6.close()
153 logger.debug('waited %f sec for server port open' % sleeped)
154 return True
Nobuaki Sukegawa59310f52016-02-18 01:41:46 +0900155
Nobuaki Sukegawa10308cb2016-02-03 01:57:03 +0900156 try:
Nobuaki Sukegawa10308cb2016-02-03 01:57:03 +0900157 max_bind_retry = 3
158 retry_count = 0
159 bind_retry_count = 0
160 test = TestEntry(testdir, **test_dict)
161 while True:
162 if stop.is_set():
163 logger.debug('Skipping because shutting down')
164 return (retry_count, None)
165 logger.debug('Start')
166 with PortAllocator.alloc_port_scoped(ports, test.socket) as port:
167 logger.debug('Start with port %d' % port)
168 sv = exec_context(port, logdir, test, test.server)
169 cl = exec_context(port, logdir, test, test.client)
Roger Meier41ad4342015-03-24 22:30:40 +0100170
Nobuaki Sukegawa10308cb2016-02-03 01:57:03 +0900171 logger.debug('Starting server')
172 with sv.start():
Nobuaki Sukegawa59310f52016-02-18 01:41:46 +0900173 if test.socket in ('domain', 'abstract'):
174 time.sleep(0.1)
Nobuaki Sukegawa103974e2016-02-28 10:07:30 +0900175 port_ok = True
Nobuaki Sukegawa59310f52016-02-18 01:41:46 +0900176 else:
Nobuaki Sukegawa103974e2016-02-28 10:07:30 +0900177 port_ok = ensure_socket_open(sv.proc, port, test.delay)
178 if port_ok:
179 connect_retry_count = 0
180 max_connect_retry = 3
181 connect_retry_wait = 0.5
182 while True:
183 if sv.proc.poll() is not None:
184 logger.info('not starting client because server process is absent')
185 break
186 logger.debug('Starting client')
187 cl.start(test.timeout)
188 logger.debug('Waiting client')
189 cl.wait()
190 if not cl.report.maybe_false_positive() or connect_retry_count >= max_connect_retry:
191 if connect_retry_count > 0 and connect_retry_count < max_connect_retry:
192 logger.warn('[%s]: Connected after %d retry (%.2f sec each)' % (test.server.name, connect_retry_count, connect_retry_wait))
193 # Wait for 50ms to see if server does not die at the end.
194 time.sleep(0.05)
195 break
196 logger.debug('Server may not be ready, waiting %.2f second...' % connect_retry_wait)
197 time.sleep(connect_retry_wait)
198 connect_retry_count += 1
Roger Meier41ad4342015-03-24 22:30:40 +0100199
Nobuaki Sukegawa10308cb2016-02-03 01:57:03 +0900200 if sv.report.maybe_false_positive() and bind_retry_count < max_bind_retry:
201 logger.warn('[%s]: Detected socket bind failure, retrying...', test.server.name)
202 bind_retry_count += 1
203 else:
204 if cl.expired:
205 result = RESULT_TIMEOUT
Nobuaki Sukegawa10308cb2016-02-03 01:57:03 +0900206 else:
Nobuaki Sukegawa59310f52016-02-18 01:41:46 +0900207 result = cl.proc.returncode if cl.proc else RESULT_ERROR
208 if not sv.killed:
209 # Server died without being killed.
210 result |= RESULT_ERROR
Nobuaki Sukegawa5e432ec2016-01-24 01:34:29 +0900211
Nobuaki Sukegawa10308cb2016-02-03 01:57:03 +0900212 if result == 0 or retry_count >= max_retry:
213 return (retry_count, result)
214 else:
215 logger.info('[%s-%s]: test failed, retrying...', test.server.name, test.client.name)
216 retry_count += 1
Nobuaki Sukegawa59310f52016-02-18 01:41:46 +0900217 except Exception:
218 if not async:
219 raise
220 logger.warn('Error executing [%s]', test.name, exc_info=True)
221 return (retry_count, RESULT_ERROR)
222 except:
223 logger.info('Interrupted execution', exc_info=True)
Nobuaki Sukegawa10308cb2016-02-03 01:57:03 +0900224 if not async:
225 raise
226 stop.set()
Nobuaki Sukegawa10308cb2016-02-03 01:57:03 +0900227 return (retry_count, RESULT_ERROR)
Roger Meier41ad4342015-03-24 22:30:40 +0100228
229
230class PortAllocator(object):
Nobuaki Sukegawa10308cb2016-02-03 01:57:03 +0900231 def __init__(self):
232 self._log = multiprocessing.get_logger()
233 self._lock = multiprocessing.Lock()
234 self._ports = set()
235 self._dom_ports = set()
236 self._last_alloc = 0
Roger Meier41ad4342015-03-24 22:30:40 +0100237
Nobuaki Sukegawa10308cb2016-02-03 01:57:03 +0900238 def _get_tcp_port(self):
239 sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
Nobuaki Sukegawa59310f52016-02-18 01:41:46 +0900240 sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
241 sock.bind(('', 0))
Nobuaki Sukegawa10308cb2016-02-03 01:57:03 +0900242 port = sock.getsockname()[1]
243 self._lock.acquire()
244 try:
245 ok = port not in self._ports
246 if ok:
247 self._ports.add(port)
248 self._last_alloc = time.time()
249 finally:
250 self._lock.release()
251 sock.close()
252 return port if ok else self._get_tcp_port()
Roger Meier41ad4342015-03-24 22:30:40 +0100253
Nobuaki Sukegawa10308cb2016-02-03 01:57:03 +0900254 def _get_domain_port(self):
255 port = random.randint(1024, 65536)
256 self._lock.acquire()
257 try:
258 ok = port not in self._dom_ports
259 if ok:
260 self._dom_ports.add(port)
261 finally:
262 self._lock.release()
263 return port if ok else self._get_domain_port()
Roger Meier41ad4342015-03-24 22:30:40 +0100264
Nobuaki Sukegawa10308cb2016-02-03 01:57:03 +0900265 def alloc_port(self, socket_type):
266 if socket_type in ('domain', 'abstract'):
267 return self._get_domain_port()
268 else:
269 return self._get_tcp_port()
Roger Meier41ad4342015-03-24 22:30:40 +0100270
Nobuaki Sukegawa10308cb2016-02-03 01:57:03 +0900271 # static method for inter-process invokation
272 @staticmethod
273 @contextlib.contextmanager
274 def alloc_port_scoped(allocator, socket_type):
275 port = allocator.alloc_port(socket_type)
276 yield port
277 allocator.free_port(socket_type, port)
Roger Meier41ad4342015-03-24 22:30:40 +0100278
Nobuaki Sukegawa10308cb2016-02-03 01:57:03 +0900279 def free_port(self, socket_type, port):
280 self._log.debug('free_port')
281 self._lock.acquire()
282 try:
283 if socket_type == 'domain':
284 self._dom_ports.remove(port)
285 path = domain_socket_path(port)
286 if os.path.exists(path):
287 os.remove(path)
288 elif socket_type == 'abstract':
289 self._dom_ports.remove(port)
290 else:
291 self._ports.remove(port)
292 except IOError:
293 self._log.info('Error while freeing port', exc_info=sys.exc_info())
294 finally:
295 self._lock.release()
Roger Meier41ad4342015-03-24 22:30:40 +0100296
297
298class NonAsyncResult(object):
Nobuaki Sukegawa10308cb2016-02-03 01:57:03 +0900299 def __init__(self, value):
300 self._value = value
Roger Meier41ad4342015-03-24 22:30:40 +0100301
Nobuaki Sukegawa10308cb2016-02-03 01:57:03 +0900302 def get(self, timeout=None):
303 return self._value
Roger Meier41ad4342015-03-24 22:30:40 +0100304
Nobuaki Sukegawa10308cb2016-02-03 01:57:03 +0900305 def wait(self, timeout=None):
306 pass
Roger Meier41ad4342015-03-24 22:30:40 +0100307
Nobuaki Sukegawa10308cb2016-02-03 01:57:03 +0900308 def ready(self):
309 return True
Roger Meier41ad4342015-03-24 22:30:40 +0100310
Nobuaki Sukegawa10308cb2016-02-03 01:57:03 +0900311 def successful(self):
312 return self._value == 0
Roger Meier41ad4342015-03-24 22:30:40 +0100313
314
315class TestDispatcher(object):
Nobuaki Sukegawa10308cb2016-02-03 01:57:03 +0900316 def __init__(self, testdir, basedir, logdir_rel, concurrency):
317 self._log = multiprocessing.get_logger()
318 self.testdir = testdir
319 self._report = SummaryReporter(basedir, logdir_rel, concurrency > 1)
320 self.logdir = self._report.testdir
321 # seems needed for python 2.x to handle keyboard interrupt
322 self._stop = multiprocessing.Event()
323 self._async = concurrency > 1
324 if not self._async:
325 self._pool = None
326 global stop
327 global ports
328 stop = self._stop
329 ports = PortAllocator()
330 else:
331 self._m = multiprocessing.managers.BaseManager()
332 self._m.register('ports', PortAllocator)
333 self._m.start()
334 self._pool = multiprocessing.Pool(concurrency, self._pool_init, (self._m.address,))
335 self._log.debug(
336 'TestDispatcher started with %d concurrent jobs' % concurrency)
Roger Meier41ad4342015-03-24 22:30:40 +0100337
Nobuaki Sukegawa10308cb2016-02-03 01:57:03 +0900338 def _pool_init(self, address):
339 global stop
340 global m
341 global ports
342 stop = self._stop
343 m = multiprocessing.managers.BaseManager(address)
344 m.connect()
345 ports = m.ports()
Roger Meier41ad4342015-03-24 22:30:40 +0100346
Nobuaki Sukegawa10308cb2016-02-03 01:57:03 +0900347 def _dispatch_sync(self, test, cont, max_retry):
348 r = run_test(self.testdir, self.logdir, test, max_retry, False)
349 cont(r)
350 return NonAsyncResult(r)
Roger Meier41ad4342015-03-24 22:30:40 +0100351
Nobuaki Sukegawa10308cb2016-02-03 01:57:03 +0900352 def _dispatch_async(self, test, cont, max_retry):
353 self._log.debug('_dispatch_async')
354 return self._pool.apply_async(func=run_test, args=(self.testdir, self.logdir, test, max_retry), callback=cont)
Roger Meier41ad4342015-03-24 22:30:40 +0100355
Nobuaki Sukegawa10308cb2016-02-03 01:57:03 +0900356 def dispatch(self, test, max_retry):
357 index = self._report.add_test(test)
Roger Meier41ad4342015-03-24 22:30:40 +0100358
Nobuaki Sukegawa10308cb2016-02-03 01:57:03 +0900359 def cont(result):
360 if not self._stop.is_set():
Nobuaki Sukegawa59310f52016-02-18 01:41:46 +0900361 if result and len(result) == 2:
362 retry_count, returncode = result
363 else:
364 retry_count = 0
365 returncode = RESULT_ERROR
Nobuaki Sukegawa10308cb2016-02-03 01:57:03 +0900366 self._log.debug('freeing port')
367 self._log.debug('adding result')
368 self._report.add_result(index, returncode, returncode == RESULT_TIMEOUT, retry_count)
369 self._log.debug('finish continuation')
370 fn = self._dispatch_async if self._async else self._dispatch_sync
371 return fn(test, cont, max_retry)
Roger Meier41ad4342015-03-24 22:30:40 +0100372
Nobuaki Sukegawa10308cb2016-02-03 01:57:03 +0900373 def wait(self):
374 if self._async:
375 self._pool.close()
376 self._pool.join()
377 self._m.shutdown()
378 return self._report.end()
Roger Meier41ad4342015-03-24 22:30:40 +0100379
Nobuaki Sukegawa10308cb2016-02-03 01:57:03 +0900380 def terminate(self):
381 self._stop.set()
382 if self._async:
383 self._pool.terminate()
384 self._pool.join()
385 self._m.shutdown()