salt/tests/unit/transport/test_zeromq.py

308 lines
11 KiB
Python
Raw Normal View History

2015-03-13 21:31:39 +00:00
# -*- coding: utf-8 -*-
'''
:codeauthor: :email:`Thomas Jackson <jacksontj.89@gmail.com>`
'''
# Import python libs
from __future__ import absolute_import
import os
import time
2015-03-13 21:31:39 +00:00
import threading
# linux_distribution deprecated in py3.7
try:
from platform import linux_distribution
except ImportError:
from distro import linux_distribution
2015-03-13 21:31:39 +00:00
# Import 3rd-party libs
2015-03-13 21:31:39 +00:00
import zmq.eventloop.ioloop
# support pyzmq 13.0.x, TODO: remove once we force people to 14.0.x
if not hasattr(zmq.eventloop.ioloop, 'ZMQIOLoop'):
zmq.eventloop.ioloop.ZMQIOLoop = zmq.eventloop.ioloop.IOLoop
2015-03-21 20:59:47 +00:00
from tornado.testing import AsyncTestCase
import tornado.gen
# Import Salt libs
2015-03-13 21:31:39 +00:00
import salt.config
Use explicit unicode strings + break up salt.utils This PR is part of what will be an ongoing effort to use explicit unicode strings in Salt. Because Python 3 does not suport Python 2's raw unicode string syntax (i.e. `ur'\d+'`), we must use `salt.utils.locales.sdecode()` to ensure that the raw string is unicode. However, because of how `salt/utils/__init__.py` has evolved into the hulking monstrosity it is today, this means importing a large module in places where it is not needed, which could negatively impact performance. For this reason, this PR also breaks out some of the functions from `salt/utils/__init__.py` into new/existing modules under `salt/utils/`. The long term goal will be that the modules within this directory do not depend on importing `salt.utils`. A summary of the changes in this PR is as follows: * Moves the following functions from `salt.utils` to new locations (including a deprecation warning if invoked from `salt.utils`): `to_bytes`, `to_str`, `to_unicode`, `str_to_num`, `is_quoted`, `dequote`, `is_hex`, `is_bin_str`, `rand_string`, `contains_whitespace`, `clean_kwargs`, `invalid_kwargs`, `which`, `which_bin`, `path_join`, `shlex_split`, `rand_str`, `is_windows`, `is_proxy`, `is_linux`, `is_darwin`, `is_sunos`, `is_smartos`, `is_smartos_globalzone`, `is_smartos_zone`, `is_freebsd`, `is_netbsd`, `is_openbsd`, `is_aix` * Moves the functions already deprecated by @rallytime to the bottom of `salt/utils/__init__.py` for better organization, so we can keep the deprecated ones separate from the ones yet to be deprecated as we continue to break up `salt.utils` * Updates `salt/*.py` and all files under `salt/client/` to use explicit unicode string literals. * Gets rid of implicit imports of `salt.utils` (e.g. `from salt.utils import foo` becomes `import salt.utils.foo as foo`). * Renames the `test.rand_str` function to `test.random_hash` to more accurately reflect what it does * Modifies `salt.utils.stringutils.random()` (née `salt.utils.rand_string()`) such that it returns a string matching the passed size. Previously this function would get `size` bytes from `os.urandom()`, base64-encode it, and return the result, which would in most cases not be equal to the passed size.
2017-07-25 01:47:15 +00:00
from salt.ext import six
2015-03-13 21:31:39 +00:00
import salt.utils
import salt.transport.server
import salt.transport.client
import salt.exceptions
from salt.ext.six.moves import range
from salt.transport.zeromq import AsyncReqMessageClientPool
2015-03-13 21:31:39 +00:00
# Import test support libs
2017-03-28 16:06:57 +00:00
from tests.support.paths import TMP_CONF_DIR
from tests.support.unit import TestCase, skipIf
2017-03-28 16:06:57 +00:00
from tests.support.helpers import flaky, get_unused_localhost_port
2017-04-02 16:17:34 +00:00
from tests.support.mixins import AdaptedConfigurationTestCaseMixin
from tests.support.mock import MagicMock, patch
2017-03-28 16:06:57 +00:00
from tests.unit.transport.mixins import PubChannelMixin, ReqChannelMixin
2015-03-13 21:31:39 +00:00
ON_SUSE = False
if 'SuSE' in linux_distribution(full_distribution_name=False):
ON_SUSE = True
2015-04-08 15:04:45 +00:00
2017-04-02 16:17:34 +00:00
class BaseZMQReqCase(TestCase, AdaptedConfigurationTestCaseMixin):
2015-03-13 21:31:39 +00:00
'''
Test the req server/client pair
'''
@classmethod
def setUpClass(cls):
if not hasattr(cls, '_handle_payload'):
return
2017-03-28 16:06:57 +00:00
ret_port = get_unused_localhost_port()
publish_port = get_unused_localhost_port()
tcp_master_pub_port = get_unused_localhost_port()
tcp_master_pull_port = get_unused_localhost_port()
tcp_master_publish_pull = get_unused_localhost_port()
tcp_master_workers = get_unused_localhost_port()
2017-04-02 16:17:34 +00:00
cls.master_config = cls.get_temp_config(
'master',
**{'transport': 'zeromq',
'auto_accept': True,
'ret_port': ret_port,
'publish_port': publish_port,
'tcp_master_pub_port': tcp_master_pub_port,
'tcp_master_pull_port': tcp_master_pull_port,
'tcp_master_publish_pull': tcp_master_publish_pull,
'tcp_master_workers': tcp_master_workers}
)
cls.minion_config = cls.get_temp_config(
'minion',
**{'transport': 'zeromq',
'master_ip': '127.0.0.1',
'master_port': ret_port,
'auth_timeout': 5,
'auth_tries': 1,
'master_uri': 'tcp://127.0.0.1:{0}'.format(ret_port)}
)
2015-03-13 21:31:39 +00:00
cls.process_manager = salt.utils.process.ProcessManager(name='ReqServer_ProcessManager')
2017-04-02 16:17:34 +00:00
cls.server_channel = salt.transport.server.ReqServerChannel.factory(cls.master_config)
2015-03-13 21:31:39 +00:00
cls.server_channel.pre_fork(cls.process_manager)
cls.io_loop = zmq.eventloop.ioloop.ZMQIOLoop()
cls.io_loop.make_current()
2015-03-13 22:27:26 +00:00
cls.server_channel.post_fork(cls._handle_payload, io_loop=cls.io_loop)
2015-03-13 21:31:39 +00:00
cls.server_thread = threading.Thread(target=cls.io_loop.start)
cls.server_thread.daemon = True
cls.server_thread.start()
@classmethod
def tearDownClass(cls):
if not hasattr(cls, '_handle_payload'):
return
# Attempting to kill the children hangs the test suite.
# Let the test suite handle this instead.
2017-03-04 20:31:32 +00:00
cls.process_manager.stop_restarting()
cls.process_manager.kill_children()
2017-03-28 16:06:57 +00:00
cls.io_loop.add_callback(cls.io_loop.stop)
cls.server_thread.join()
time.sleep(2) # Give the procs a chance to fully close before we stop the io_loop
2015-03-13 21:31:39 +00:00
cls.server_channel.close()
del cls.server_channel
2017-03-04 20:31:32 +00:00
del cls.io_loop
del cls.process_manager
del cls.server_thread
2017-04-02 16:17:34 +00:00
del cls.master_config
del cls.minion_config
@classmethod
def _handle_payload(cls, payload):
'''
TODO: something besides echo
'''
return payload, {'fun': 'send_clear'}
2015-03-13 21:31:39 +00:00
class ClearReqTestCases(BaseZMQReqCase, ReqChannelMixin):
'''
Test all of the clear msg stuff
'''
def setUp(self):
2017-04-02 16:17:34 +00:00
self.channel = salt.transport.client.ReqChannel.factory(self.minion_config, crypt='clear')
2015-03-13 21:31:39 +00:00
2017-03-04 20:31:32 +00:00
def tearDown(self):
del self.channel
2015-03-13 21:31:39 +00:00
@classmethod
@tornado.gen.coroutine
2015-03-13 21:31:39 +00:00
def _handle_payload(cls, payload):
'''
TODO: something besides echo
'''
raise tornado.gen.Return((payload, {'fun': 'send_clear'}))
2015-03-13 21:31:39 +00:00
@flaky
@skipIf(ON_SUSE, 'Skipping until https://github.com/saltstack/salt/issues/32902 gets fixed')
2015-03-13 21:31:39 +00:00
class AESReqTestCases(BaseZMQReqCase, ReqChannelMixin):
def setUp(self):
2017-04-02 16:17:34 +00:00
self.channel = salt.transport.client.ReqChannel.factory(self.minion_config)
2015-03-13 21:31:39 +00:00
2017-03-04 20:31:32 +00:00
def tearDown(self):
del self.channel
2015-03-13 21:31:39 +00:00
@classmethod
@tornado.gen.coroutine
2015-03-13 21:31:39 +00:00
def _handle_payload(cls, payload):
'''
TODO: something besides echo
'''
raise tornado.gen.Return((payload, {'fun': 'send'}))
2015-03-13 21:31:39 +00:00
# TODO: make failed returns have a specific framing so we can raise the same exception
# on encrypted channels
#
#!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
#
# WARNING: This test will fail randomly on any system with > 1 CPU core!!!
#
#!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
2015-03-13 21:31:39 +00:00
def test_badload(self):
'''
Test a variety of bad requests, make sure that we get some sort of error
'''
# TODO: This test should be re-enabled when Jenkins moves to C7.
# Once the version of salt-testing is increased to something newer than the September
# release of salt-testing, the @flaky decorator should be applied to this test.
2015-03-13 21:31:39 +00:00
msgs = ['', [], tuple()]
for msg in msgs:
with self.assertRaises(salt.exceptions.AuthenticationError):
ret = self.channel.send(msg, timeout=5)
2015-03-13 21:31:39 +00:00
2015-03-13 22:27:26 +00:00
2017-04-02 16:17:34 +00:00
class BaseZMQPubCase(AsyncTestCase, AdaptedConfigurationTestCaseMixin):
2015-03-13 22:27:26 +00:00
'''
Test the req server/client pair
'''
@classmethod
def setUpClass(cls):
2017-03-28 16:06:57 +00:00
ret_port = get_unused_localhost_port()
publish_port = get_unused_localhost_port()
tcp_master_pub_port = get_unused_localhost_port()
tcp_master_pull_port = get_unused_localhost_port()
tcp_master_publish_pull = get_unused_localhost_port()
tcp_master_workers = get_unused_localhost_port()
2017-04-02 16:17:34 +00:00
cls.master_config = cls.get_temp_config(
'master',
**{'transport': 'zeromq',
'auto_accept': True,
'ret_port': ret_port,
'publish_port': publish_port,
'tcp_master_pub_port': tcp_master_pub_port,
'tcp_master_pull_port': tcp_master_pull_port,
'tcp_master_publish_pull': tcp_master_publish_pull,
'tcp_master_workers': tcp_master_workers}
)
cls.minion_config = salt.config.minion_config(os.path.join(TMP_CONF_DIR, 'minion'))
cls.minion_config = cls.get_temp_config(
'minion',
**{'transport': 'zeromq',
'master_ip': '127.0.0.1',
'master_port': ret_port,
'master_uri': 'tcp://127.0.0.1:{0}'.format(ret_port)}
)
2015-03-13 22:27:26 +00:00
cls.process_manager = salt.utils.process.ProcessManager(name='ReqServer_ProcessManager')
2017-04-02 16:17:34 +00:00
cls.server_channel = salt.transport.server.PubServerChannel.factory(cls.master_config)
2015-03-13 22:27:26 +00:00
cls.server_channel.pre_fork(cls.process_manager)
# we also require req server for auth
2017-04-02 16:17:34 +00:00
cls.req_server_channel = salt.transport.server.ReqServerChannel.factory(cls.master_config)
2015-03-13 22:27:26 +00:00
cls.req_server_channel.pre_fork(cls.process_manager)
cls._server_io_loop = zmq.eventloop.ioloop.ZMQIOLoop()
cls.req_server_channel.post_fork(cls._handle_payload, io_loop=cls._server_io_loop)
2015-03-13 22:27:26 +00:00
cls.server_thread = threading.Thread(target=cls._server_io_loop.start)
2015-03-13 22:27:26 +00:00
cls.server_thread.daemon = True
cls.server_thread.start()
2017-03-04 20:31:32 +00:00
@classmethod
def tearDownClass(cls):
cls.process_manager.kill_children()
cls.process_manager.stop_restarting()
time.sleep(2) # Give the procs a chance to fully close before we stop the io_loop
2017-03-28 16:06:57 +00:00
cls.io_loop.add_callback(cls.io_loop.stop)
cls.server_thread.join()
2017-03-04 20:31:32 +00:00
cls.req_server_channel.close()
cls.server_channel.close()
cls._server_io_loop.stop()
del cls.server_channel
del cls._server_io_loop
del cls.process_manager
del cls.server_thread
2017-04-02 16:17:34 +00:00
del cls.master_config
del cls.minion_config
2017-03-04 20:31:32 +00:00
2015-03-13 22:27:26 +00:00
@classmethod
def _handle_payload(cls, payload):
'''
TODO: something besides echo
'''
return payload, {'fun': 'send_clear'}
def setUp(self):
super(BaseZMQPubCase, self).setUp()
self._start_handlers = dict(self.io_loop._handlers)
def tearDown(self):
super(BaseZMQPubCase, self).tearDown()
failures = []
for k, v in six.iteritems(self.io_loop._handlers):
if self._start_handlers.get(k) != v:
failures.append((k, v))
2017-03-04 20:31:32 +00:00
del self._start_handlers
if len(failures) > 0:
raise Exception('FDs still attached to the IOLoop: {0}'.format(failures))
@skipIf(True, 'Skip until we can devote time to fix this test')
2015-03-29 23:37:55 +00:00
class AsyncPubChannelTest(BaseZMQPubCase, PubChannelMixin):
2015-03-13 22:27:26 +00:00
'''
Tests around the publish system
'''
2015-03-21 21:07:26 +00:00
def get_new_ioloop(self):
2015-06-30 20:38:31 +00:00
return zmq.eventloop.ioloop.ZMQIOLoop()
2015-03-21 21:17:13 +00:00
2015-03-13 22:27:26 +00:00
class AsyncReqMessageClientPoolTest(TestCase):
def setUp(self):
super(AsyncReqMessageClientPoolTest, self).setUp()
sock_pool_size = 5
with patch('salt.transport.zeromq.AsyncReqMessageClient.__init__', MagicMock(return_value=None)):
self.message_client_pool = AsyncReqMessageClientPool({'sock_pool_size': sock_pool_size},
args=({}, ''))
self.original_message_clients = self.message_client_pool.message_clients
self.message_client_pool.message_clients = [MagicMock() for _ in range(sock_pool_size)]
def tearDown(self):
with patch('salt.transport.zeromq.AsyncReqMessageClient.destroy', MagicMock(return_value=None)):
del self.original_message_clients
super(AsyncReqMessageClientPoolTest, self).tearDown()
def test_send(self):
for message_client_mock in self.message_client_pool.message_clients:
message_client_mock.send_queue = [0, 0, 0]
message_client_mock.send.return_value = []
self.assertEqual([], self.message_client_pool.send())
self.message_client_pool.message_clients[2].send_queue = [0]
self.message_client_pool.message_clients[2].send.return_value = [1]
self.assertEqual([1], self.message_client_pool.send())
def test_destroy(self):
self.message_client_pool.destroy()
2017-06-10 06:03:03 +00:00
self.assertEqual([], self.message_client_pool.message_clients)