2017-09-15 06:24:41 +00:00
|
|
|
|
2018-03-29 13:09:55 +00:00
|
|
|
import logging
|
2017-09-15 06:24:41 +00:00
|
|
|
import os
|
2017-09-16 23:57:14 +00:00
|
|
|
import random
|
2017-10-15 19:31:10 +00:00
|
|
|
import re
|
2019-01-23 12:44:08 +00:00
|
|
|
import signal
|
2017-10-15 19:31:10 +00:00
|
|
|
import socket
|
2018-06-24 00:55:35 +00:00
|
|
|
import subprocess
|
2017-09-15 06:24:41 +00:00
|
|
|
import sys
|
2018-11-03 15:01:45 +00:00
|
|
|
import threading
|
2017-10-15 19:31:10 +00:00
|
|
|
import time
|
2018-11-03 15:01:45 +00:00
|
|
|
import traceback
|
2017-09-15 06:24:41 +00:00
|
|
|
|
2017-11-12 12:42:27 +00:00
|
|
|
import unittest2
|
2017-11-11 22:59:38 +00:00
|
|
|
|
2018-03-29 14:39:54 +00:00
|
|
|
import mitogen.core
|
2018-11-03 13:28:37 +00:00
|
|
|
import mitogen.fork
|
2017-09-15 06:24:41 +00:00
|
|
|
import mitogen.master
|
2018-03-29 07:25:11 +00:00
|
|
|
import mitogen.utils
|
|
|
|
|
2018-10-29 15:23:57 +00:00
|
|
|
try:
|
|
|
|
import faulthandler
|
|
|
|
except ImportError:
|
2018-11-04 19:49:17 +00:00
|
|
|
faulthandler = None
|
2018-10-29 15:23:57 +00:00
|
|
|
|
2018-04-17 16:40:45 +00:00
|
|
|
try:
|
|
|
|
import urlparse
|
|
|
|
except ImportError:
|
|
|
|
import urllib.parse as urlparse
|
|
|
|
|
|
|
|
try:
|
|
|
|
from cStringIO import StringIO
|
|
|
|
except ImportError:
|
|
|
|
from io import StringIO
|
|
|
|
|
2019-01-23 12:44:08 +00:00
|
|
|
try:
|
|
|
|
BaseException
|
|
|
|
except NameError:
|
|
|
|
BaseException = Exception
|
|
|
|
|
2017-09-15 06:24:41 +00:00
|
|
|
|
2018-07-04 17:38:18 +00:00
|
|
|
LOG = logging.getLogger(__name__)
|
2017-09-15 06:24:41 +00:00
|
|
|
DATA_DIR = os.path.join(os.path.dirname(__file__), 'data')
|
2019-06-02 17:56:56 +00:00
|
|
|
MODS_DIR = os.path.join(DATA_DIR, 'importer')
|
|
|
|
|
|
|
|
sys.path.append(DATA_DIR)
|
|
|
|
sys.path.append(MODS_DIR)
|
|
|
|
|
2017-09-15 06:24:41 +00:00
|
|
|
|
2018-05-08 13:32:32 +00:00
|
|
|
if mitogen.is_master:
|
|
|
|
mitogen.utils.log_to_file()
|
2017-09-15 06:24:41 +00:00
|
|
|
|
2018-10-29 15:23:57 +00:00
|
|
|
if faulthandler is not None:
|
|
|
|
faulthandler.enable()
|
|
|
|
|
2017-09-15 06:24:41 +00:00
|
|
|
|
2018-11-03 13:28:37 +00:00
|
|
|
def get_fd_count():
|
|
|
|
"""
|
|
|
|
Return the number of FDs open by this process.
|
|
|
|
"""
|
2018-11-04 11:57:50 +00:00
|
|
|
import psutil
|
2018-11-03 13:28:37 +00:00
|
|
|
return psutil.Process().num_fds()
|
|
|
|
|
|
|
|
|
2017-09-15 06:24:41 +00:00
|
|
|
def data_path(suffix):
|
2017-09-17 15:03:43 +00:00
|
|
|
path = os.path.join(DATA_DIR, suffix)
|
|
|
|
if path.endswith('.key'):
|
|
|
|
# SSH is funny about private key permissions.
|
2018-04-17 16:40:45 +00:00
|
|
|
os.chmod(path, int('0600', 8))
|
2017-09-17 15:03:43 +00:00
|
|
|
return path
|
2017-09-15 06:24:41 +00:00
|
|
|
|
|
|
|
|
2018-06-24 00:55:35 +00:00
|
|
|
def subprocess__check_output(*popenargs, **kwargs):
|
|
|
|
# Missing from 2.6.
|
|
|
|
process = subprocess.Popen(stdout=subprocess.PIPE, *popenargs, **kwargs)
|
|
|
|
output, _ = process.communicate()
|
|
|
|
retcode = process.poll()
|
|
|
|
if retcode:
|
|
|
|
cmd = kwargs.get("args")
|
|
|
|
if cmd is None:
|
|
|
|
cmd = popenargs[0]
|
2018-06-24 18:30:16 +00:00
|
|
|
raise subprocess.CalledProcessError(retcode, cmd)
|
2018-06-24 00:55:35 +00:00
|
|
|
return output
|
|
|
|
|
2019-01-23 12:44:08 +00:00
|
|
|
|
|
|
|
def Popen__terminate(proc):
|
|
|
|
os.kill(proc.pid, signal.SIGTERM)
|
|
|
|
|
|
|
|
|
2018-06-24 18:30:16 +00:00
|
|
|
if hasattr(subprocess, 'check_output'):
|
|
|
|
subprocess__check_output = subprocess.check_output
|
|
|
|
|
2019-01-23 12:44:08 +00:00
|
|
|
if hasattr(subprocess.Popen, 'terminate'):
|
|
|
|
Popen__terminate = subprocess.Popen.terminate
|
|
|
|
|
2018-06-24 00:55:35 +00:00
|
|
|
|
2017-10-15 19:31:10 +00:00
|
|
|
def wait_for_port(
|
|
|
|
host,
|
|
|
|
port,
|
|
|
|
pattern=None,
|
|
|
|
connect_timeout=0.5,
|
|
|
|
receive_timeout=0.5,
|
|
|
|
overall_timeout=5.0,
|
|
|
|
sleep=0.1,
|
|
|
|
):
|
|
|
|
"""Attempt to connect to host/port, for upto overall_timeout seconds.
|
|
|
|
If a regex pattern is supplied try to find it in the initial data.
|
|
|
|
Return None on success, or raise on error.
|
|
|
|
"""
|
|
|
|
start = time.time()
|
|
|
|
end = start + overall_timeout
|
|
|
|
addr = (host, port)
|
|
|
|
|
|
|
|
while time.time() < end:
|
|
|
|
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
|
|
|
|
sock.settimeout(connect_timeout)
|
|
|
|
try:
|
|
|
|
sock.connect(addr)
|
|
|
|
except socket.error:
|
|
|
|
# Failed to connect. So wait then retry.
|
|
|
|
time.sleep(sleep)
|
|
|
|
continue
|
|
|
|
|
|
|
|
if not pattern:
|
|
|
|
# Success: We connected & there's no banner check to perform.
|
|
|
|
sock.shutdown(socket.SHUTD_RDWR)
|
|
|
|
sock.close()
|
|
|
|
return
|
|
|
|
|
|
|
|
sock.settimeout(receive_timeout)
|
2018-04-17 16:40:45 +00:00
|
|
|
data = mitogen.core.b('')
|
2017-10-15 19:31:10 +00:00
|
|
|
found = False
|
|
|
|
while time.time() < end:
|
|
|
|
try:
|
|
|
|
resp = sock.recv(1024)
|
|
|
|
except socket.timeout:
|
|
|
|
# Server stayed up, but had no data. Retry the recv().
|
|
|
|
continue
|
|
|
|
|
|
|
|
if not resp:
|
|
|
|
# Server went away. Wait then retry the connection.
|
|
|
|
time.sleep(sleep)
|
|
|
|
break
|
|
|
|
|
|
|
|
data += resp
|
2018-04-17 16:40:45 +00:00
|
|
|
if re.search(mitogen.core.b(pattern), data):
|
2017-10-15 19:31:10 +00:00
|
|
|
found = True
|
|
|
|
break
|
|
|
|
|
2017-10-30 12:07:10 +00:00
|
|
|
try:
|
|
|
|
sock.shutdown(socket.SHUT_RDWR)
|
2018-04-17 16:40:45 +00:00
|
|
|
except socket.error:
|
|
|
|
e = sys.exc_info()[1]
|
|
|
|
# On Mac OS X - a BSD variant - the above code only succeeds if the
|
|
|
|
# operating system thinks that the socket is still open when
|
|
|
|
# shutdown() is invoked. If Python is too slow and the FIN packet
|
|
|
|
# arrives before that statement can be reached, then OS X kills the
|
|
|
|
# sock.shutdown() statement with:
|
2017-10-30 12:07:10 +00:00
|
|
|
#
|
|
|
|
# socket.error: [Errno 57] Socket is not connected
|
|
|
|
#
|
2018-04-17 16:40:45 +00:00
|
|
|
# Protect shutdown() with a try...except that catches the
|
|
|
|
# socket.error, test to make sure Errno is right, and ignore it if
|
|
|
|
# Errno matches.
|
2017-10-30 12:07:10 +00:00
|
|
|
if e.errno == 57:
|
|
|
|
pass
|
|
|
|
else:
|
|
|
|
raise
|
2017-10-15 19:31:10 +00:00
|
|
|
sock.close()
|
|
|
|
|
|
|
|
if found:
|
|
|
|
# Success: We received the banner & found the desired pattern
|
|
|
|
return
|
|
|
|
else:
|
|
|
|
# Failure: The overall timeout expired
|
|
|
|
if pattern:
|
|
|
|
raise socket.timeout('Timed out while searching for %r from %s:%s'
|
|
|
|
% (pattern, host, port))
|
|
|
|
else:
|
|
|
|
raise socket.timeout('Timed out while connecting to %s:%s'
|
|
|
|
% (host, port))
|
|
|
|
|
|
|
|
|
2018-03-29 14:39:54 +00:00
|
|
|
def sync_with_broker(broker, timeout=10.0):
|
|
|
|
"""
|
|
|
|
Insert a synchronization barrier between the calling thread and the Broker
|
|
|
|
thread, ensuring it has completed at least one full IO loop before
|
|
|
|
returning.
|
|
|
|
|
|
|
|
Used to block while asynchronous stuff (like defer()) happens on the
|
|
|
|
broker.
|
|
|
|
"""
|
|
|
|
sem = mitogen.core.Latch()
|
|
|
|
broker.defer(sem.put, None)
|
2019-08-07 18:52:24 +00:00
|
|
|
sem.get(timeout=timeout)
|
2018-03-29 14:39:54 +00:00
|
|
|
|
|
|
|
|
2018-11-03 15:01:45 +00:00
|
|
|
def log_fd_calls():
|
|
|
|
mypid = os.getpid()
|
|
|
|
l = threading.Lock()
|
|
|
|
real_pipe = os.pipe
|
|
|
|
def pipe():
|
2019-01-23 12:44:08 +00:00
|
|
|
l.acquire()
|
|
|
|
try:
|
2018-11-03 15:01:45 +00:00
|
|
|
rv = real_pipe()
|
|
|
|
if mypid == os.getpid():
|
2018-11-04 11:57:50 +00:00
|
|
|
sys.stdout.write('\n%s\n' % (rv,))
|
2018-11-03 15:01:45 +00:00
|
|
|
traceback.print_stack(limit=3)
|
2018-11-04 11:57:50 +00:00
|
|
|
sys.stdout.write('\n')
|
2018-11-03 15:01:45 +00:00
|
|
|
return rv
|
2019-01-23 12:44:08 +00:00
|
|
|
finally:
|
|
|
|
l.release()
|
|
|
|
|
2018-11-03 15:48:31 +00:00
|
|
|
os.pipe = pipe
|
|
|
|
|
|
|
|
real_socketpair = socket.socketpair
|
|
|
|
def socketpair(*args):
|
2019-01-23 12:44:08 +00:00
|
|
|
l.acquire()
|
|
|
|
try:
|
2018-11-03 15:48:31 +00:00
|
|
|
rv = real_socketpair(*args)
|
|
|
|
if mypid == os.getpid():
|
2018-11-04 11:57:50 +00:00
|
|
|
sys.stdout.write('\n%s -> %s\n' % (args, rv))
|
2018-11-03 15:48:31 +00:00
|
|
|
traceback.print_stack(limit=3)
|
2018-11-04 11:57:50 +00:00
|
|
|
sys.stdout.write('\n')
|
2018-11-03 15:48:31 +00:00
|
|
|
return rv
|
2019-01-23 12:44:08 +00:00
|
|
|
finally:
|
|
|
|
l.release()
|
|
|
|
|
2018-11-03 15:48:31 +00:00
|
|
|
socket.socketpair = socketpair
|
2018-11-03 15:01:45 +00:00
|
|
|
|
|
|
|
real_dup2 = os.dup2
|
|
|
|
def dup2(*args):
|
2019-01-23 12:44:08 +00:00
|
|
|
l.acquire()
|
|
|
|
try:
|
2018-11-03 15:01:45 +00:00
|
|
|
real_dup2(*args)
|
|
|
|
if mypid == os.getpid():
|
2018-11-04 11:57:50 +00:00
|
|
|
sys.stdout.write('\n%s\n' % (args,))
|
2018-11-03 15:01:45 +00:00
|
|
|
traceback.print_stack(limit=3)
|
2018-11-04 11:57:50 +00:00
|
|
|
sys.stdout.write('\n')
|
2019-01-23 12:44:08 +00:00
|
|
|
finally:
|
|
|
|
l.release()
|
|
|
|
|
2018-11-03 15:48:31 +00:00
|
|
|
os.dup2 = dup2
|
2018-11-03 15:01:45 +00:00
|
|
|
|
|
|
|
real_dup = os.dup
|
|
|
|
def dup(*args):
|
2019-01-23 12:44:08 +00:00
|
|
|
l.acquire()
|
|
|
|
try:
|
2018-11-03 19:49:13 +00:00
|
|
|
rv = real_dup(*args)
|
2018-11-03 15:01:45 +00:00
|
|
|
if mypid == os.getpid():
|
2018-11-04 11:57:50 +00:00
|
|
|
sys.stdout.write('\n%s -> %s\n' % (args, rv))
|
2018-11-03 15:01:45 +00:00
|
|
|
traceback.print_stack(limit=3)
|
2018-11-04 11:57:50 +00:00
|
|
|
sys.stdout.write('\n')
|
2018-11-03 15:01:45 +00:00
|
|
|
return rv
|
2019-01-23 12:44:08 +00:00
|
|
|
finally:
|
|
|
|
l.release()
|
|
|
|
|
2018-11-03 15:01:45 +00:00
|
|
|
os.dup = dup
|
|
|
|
|
|
|
|
|
2018-10-02 20:06:00 +00:00
|
|
|
class CaptureStreamHandler(logging.StreamHandler):
|
|
|
|
def __init__(self, *args, **kwargs):
|
2018-10-26 12:22:33 +00:00
|
|
|
logging.StreamHandler.__init__(self, *args, **kwargs)
|
2018-10-02 20:06:00 +00:00
|
|
|
self.msgs = []
|
|
|
|
|
|
|
|
def emit(self, msg):
|
|
|
|
self.msgs.append(msg)
|
2018-10-26 12:22:33 +00:00
|
|
|
logging.StreamHandler.emit(self, msg)
|
2018-10-02 20:06:00 +00:00
|
|
|
|
|
|
|
|
2018-03-29 13:09:55 +00:00
|
|
|
class LogCapturer(object):
|
|
|
|
def __init__(self, name=None):
|
2018-04-17 16:40:45 +00:00
|
|
|
self.sio = StringIO()
|
2018-03-29 13:09:55 +00:00
|
|
|
self.logger = logging.getLogger(name)
|
2018-10-02 20:06:00 +00:00
|
|
|
self.handler = CaptureStreamHandler(self.sio)
|
2018-03-29 13:09:55 +00:00
|
|
|
self.old_propagate = self.logger.propagate
|
|
|
|
self.old_handlers = self.logger.handlers
|
2018-10-02 20:06:00 +00:00
|
|
|
self.old_level = self.logger.level
|
2018-03-29 13:09:55 +00:00
|
|
|
|
|
|
|
def start(self):
|
|
|
|
self.logger.handlers = [self.handler]
|
|
|
|
self.logger.propagate = False
|
2018-10-02 20:06:00 +00:00
|
|
|
self.logger.level = logging.DEBUG
|
|
|
|
|
|
|
|
def raw(self):
|
2019-03-11 22:04:32 +00:00
|
|
|
s = self.sio.getvalue()
|
|
|
|
# Python 2.x logging package hard-wires UTF-8 output.
|
|
|
|
if isinstance(s, mitogen.core.BytesType):
|
|
|
|
s = s.decode('utf-8')
|
|
|
|
return s
|
2018-10-02 20:06:00 +00:00
|
|
|
|
|
|
|
def msgs(self):
|
|
|
|
return self.handler.msgs
|
|
|
|
|
|
|
|
def __enter__(self):
|
|
|
|
self.start()
|
|
|
|
return self
|
|
|
|
|
|
|
|
def __exit__(self, _1, _2, _3):
|
|
|
|
self.stop()
|
2018-03-29 13:09:55 +00:00
|
|
|
|
|
|
|
def stop(self):
|
2018-10-02 20:06:00 +00:00
|
|
|
self.logger.level = self.old_level
|
2018-03-29 13:09:55 +00:00
|
|
|
self.logger.handlers = self.old_handlers
|
|
|
|
self.logger.propagate = self.old_propagate
|
2018-10-02 20:06:00 +00:00
|
|
|
return self.raw()
|
2018-03-29 13:09:55 +00:00
|
|
|
|
|
|
|
|
2017-11-12 12:42:27 +00:00
|
|
|
class TestCase(unittest2.TestCase):
|
2018-11-03 13:28:37 +00:00
|
|
|
@classmethod
|
|
|
|
def setUpClass(cls):
|
|
|
|
# This is done in setUpClass() so we have a chance to run before any
|
|
|
|
# Broker() instantiations in setUp() etc.
|
|
|
|
mitogen.fork.on_fork()
|
|
|
|
cls._fd_count_before = get_fd_count()
|
|
|
|
super(TestCase, cls).setUpClass()
|
|
|
|
|
2018-11-03 20:13:11 +00:00
|
|
|
ALLOWED_THREADS = set([
|
|
|
|
'MainThread',
|
|
|
|
'mitogen.master.join_thread_async'
|
|
|
|
])
|
|
|
|
|
2018-11-05 23:47:53 +00:00
|
|
|
def _teardown_check_threads(self):
|
2018-11-03 20:13:11 +00:00
|
|
|
counts = {}
|
|
|
|
for thread in threading.enumerate():
|
2019-01-23 12:44:08 +00:00
|
|
|
name = thread.getName()
|
2019-01-23 12:44:08 +00:00
|
|
|
# Python 2.4: enumerate() may return stopped threads.
|
|
|
|
assert (not thread.isAlive()) or name in self.ALLOWED_THREADS, \
|
2019-01-23 12:44:08 +00:00
|
|
|
'Found thread %r still running after tests.' % (name,)
|
|
|
|
counts[name] = counts.get(name, 0) + 1
|
2018-11-03 20:13:11 +00:00
|
|
|
|
|
|
|
for name in counts:
|
|
|
|
assert counts[name] == 1, \
|
2019-07-28 10:35:05 +00:00
|
|
|
'Found %d copies of thread %r running after tests.' % (
|
|
|
|
counts[name], name
|
|
|
|
)
|
2018-11-03 20:13:11 +00:00
|
|
|
|
2018-11-05 23:47:53 +00:00
|
|
|
def _teardown_check_fds(self):
|
2018-11-03 20:13:11 +00:00
|
|
|
mitogen.core.Latch._on_fork()
|
2018-11-05 23:47:53 +00:00
|
|
|
if get_fd_count() != self._fd_count_before:
|
2019-08-07 19:54:03 +00:00
|
|
|
import os; os.system('lsof +E -w -p %s' % (os.getpid(),))
|
2018-11-03 15:01:45 +00:00
|
|
|
assert 0, "%s leaked FDs. Count before: %s, after: %s" % (
|
2018-11-05 23:47:53 +00:00
|
|
|
self, self._fd_count_before, get_fd_count(),
|
2018-11-03 15:01:45 +00:00
|
|
|
)
|
2018-11-03 13:28:37 +00:00
|
|
|
|
2019-07-30 03:01:49 +00:00
|
|
|
# Some class fixtures (like Ansible MuxProcess) start persistent children
|
|
|
|
# for the duration of the class.
|
|
|
|
no_zombie_check = False
|
|
|
|
|
2019-03-14 19:31:39 +00:00
|
|
|
def _teardown_check_zombies(self):
|
2019-07-30 03:01:49 +00:00
|
|
|
if self.no_zombie_check:
|
|
|
|
return
|
|
|
|
|
2019-03-14 19:31:39 +00:00
|
|
|
try:
|
2019-07-23 16:30:46 +00:00
|
|
|
pid, status = os.waitpid(0, os.WNOHANG)
|
2019-03-14 19:31:39 +00:00
|
|
|
except OSError:
|
|
|
|
return # ECHILD
|
|
|
|
|
|
|
|
if pid:
|
|
|
|
assert 0, "%s failed to reap subprocess %d (status %d)." % (
|
|
|
|
self, pid, status
|
|
|
|
)
|
2019-07-23 13:04:22 +00:00
|
|
|
|
2019-07-30 03:01:49 +00:00
|
|
|
print('')
|
2019-07-23 13:04:22 +00:00
|
|
|
print('Children of unit test process:')
|
|
|
|
os.system('ps uww --ppid ' + str(os.getpid()))
|
2019-03-14 19:31:39 +00:00
|
|
|
assert 0, "%s leaked still-running subprocesses." % (self,)
|
|
|
|
|
2018-11-05 23:47:53 +00:00
|
|
|
def tearDown(self):
|
2019-03-14 19:31:39 +00:00
|
|
|
self._teardown_check_zombies()
|
2018-11-05 23:47:53 +00:00
|
|
|
self._teardown_check_threads()
|
|
|
|
self._teardown_check_fds()
|
|
|
|
super(TestCase, self).tearDown()
|
2018-11-03 20:13:11 +00:00
|
|
|
|
2017-09-27 08:26:19 +00:00
|
|
|
def assertRaises(self, exc, func, *args, **kwargs):
|
|
|
|
"""Like regular assertRaises, except return the exception that was
|
|
|
|
raised. Can't use context manager because tests must run on Python2.4"""
|
|
|
|
try:
|
|
|
|
func(*args, **kwargs)
|
2018-04-17 16:40:45 +00:00
|
|
|
except exc:
|
|
|
|
e = sys.exc_info()[1]
|
2017-09-27 08:26:19 +00:00
|
|
|
return e
|
2018-04-17 16:40:45 +00:00
|
|
|
except BaseException:
|
2018-07-04 17:38:18 +00:00
|
|
|
LOG.exception('Original exception')
|
2018-04-17 16:40:45 +00:00
|
|
|
e = sys.exc_info()[1]
|
2017-09-27 08:26:19 +00:00
|
|
|
assert 0, '%r raised %r, not %r' % (func, e, exc)
|
|
|
|
assert 0, '%r did not raise %r' % (func, exc)
|
|
|
|
|
|
|
|
|
2018-06-24 00:55:35 +00:00
|
|
|
def get_docker_host():
|
|
|
|
url = os.environ.get('DOCKER_HOST')
|
|
|
|
if url in (None, 'http+docker://localunixsocket'):
|
2018-04-05 19:24:11 +00:00
|
|
|
return 'localhost'
|
|
|
|
|
2018-06-24 00:55:35 +00:00
|
|
|
parsed = urlparse.urlparse(url)
|
2018-04-05 19:24:11 +00:00
|
|
|
return parsed.netloc.partition(':')[0]
|
|
|
|
|
|
|
|
|
2017-09-16 23:57:14 +00:00
|
|
|
class DockerizedSshDaemon(object):
|
2019-01-23 12:44:08 +00:00
|
|
|
mitogen_test_distro = os.environ.get('MITOGEN_TEST_DISTRO', 'debian')
|
|
|
|
if '-' in mitogen_test_distro:
|
|
|
|
distro, _py3 = mitogen_test_distro.split('-')
|
|
|
|
else:
|
|
|
|
distro = mitogen_test_distro
|
|
|
|
_py3 = None
|
|
|
|
|
|
|
|
if _py3 == 'py3':
|
|
|
|
python_path = '/usr/bin/python3'
|
|
|
|
else:
|
|
|
|
python_path = '/usr/bin/python'
|
|
|
|
|
2018-11-07 00:13:05 +00:00
|
|
|
image = 'mitogen/%s-test' % (distro,)
|
2018-04-16 13:24:39 +00:00
|
|
|
|
2018-06-24 00:55:35 +00:00
|
|
|
# 22/tcp -> 0.0.0.0:32771
|
|
|
|
PORT_RE = re.compile(r'([^/]+)/([^ ]+) -> ([^:]+):(.*)')
|
|
|
|
port = None
|
|
|
|
|
|
|
|
def _get_container_port(self):
|
|
|
|
s = subprocess__check_output(['docker', 'port', self.container_name])
|
2018-06-26 07:25:40 +00:00
|
|
|
for line in s.decode().splitlines():
|
2018-06-24 00:55:35 +00:00
|
|
|
dport, proto, baddr, bport = self.PORT_RE.match(line).groups()
|
|
|
|
if dport == '22' and proto == 'tcp':
|
|
|
|
self.port = int(bport)
|
|
|
|
|
2017-09-16 23:57:14 +00:00
|
|
|
self.host = self.get_host()
|
2018-06-24 00:55:35 +00:00
|
|
|
if self.port is None:
|
|
|
|
raise ValueError('could not find SSH port in: %r' % (s,))
|
|
|
|
|
|
|
|
def start_container(self):
|
2019-08-03 04:48:47 +00:00
|
|
|
try:
|
2019-08-04 14:02:27 +00:00
|
|
|
subprocess__check_output(['docker', '--version'])
|
2019-08-03 04:48:47 +00:00
|
|
|
except Exception:
|
|
|
|
raise unittest2.SkipTest('Docker binary is unavailable')
|
|
|
|
|
2018-06-24 00:55:35 +00:00
|
|
|
self.container_name = 'mitogen-test-%08x' % (random.getrandbits(64),)
|
|
|
|
args = [
|
|
|
|
'docker',
|
|
|
|
'run',
|
|
|
|
'--detach',
|
|
|
|
'--privileged',
|
|
|
|
'--publish-all',
|
|
|
|
'--name', self.container_name,
|
2018-11-07 00:13:05 +00:00
|
|
|
self.image,
|
2018-06-24 00:55:35 +00:00
|
|
|
]
|
|
|
|
subprocess__check_output(args)
|
|
|
|
self._get_container_port()
|
|
|
|
|
|
|
|
def __init__(self):
|
|
|
|
self.start_container()
|
2017-09-16 23:57:14 +00:00
|
|
|
|
|
|
|
def get_host(self):
|
2018-06-24 00:55:35 +00:00
|
|
|
return get_docker_host()
|
2017-09-16 23:57:14 +00:00
|
|
|
|
2017-10-15 19:31:10 +00:00
|
|
|
def wait_for_sshd(self):
|
2018-06-24 00:55:35 +00:00
|
|
|
wait_for_port(self.get_host(), self.port, pattern='OpenSSH')
|
2017-10-15 19:31:10 +00:00
|
|
|
|
2019-08-09 13:58:03 +00:00
|
|
|
def check_processes(self):
|
|
|
|
args = ['docker', 'exec', self.container_name, 'ps', '-o', 'comm=']
|
|
|
|
counts = {}
|
2019-08-09 21:45:00 +00:00
|
|
|
for comm in subprocess__check_output(args).decode().splitlines():
|
2019-08-09 13:58:03 +00:00
|
|
|
comm = comm.strip()
|
|
|
|
counts[comm] = counts.get(comm, 0) + 1
|
|
|
|
|
|
|
|
if counts != {'ps': 1, 'sshd': 1}:
|
|
|
|
assert 0, (
|
|
|
|
'Docker container %r contained extra running processes '
|
|
|
|
'after test completed: %r' % (
|
|
|
|
self.container_name,
|
|
|
|
counts
|
|
|
|
)
|
|
|
|
)
|
|
|
|
|
2017-09-16 23:57:14 +00:00
|
|
|
def close(self):
|
2018-06-24 00:55:35 +00:00
|
|
|
args = ['docker', 'rm', '-f', self.container_name]
|
|
|
|
subprocess__check_output(args)
|
2017-09-16 23:57:14 +00:00
|
|
|
|
|
|
|
|
2018-03-29 13:09:55 +00:00
|
|
|
class BrokerMixin(object):
|
2017-09-15 06:24:41 +00:00
|
|
|
broker_class = mitogen.master.Broker
|
2019-01-19 06:19:55 +00:00
|
|
|
broker_shutdown = False
|
2017-09-15 06:24:41 +00:00
|
|
|
|
|
|
|
def setUp(self):
|
2018-03-29 13:09:55 +00:00
|
|
|
super(BrokerMixin, self).setUp()
|
2017-09-15 06:24:41 +00:00
|
|
|
self.broker = self.broker_class()
|
|
|
|
|
|
|
|
def tearDown(self):
|
2019-01-19 06:19:55 +00:00
|
|
|
if not self.broker_shutdown:
|
|
|
|
self.broker.shutdown()
|
2017-09-15 06:24:41 +00:00
|
|
|
self.broker.join()
|
2019-02-17 23:12:15 +00:00
|
|
|
del self.broker
|
2018-03-29 13:09:55 +00:00
|
|
|
super(BrokerMixin, self).tearDown()
|
|
|
|
|
2018-03-29 14:39:54 +00:00
|
|
|
def sync_with_broker(self):
|
|
|
|
sync_with_broker(self.broker)
|
|
|
|
|
2018-03-29 13:09:55 +00:00
|
|
|
|
|
|
|
class RouterMixin(BrokerMixin):
|
|
|
|
router_class = mitogen.master.Router
|
|
|
|
|
|
|
|
def setUp(self):
|
|
|
|
super(RouterMixin, self).setUp()
|
|
|
|
self.router = self.router_class(self.broker)
|
2017-09-16 23:57:14 +00:00
|
|
|
|
2019-02-17 23:12:15 +00:00
|
|
|
def tearDown(self):
|
|
|
|
del self.router
|
|
|
|
super(RouterMixin, self).tearDown()
|
|
|
|
|
2017-09-16 23:57:14 +00:00
|
|
|
|
|
|
|
class DockerMixin(RouterMixin):
|
|
|
|
@classmethod
|
|
|
|
def setUpClass(cls):
|
|
|
|
super(DockerMixin, cls).setUpClass()
|
2019-02-14 11:17:52 +00:00
|
|
|
if os.environ.get('SKIP_DOCKER_TESTS'):
|
|
|
|
raise unittest2.SkipTest('SKIP_DOCKER_TESTS is set')
|
2017-09-16 23:57:14 +00:00
|
|
|
cls.dockerized_ssh = DockerizedSshDaemon()
|
2017-10-15 19:31:10 +00:00
|
|
|
cls.dockerized_ssh.wait_for_sshd()
|
2017-09-16 23:57:14 +00:00
|
|
|
|
|
|
|
@classmethod
|
|
|
|
def tearDownClass(cls):
|
2019-08-09 13:58:03 +00:00
|
|
|
cls.dockerized_ssh.check_processes()
|
2017-09-16 23:57:14 +00:00
|
|
|
cls.dockerized_ssh.close()
|
|
|
|
super(DockerMixin, cls).tearDownClass()
|
2017-09-17 15:49:06 +00:00
|
|
|
|
|
|
|
def docker_ssh(self, **kwargs):
|
|
|
|
kwargs.setdefault('hostname', self.dockerized_ssh.host)
|
|
|
|
kwargs.setdefault('port', self.dockerized_ssh.port)
|
2018-05-02 16:59:23 +00:00
|
|
|
kwargs.setdefault('check_host_keys', 'ignore')
|
2018-06-26 07:25:40 +00:00
|
|
|
kwargs.setdefault('ssh_debug_level', 3)
|
2018-11-07 00:13:05 +00:00
|
|
|
kwargs.setdefault('python_path', self.dockerized_ssh.python_path)
|
2017-09-17 15:49:06 +00:00
|
|
|
return self.router.ssh(**kwargs)
|
|
|
|
|
|
|
|
def docker_ssh_any(self, **kwargs):
|
|
|
|
return self.docker_ssh(
|
2018-04-16 13:24:39 +00:00
|
|
|
username='mitogen__has_sudo_nopw',
|
|
|
|
password='has_sudo_nopw_password',
|
2017-09-17 15:49:06 +00:00
|
|
|
)
|