test_zeromq.py 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669
  1. # -*- coding: utf-8 -*-
  2. '''
  3. :codeauthor: Thomas Jackson <jacksontj.89@gmail.com>
  4. '''
  5. # Import python libs
  6. from __future__ import absolute_import, print_function, unicode_literals
  7. import os
  8. import time
  9. import threading
  10. import multiprocessing
  11. import ctypes
  12. from concurrent.futures.thread import ThreadPoolExecutor
  13. # Import 3rd-party libs
  14. import pytest
  15. import zmq.eventloop.ioloop
  16. # support pyzmq 13.0.x, TODO: remove once we force people to 14.0.x
  17. if not hasattr(zmq.eventloop.ioloop, 'ZMQIOLoop'):
  18. zmq.eventloop.ioloop.ZMQIOLoop = zmq.eventloop.ioloop.IOLoop
  19. from tornado.testing import AsyncTestCase
  20. import tornado.gen
  21. # Import Salt libs
  22. import salt.config
  23. import salt.log.setup
  24. from salt.ext import six
  25. import salt.utils.process
  26. import salt.utils.platform
  27. import salt.transport.server
  28. import salt.transport.client
  29. import salt.exceptions
  30. from salt.ext.six.moves import range
  31. from salt.transport.zeromq import AsyncReqMessageClientPool
  32. # Import test support libs
  33. from tests.support.runtests import RUNTIME_VARS
  34. from tests.support.unit import TestCase
  35. from tests.support.helpers import flaky, get_unused_localhost_port
  36. from tests.support.mixins import AdaptedConfigurationTestCaseMixin
  37. from tests.support.mock import MagicMock, patch
  38. from tests.unit.transport.mixins import PubChannelMixin, ReqChannelMixin, run_loop_in_thread
  39. class BaseZMQReqCase(TestCase, AdaptedConfigurationTestCaseMixin):
  40. '''
  41. Test the req server/client pair
  42. '''
  43. @classmethod
  44. def setUpClass(cls):
  45. if not hasattr(cls, '_handle_payload'):
  46. return
  47. ret_port = get_unused_localhost_port()
  48. publish_port = get_unused_localhost_port()
  49. tcp_master_pub_port = get_unused_localhost_port()
  50. tcp_master_pull_port = get_unused_localhost_port()
  51. tcp_master_publish_pull = get_unused_localhost_port()
  52. tcp_master_workers = get_unused_localhost_port()
  53. cls.master_config = cls.get_temp_config(
  54. 'master',
  55. **{'transport': 'zeromq',
  56. 'auto_accept': True,
  57. 'ret_port': ret_port,
  58. 'publish_port': publish_port,
  59. 'tcp_master_pub_port': tcp_master_pub_port,
  60. 'tcp_master_pull_port': tcp_master_pull_port,
  61. 'tcp_master_publish_pull': tcp_master_publish_pull,
  62. 'tcp_master_workers': tcp_master_workers}
  63. )
  64. cls.minion_config = cls.get_temp_config(
  65. 'minion',
  66. **{'transport': 'zeromq',
  67. 'master_ip': '127.0.0.1',
  68. 'master_port': ret_port,
  69. 'auth_timeout': 5,
  70. 'auth_tries': 1,
  71. 'master_uri': 'tcp://127.0.0.1:{0}'.format(ret_port)}
  72. )
  73. cls.process_manager = salt.utils.process.ProcessManager(name='ReqServer_ProcessManager')
  74. cls.server_channel = salt.transport.server.ReqServerChannel.factory(cls.master_config)
  75. cls.server_channel.pre_fork(cls.process_manager)
  76. cls.io_loop = zmq.eventloop.ioloop.ZMQIOLoop()
  77. cls.evt = threading.Event()
  78. cls.server_channel.post_fork(cls._handle_payload, io_loop=cls.io_loop)
  79. cls.server_thread = threading.Thread(target=run_loop_in_thread, args=(cls.io_loop, cls.evt))
  80. cls.server_thread.start()
  81. @classmethod
  82. def tearDownClass(cls):
  83. if not hasattr(cls, '_handle_payload'):
  84. return
  85. # Attempting to kill the children hangs the test suite.
  86. # Let the test suite handle this instead.
  87. cls.process_manager.stop_restarting()
  88. cls.process_manager.kill_children()
  89. cls.evt.set()
  90. cls.server_thread.join()
  91. time.sleep(2) # Give the procs a chance to fully close before we stop the io_loop
  92. cls.server_channel.close()
  93. del cls.server_channel
  94. del cls.io_loop
  95. del cls.process_manager
  96. del cls.server_thread
  97. del cls.master_config
  98. del cls.minion_config
  99. @classmethod
  100. def _handle_payload(cls, payload):
  101. '''
  102. TODO: something besides echo
  103. '''
  104. return payload, {'fun': 'send_clear'}
  105. class ClearReqTestCases(BaseZMQReqCase, ReqChannelMixin):
  106. '''
  107. Test all of the clear msg stuff
  108. '''
  109. def setUp(self):
  110. self.channel = salt.transport.client.ReqChannel.factory(self.minion_config, crypt='clear')
  111. def tearDown(self):
  112. self.channel.close()
  113. del self.channel
  114. @classmethod
  115. @tornado.gen.coroutine
  116. def _handle_payload(cls, payload):
  117. '''
  118. TODO: something besides echo
  119. '''
  120. raise tornado.gen.Return((payload, {'fun': 'send_clear'}))
  121. def test_master_uri_override(self):
  122. '''
  123. ensure master_uri kwarg is respected
  124. '''
  125. # minion_config should be 127.0.0.1, we want a different uri that still connects
  126. uri = 'tcp://{master_ip}:{master_port}'.format(master_ip='localhost', master_port=self.minion_config['master_port'])
  127. channel = salt.transport.Channel.factory(self.minion_config, master_uri=uri)
  128. self.assertIn('localhost', channel.master_uri)
  129. del channel
  130. @flaky
  131. @pytest.mark.skipif('grains["os_family"] == "Suse"',
  132. reason='Skipping until https://github.com/saltstack/salt/issues/32902 gets fixed')
  133. class AESReqTestCases(BaseZMQReqCase, ReqChannelMixin):
  134. def setUp(self):
  135. self.channel = salt.transport.client.ReqChannel.factory(self.minion_config)
  136. def tearDown(self):
  137. self.channel.close()
  138. del self.channel
  139. @classmethod
  140. @tornado.gen.coroutine
  141. def _handle_payload(cls, payload):
  142. '''
  143. TODO: something besides echo
  144. '''
  145. raise tornado.gen.Return((payload, {'fun': 'send'}))
  146. # TODO: make failed returns have a specific framing so we can raise the same exception
  147. # on encrypted channels
  148. #
  149. #!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
  150. #
  151. # WARNING: This test will fail randomly on any system with > 1 CPU core!!!
  152. #
  153. #!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
  154. def test_badload(self):
  155. '''
  156. Test a variety of bad requests, make sure that we get some sort of error
  157. '''
  158. # TODO: This test should be re-enabled when Jenkins moves to C7.
  159. # Once the version of salt-testing is increased to something newer than the September
  160. # release of salt-testing, the @flaky decorator should be applied to this test.
  161. msgs = ['', [], tuple()]
  162. for msg in msgs:
  163. with self.assertRaises(salt.exceptions.AuthenticationError):
  164. ret = self.channel.send(msg, timeout=5)
  165. class BaseZMQPubCase(AsyncTestCase, AdaptedConfigurationTestCaseMixin):
  166. '''
  167. Test the req server/client pair
  168. '''
  169. @classmethod
  170. def setUpClass(cls):
  171. ret_port = get_unused_localhost_port()
  172. publish_port = get_unused_localhost_port()
  173. tcp_master_pub_port = get_unused_localhost_port()
  174. tcp_master_pull_port = get_unused_localhost_port()
  175. tcp_master_publish_pull = get_unused_localhost_port()
  176. tcp_master_workers = get_unused_localhost_port()
  177. cls.master_config = cls.get_temp_config(
  178. 'master',
  179. **{'transport': 'zeromq',
  180. 'auto_accept': True,
  181. 'ret_port': ret_port,
  182. 'publish_port': publish_port,
  183. 'tcp_master_pub_port': tcp_master_pub_port,
  184. 'tcp_master_pull_port': tcp_master_pull_port,
  185. 'tcp_master_publish_pull': tcp_master_publish_pull,
  186. 'tcp_master_workers': tcp_master_workers}
  187. )
  188. cls.minion_config = salt.config.minion_config(os.path.join(RUNTIME_VARS.TMP_CONF_DIR, 'minion'))
  189. cls.minion_config = cls.get_temp_config(
  190. 'minion',
  191. **{'transport': 'zeromq',
  192. 'master_ip': '127.0.0.1',
  193. 'master_port': ret_port,
  194. 'master_uri': 'tcp://127.0.0.1:{0}'.format(ret_port)}
  195. )
  196. cls.process_manager = salt.utils.process.ProcessManager(name='ReqServer_ProcessManager')
  197. cls.server_channel = salt.transport.server.PubServerChannel.factory(cls.master_config)
  198. cls.server_channel.pre_fork(cls.process_manager)
  199. # we also require req server for auth
  200. cls.req_server_channel = salt.transport.server.ReqServerChannel.factory(cls.master_config)
  201. cls.req_server_channel.pre_fork(cls.process_manager)
  202. cls._server_io_loop = zmq.eventloop.ioloop.ZMQIOLoop()
  203. cls.evt = threading.Event()
  204. cls.req_server_channel.post_fork(cls._handle_payload, io_loop=cls._server_io_loop)
  205. cls.server_thread = threading.Thread(target=run_loop_in_thread, args=(cls._server_io_loop, cls.evt))
  206. cls.server_thread.start()
  207. @classmethod
  208. def tearDownClass(cls):
  209. cls.process_manager.kill_children()
  210. cls.process_manager.stop_restarting()
  211. time.sleep(2) # Give the procs a chance to fully close before we stop the io_loop
  212. cls.evt.set()
  213. cls.server_thread.join()
  214. cls.req_server_channel.close()
  215. cls.server_channel.close()
  216. cls._server_io_loop.stop()
  217. del cls.server_channel
  218. del cls._server_io_loop
  219. del cls.process_manager
  220. del cls.server_thread
  221. del cls.master_config
  222. del cls.minion_config
  223. @classmethod
  224. def _handle_payload(cls, payload):
  225. '''
  226. TODO: something besides echo
  227. '''
  228. return payload, {'fun': 'send_clear'}
  229. def setUp(self):
  230. super(BaseZMQPubCase, self).setUp()
  231. self._start_handlers = dict(self.io_loop._handlers)
  232. def tearDown(self):
  233. super(BaseZMQPubCase, self).tearDown()
  234. failures = []
  235. for k, v in six.iteritems(self.io_loop._handlers):
  236. if self._start_handlers.get(k) != v:
  237. failures.append((k, v))
  238. del self._start_handlers
  239. if len(failures) > 0:
  240. raise Exception('FDs still attached to the IOLoop: {0}'.format(failures))
  241. @pytest.mark.skip('Skip until we can devote time to fix this test')
  242. class AsyncPubChannelTest(BaseZMQPubCase, PubChannelMixin):
  243. '''
  244. Tests around the publish system
  245. '''
  246. def get_new_ioloop(self):
  247. return zmq.eventloop.ioloop.ZMQIOLoop()
  248. class AsyncReqMessageClientPoolTest(TestCase):
  249. def setUp(self):
  250. super(AsyncReqMessageClientPoolTest, self).setUp()
  251. sock_pool_size = 5
  252. with patch('salt.transport.zeromq.AsyncReqMessageClient.__init__', MagicMock(return_value=None)):
  253. self.message_client_pool = AsyncReqMessageClientPool({'sock_pool_size': sock_pool_size},
  254. args=({}, ''))
  255. self.original_message_clients = self.message_client_pool.message_clients
  256. self.message_client_pool.message_clients = [MagicMock() for _ in range(sock_pool_size)]
  257. def tearDown(self):
  258. with patch('salt.transport.zeromq.AsyncReqMessageClient.destroy', MagicMock(return_value=None)):
  259. del self.original_message_clients
  260. super(AsyncReqMessageClientPoolTest, self).tearDown()
  261. def test_send(self):
  262. for message_client_mock in self.message_client_pool.message_clients:
  263. message_client_mock.send_queue = [0, 0, 0]
  264. message_client_mock.send.return_value = []
  265. self.assertEqual([], self.message_client_pool.send())
  266. self.message_client_pool.message_clients[2].send_queue = [0]
  267. self.message_client_pool.message_clients[2].send.return_value = [1]
  268. self.assertEqual([1], self.message_client_pool.send())
  269. def test_destroy(self):
  270. self.message_client_pool.destroy()
  271. self.assertEqual([], self.message_client_pool.message_clients)
  272. class ZMQConfigTest(TestCase):
  273. def test_master_uri(self):
  274. '''
  275. test _get_master_uri method
  276. '''
  277. m_ip = '127.0.0.1'
  278. m_port = 4505
  279. s_ip = '111.1.0.1'
  280. s_port = 4058
  281. m_ip6 = '1234:5678::9abc'
  282. s_ip6 = '1234:5678::1:9abc'
  283. with patch('salt.transport.zeromq.LIBZMQ_VERSION_INFO', (4, 1, 6)), \
  284. patch('salt.transport.zeromq.ZMQ_VERSION_INFO', (16, 0, 1)):
  285. # pass in both source_ip and source_port
  286. assert salt.transport.zeromq._get_master_uri(master_ip=m_ip,
  287. master_port=m_port,
  288. source_ip=s_ip,
  289. source_port=s_port) == 'tcp://{0}:{1};{2}:{3}'.format(s_ip, s_port, m_ip, m_port)
  290. assert salt.transport.zeromq._get_master_uri(master_ip=m_ip6,
  291. master_port=m_port,
  292. source_ip=s_ip6,
  293. source_port=s_port) == 'tcp://[{0}]:{1};[{2}]:{3}'.format(s_ip6, s_port, m_ip6, m_port)
  294. # source ip and source_port empty
  295. assert salt.transport.zeromq._get_master_uri(master_ip=m_ip,
  296. master_port=m_port) == 'tcp://{0}:{1}'.format(m_ip, m_port)
  297. assert salt.transport.zeromq._get_master_uri(master_ip=m_ip6,
  298. master_port=m_port) == 'tcp://[{0}]:{1}'.format(m_ip6, m_port)
  299. # pass in only source_ip
  300. assert salt.transport.zeromq._get_master_uri(master_ip=m_ip,
  301. master_port=m_port,
  302. source_ip=s_ip) == 'tcp://{0}:0;{1}:{2}'.format(s_ip, m_ip, m_port)
  303. assert salt.transport.zeromq._get_master_uri(master_ip=m_ip6,
  304. master_port=m_port,
  305. source_ip=s_ip6) == 'tcp://[{0}]:0;[{1}]:{2}'.format(s_ip6, m_ip6, m_port)
  306. # pass in only source_port
  307. assert salt.transport.zeromq._get_master_uri(master_ip=m_ip,
  308. master_port=m_port,
  309. source_port=s_port) == 'tcp://0.0.0.0:{0};{1}:{2}'.format(s_port, m_ip, m_port)
  310. class PubServerChannel(TestCase, AdaptedConfigurationTestCaseMixin):
  311. @classmethod
  312. def setUpClass(cls):
  313. ret_port = get_unused_localhost_port()
  314. publish_port = get_unused_localhost_port()
  315. tcp_master_pub_port = get_unused_localhost_port()
  316. tcp_master_pull_port = get_unused_localhost_port()
  317. tcp_master_publish_pull = get_unused_localhost_port()
  318. tcp_master_workers = get_unused_localhost_port()
  319. cls.master_config = cls.get_temp_config(
  320. 'master',
  321. **{'transport': 'zeromq',
  322. 'auto_accept': True,
  323. 'ret_port': ret_port,
  324. 'publish_port': publish_port,
  325. 'tcp_master_pub_port': tcp_master_pub_port,
  326. 'tcp_master_pull_port': tcp_master_pull_port,
  327. 'tcp_master_publish_pull': tcp_master_publish_pull,
  328. 'tcp_master_workers': tcp_master_workers,
  329. 'sign_pub_messages': False,
  330. }
  331. )
  332. salt.master.SMaster.secrets['aes'] = {
  333. 'secret': multiprocessing.Array(
  334. ctypes.c_char,
  335. six.b(salt.crypt.Crypticle.generate_key_string()),
  336. ),
  337. }
  338. cls.minion_config = cls.get_temp_config(
  339. 'minion',
  340. **{'transport': 'zeromq',
  341. 'master_ip': '127.0.0.1',
  342. 'master_port': ret_port,
  343. 'auth_timeout': 5,
  344. 'auth_tries': 1,
  345. 'master_uri': 'tcp://127.0.0.1:{0}'.format(ret_port)}
  346. )
  347. @classmethod
  348. def tearDownClass(cls):
  349. del cls.minion_config
  350. del cls.master_config
  351. def setUp(self):
  352. # Start the event loop, even though we dont directly use this with
  353. # ZeroMQPubServerChannel, having it running seems to increase the
  354. # likely hood of dropped messages.
  355. self.io_loop = zmq.eventloop.ioloop.ZMQIOLoop()
  356. self.io_loop.make_current()
  357. self.io_loop_thread = threading.Thread(target=self.io_loop.start)
  358. self.io_loop_thread.start()
  359. self.process_manager = salt.utils.process.ProcessManager(name='PubServer_ProcessManager')
  360. def tearDown(self):
  361. self.io_loop.add_callback(self.io_loop.stop)
  362. self.io_loop_thread.join()
  363. self.process_manager.stop_restarting()
  364. self.process_manager.kill_children()
  365. del self.io_loop
  366. del self.io_loop_thread
  367. del self.process_manager
  368. @staticmethod
  369. def _gather_results(opts, pub_uri, results, timeout=120, messages=None):
  370. '''
  371. Gather results until then number of seconds specified by timeout passes
  372. without reveiving a message
  373. '''
  374. ctx = zmq.Context()
  375. sock = ctx.socket(zmq.SUB)
  376. sock.setsockopt(zmq.LINGER, -1)
  377. sock.setsockopt(zmq.SUBSCRIBE, b'')
  378. sock.connect(pub_uri)
  379. last_msg = time.time()
  380. serial = salt.payload.Serial(opts)
  381. crypticle = salt.crypt.Crypticle(opts, salt.master.SMaster.secrets['aes']['secret'].value)
  382. while time.time() - last_msg < timeout:
  383. try:
  384. payload = sock.recv(zmq.NOBLOCK)
  385. except zmq.ZMQError:
  386. time.sleep(.01)
  387. else:
  388. if messages:
  389. if messages != 1:
  390. messages -= 1
  391. continue
  392. payload = crypticle.loads(serial.loads(payload)['load'])
  393. if 'stop' in payload:
  394. break
  395. last_msg = time.time()
  396. results.append(payload['jid'])
  397. @pytest.mark.skipif('grains["os_family"] == "Windows"', reason='Skip on Windows')
  398. def test_publish_to_pubserv_ipc(self):
  399. '''
  400. Test sending 10K messags to ZeroMQPubServerChannel using IPC transport
  401. ZMQ's ipc transport not supported on Windows
  402. '''
  403. opts = dict(self.master_config, ipc_mode='ipc', pub_hwm=0)
  404. server_channel = salt.transport.zeromq.ZeroMQPubServerChannel(opts)
  405. server_channel.pre_fork(self.process_manager, kwargs={
  406. 'log_queue': salt.log.setup.get_multiprocessing_logging_queue()
  407. })
  408. pub_uri = 'tcp://{interface}:{publish_port}'.format(**server_channel.opts)
  409. send_num = 10000
  410. expect = []
  411. results = []
  412. gather = threading.Thread(target=self._gather_results, args=(self.minion_config, pub_uri, results,))
  413. gather.start()
  414. # Allow time for server channel to start, especially on windows
  415. time.sleep(2)
  416. for i in range(send_num):
  417. expect.append(i)
  418. load = {'tgt_type': 'glob', 'tgt': '*', 'jid': i}
  419. server_channel.publish(load)
  420. server_channel.publish(
  421. {'tgt_type': 'glob', 'tgt': '*', 'stop': True}
  422. )
  423. gather.join()
  424. server_channel.pub_close()
  425. assert len(results) == send_num, (len(results), set(expect).difference(results))
  426. def test_zeromq_publish_port(self):
  427. '''
  428. test when connecting that we
  429. use the publish_port set in opts
  430. when its not 4506
  431. '''
  432. opts = dict(self.master_config, ipc_mode='ipc',
  433. pub_hwm=0, recon_randomize=False,
  434. publish_port=455505,
  435. recon_default=1, recon_max=2, master_ip='127.0.0.1',
  436. acceptance_wait_time=5, acceptance_wait_time_max=5)
  437. opts['master_uri'] = 'tcp://{interface}:{publish_port}'.format(**opts)
  438. channel = salt.transport.zeromq.AsyncZeroMQPubChannel(opts)
  439. patch_socket = MagicMock(return_value=True)
  440. patch_auth = MagicMock(return_value=True)
  441. with patch.object(channel, '_socket', patch_socket), \
  442. patch.object(channel, 'auth', patch_auth):
  443. channel.connect()
  444. assert str(opts['publish_port']) in patch_socket.mock_calls[0][1][0]
  445. def test_zeromq_zeromq_filtering_decode_message_no_match(self):
  446. '''
  447. test AsyncZeroMQPubChannel _decode_messages when
  448. zmq_filtering enabled and minion does not match
  449. '''
  450. message = [b'4f26aeafdb2367620a393c973eddbe8f8b846eb',
  451. b'\x82\xa3enc\xa3aes\xa4load\xda\x00`\xeeR\xcf'
  452. b'\x0eaI#V\x17if\xcf\xae\x05\xa7\xb3bN\xf7\xb2\xe2'
  453. b'\xd0sF\xd1\xd4\xecB\xe8\xaf"/*ml\x80Q3\xdb\xaexg'
  454. b'\x8e\x8a\x8c\xd3l\x03\\,J\xa7\x01i\xd1:]\xe3\x8d'
  455. b'\xf4\x03\x88K\x84\n`\xe8\x9a\xad\xad\xc6\x8ea\x15>'
  456. b'\x92m\x9e\xc7aM\x11?\x18;\xbd\x04c\x07\x85\x99\xa3\xea[\x00D']
  457. opts = dict(self.master_config, ipc_mode='ipc',
  458. pub_hwm=0, zmq_filtering=True, recon_randomize=False,
  459. recon_default=1, recon_max=2, master_ip='127.0.0.1',
  460. acceptance_wait_time=5, acceptance_wait_time_max=5)
  461. opts['master_uri'] = 'tcp://{interface}:{publish_port}'.format(**opts)
  462. server_channel = salt.transport.zeromq.AsyncZeroMQPubChannel(opts)
  463. with patch('salt.crypt.AsyncAuth.crypticle',
  464. MagicMock(return_value={'tgt_type': 'glob', 'tgt': '*',
  465. 'jid': 1})) as mock_test:
  466. res = server_channel._decode_messages(message)
  467. assert res.result() is None
  468. def test_zeromq_zeromq_filtering_decode_message(self):
  469. '''
  470. test AsyncZeroMQPubChannel _decode_messages
  471. when zmq_filtered enabled
  472. '''
  473. message = [b'4f26aeafdb2367620a393c973eddbe8f8b846ebd',
  474. b'\x82\xa3enc\xa3aes\xa4load\xda\x00`\xeeR\xcf'
  475. b'\x0eaI#V\x17if\xcf\xae\x05\xa7\xb3bN\xf7\xb2\xe2'
  476. b'\xd0sF\xd1\xd4\xecB\xe8\xaf"/*ml\x80Q3\xdb\xaexg'
  477. b'\x8e\x8a\x8c\xd3l\x03\\,J\xa7\x01i\xd1:]\xe3\x8d'
  478. b'\xf4\x03\x88K\x84\n`\xe8\x9a\xad\xad\xc6\x8ea\x15>'
  479. b'\x92m\x9e\xc7aM\x11?\x18;\xbd\x04c\x07\x85\x99\xa3\xea[\x00D']
  480. opts = dict(self.master_config, ipc_mode='ipc',
  481. pub_hwm=0, zmq_filtering=True, recon_randomize=False,
  482. recon_default=1, recon_max=2, master_ip='127.0.0.1',
  483. acceptance_wait_time=5, acceptance_wait_time_max=5)
  484. opts['master_uri'] = 'tcp://{interface}:{publish_port}'.format(**opts)
  485. server_channel = salt.transport.zeromq.AsyncZeroMQPubChannel(opts)
  486. with patch('salt.crypt.AsyncAuth.crypticle',
  487. MagicMock(return_value={'tgt_type': 'glob', 'tgt': '*',
  488. 'jid': 1})) as mock_test:
  489. res = server_channel._decode_messages(message)
  490. assert res.result()['enc'] == 'aes'
  491. @pytest.mark.skipif('grains["os_family"] == "Windows"', reason='Skip on Windows')
  492. def test_zeromq_filtering(self):
  493. '''
  494. Test sending messags to publisher using UDP
  495. with zeromq_filtering enabled
  496. '''
  497. opts = dict(self.master_config, ipc_mode='ipc',
  498. pub_hwm=0, zmq_filtering=True, acceptance_wait_time=5)
  499. server_channel = salt.transport.zeromq.ZeroMQPubServerChannel(opts)
  500. server_channel.pre_fork(self.process_manager, kwargs={
  501. 'log_queue': salt.log.setup.get_multiprocessing_logging_queue()
  502. })
  503. pub_uri = 'tcp://{interface}:{publish_port}'.format(**server_channel.opts)
  504. send_num = 1
  505. expect = []
  506. results = []
  507. gather = threading.Thread(target=self._gather_results,
  508. args=(self.minion_config, pub_uri, results,),
  509. kwargs={'messages': 2})
  510. gather.start()
  511. # Allow time for server channel to start, especially on windows
  512. time.sleep(2)
  513. expect.append(send_num)
  514. load = {'tgt_type': 'glob', 'tgt': '*', 'jid': send_num}
  515. with patch('salt.utils.minions.CkMinions.check_minions',
  516. MagicMock(return_value={'minions': ['minion'], 'missing': [],
  517. 'ssh_minions': False})):
  518. server_channel.publish(load)
  519. server_channel.publish(
  520. {'tgt_type': 'glob', 'tgt': '*', 'stop': True}
  521. )
  522. gather.join()
  523. server_channel.pub_close()
  524. assert len(results) == send_num, (len(results), set(expect).difference(results))
  525. def test_publish_to_pubserv_tcp(self):
  526. '''
  527. Test sending 10K messags to ZeroMQPubServerChannel using TCP transport
  528. '''
  529. opts = dict(self.master_config, ipc_mode='tcp', pub_hwm=0)
  530. server_channel = salt.transport.zeromq.ZeroMQPubServerChannel(opts)
  531. server_channel.pre_fork(self.process_manager, kwargs={
  532. 'log_queue': salt.log.setup.get_multiprocessing_logging_queue()
  533. })
  534. pub_uri = 'tcp://{interface}:{publish_port}'.format(**server_channel.opts)
  535. send_num = 10000
  536. expect = []
  537. results = []
  538. gather = threading.Thread(target=self._gather_results, args=(self.minion_config, pub_uri, results,))
  539. gather.start()
  540. # Allow time for server channel to start, especially on windows
  541. time.sleep(2)
  542. for i in range(send_num):
  543. expect.append(i)
  544. load = {'tgt_type': 'glob', 'tgt': '*', 'jid': i}
  545. server_channel.publish(load)
  546. gather.join()
  547. server_channel.pub_close()
  548. assert len(results) == send_num, (len(results), set(expect).difference(results))
  549. @staticmethod
  550. def _send_small(opts, sid, num=10):
  551. server_channel = salt.transport.zeromq.ZeroMQPubServerChannel(opts)
  552. for i in range(num):
  553. load = {'tgt_type': 'glob', 'tgt': '*', 'jid': '{}-{}'.format(sid, i)}
  554. server_channel.publish(load)
  555. server_channel.close()
  556. @staticmethod
  557. def _send_large(opts, sid, num=10, size=250000 * 3):
  558. server_channel = salt.transport.zeromq.ZeroMQPubServerChannel(opts)
  559. for i in range(num):
  560. load = {'tgt_type': 'glob', 'tgt': '*', 'jid': '{}-{}'.format(sid, i), 'xdata': '0' * size}
  561. server_channel.publish(load)
  562. server_channel.close()
  563. def test_issue_36469_tcp(self):
  564. '''
  565. Test sending both large and small messags to publisher using TCP
  566. https://github.com/saltstack/salt/issues/36469
  567. '''
  568. opts = dict(self.master_config, ipc_mode='tcp', pub_hwm=0)
  569. server_channel = salt.transport.zeromq.ZeroMQPubServerChannel(opts)
  570. server_channel.pre_fork(self.process_manager, kwargs={
  571. 'log_queue': salt.log.setup.get_multiprocessing_logging_queue()
  572. })
  573. send_num = 10 * 4
  574. expect = []
  575. results = []
  576. pub_uri = 'tcp://{interface}:{publish_port}'.format(**opts)
  577. # Allow time for server channel to start, especially on windows
  578. time.sleep(2)
  579. gather = threading.Thread(target=self._gather_results, args=(self.minion_config, pub_uri, results,))
  580. gather.start()
  581. with ThreadPoolExecutor(max_workers=4) as executor:
  582. executor.submit(self._send_small, opts, 1)
  583. executor.submit(self._send_small, opts, 2)
  584. executor.submit(self._send_small, opts, 3)
  585. executor.submit(self._send_large, opts, 4)
  586. expect = ['{}-{}'.format(a, b) for a in range(10) for b in (1, 2, 3, 4)]
  587. time.sleep(0.1)
  588. server_channel.publish({'tgt_type': 'glob', 'tgt': '*', 'stop': True})
  589. gather.join()
  590. server_channel.pub_close()
  591. assert len(results) == send_num, (len(results), set(expect).difference(results))