1
0

test_zeromq.py 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679
  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.runtime 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. return results
  398. @pytest.mark.skipif('grains["os_family"] == "Windows"', reason='Skip on Windows')
  399. def test_publish_to_pubserv_ipc(self):
  400. '''
  401. Test sending 10K messags to ZeroMQPubServerChannel using IPC transport
  402. ZMQ's ipc transport not supported on Windows
  403. '''
  404. opts = dict(self.master_config, ipc_mode='ipc', pub_hwm=0)
  405. server_channel = salt.transport.zeromq.ZeroMQPubServerChannel(opts)
  406. server_channel.pre_fork(self.process_manager, kwargs={
  407. 'log_queue': salt.log.setup.get_multiprocessing_logging_queue()
  408. })
  409. pub_uri = 'tcp://{interface}:{publish_port}'.format(**server_channel.opts)
  410. send_num = 10000
  411. expect = []
  412. results = []
  413. gather = threading.Thread(target=self._gather_results, args=(self.minion_config, pub_uri, results,))
  414. gather.start()
  415. # Allow time for server channel to start, especially on windows
  416. time.sleep(2)
  417. for i in range(send_num):
  418. expect.append(i)
  419. load = {'tgt_type': 'glob', 'tgt': '*', 'jid': i}
  420. server_channel.publish(load)
  421. server_channel.publish(
  422. {'tgt_type': 'glob', 'tgt': '*', 'stop': True}
  423. )
  424. gather.join()
  425. server_channel.pub_close()
  426. assert len(results) == send_num, (len(results), set(expect).difference(results))
  427. def test_zeromq_zeromq_filtering_decode_message_no_match(self):
  428. '''
  429. test AsyncZeroMQPubChannel _decode_messages when
  430. zmq_filtering enabled and minion does not match
  431. '''
  432. message = [b'4f26aeafdb2367620a393c973eddbe8f8b846eb',
  433. b'\x82\xa3enc\xa3aes\xa4load\xda\x00`\xeeR\xcf'
  434. b'\x0eaI#V\x17if\xcf\xae\x05\xa7\xb3bN\xf7\xb2\xe2'
  435. b'\xd0sF\xd1\xd4\xecB\xe8\xaf"/*ml\x80Q3\xdb\xaexg'
  436. b'\x8e\x8a\x8c\xd3l\x03\\,J\xa7\x01i\xd1:]\xe3\x8d'
  437. b'\xf4\x03\x88K\x84\n`\xe8\x9a\xad\xad\xc6\x8ea\x15>'
  438. b'\x92m\x9e\xc7aM\x11?\x18;\xbd\x04c\x07\x85\x99\xa3\xea[\x00D']
  439. opts = dict(self.master_config, ipc_mode='ipc',
  440. pub_hwm=0, zmq_filtering=True, recon_randomize=False,
  441. recon_default=1, recon_max=2, master_ip='127.0.0.1',
  442. acceptance_wait_time=5, acceptance_wait_time_max=5)
  443. opts['master_uri'] = 'tcp://{interface}:{publish_port}'.format(**opts)
  444. server_channel = salt.transport.zeromq.AsyncZeroMQPubChannel(opts)
  445. with patch('salt.crypt.AsyncAuth.crypticle',
  446. MagicMock(return_value={'tgt_type': 'glob', 'tgt': '*',
  447. 'jid': 1})) as mock_test:
  448. res = server_channel._decode_messages(message)
  449. assert res.result() is None
  450. def test_zeromq_zeromq_filtering_decode_message(self):
  451. '''
  452. test AsyncZeroMQPubChannel _decode_messages
  453. when zmq_filtered enabled
  454. '''
  455. message = [b'4f26aeafdb2367620a393c973eddbe8f8b846ebd',
  456. b'\x82\xa3enc\xa3aes\xa4load\xda\x00`\xeeR\xcf'
  457. b'\x0eaI#V\x17if\xcf\xae\x05\xa7\xb3bN\xf7\xb2\xe2'
  458. b'\xd0sF\xd1\xd4\xecB\xe8\xaf"/*ml\x80Q3\xdb\xaexg'
  459. b'\x8e\x8a\x8c\xd3l\x03\\,J\xa7\x01i\xd1:]\xe3\x8d'
  460. b'\xf4\x03\x88K\x84\n`\xe8\x9a\xad\xad\xc6\x8ea\x15>'
  461. b'\x92m\x9e\xc7aM\x11?\x18;\xbd\x04c\x07\x85\x99\xa3\xea[\x00D']
  462. opts = dict(self.master_config, ipc_mode='ipc',
  463. pub_hwm=0, zmq_filtering=True, recon_randomize=False,
  464. recon_default=1, recon_max=2, master_ip='127.0.0.1',
  465. acceptance_wait_time=5, acceptance_wait_time_max=5)
  466. opts['master_uri'] = 'tcp://{interface}:{publish_port}'.format(**opts)
  467. server_channel = salt.transport.zeromq.AsyncZeroMQPubChannel(opts)
  468. with patch('salt.crypt.AsyncAuth.crypticle',
  469. MagicMock(return_value={'tgt_type': 'glob', 'tgt': '*',
  470. 'jid': 1})) as mock_test:
  471. res = server_channel._decode_messages(message)
  472. assert res.result()['enc'] == 'aes'
  473. @pytest.mark.skipif('grains["os_family"] == "Windows"', reason='Skip on Windows')
  474. def test_zeromq_filtering(self):
  475. '''
  476. Test sending messags to publisher using UDP
  477. with zeromq_filtering enabled
  478. '''
  479. opts = dict(self.master_config, ipc_mode='ipc',
  480. pub_hwm=0, zmq_filtering=True, acceptance_wait_time=5)
  481. server_channel = salt.transport.zeromq.ZeroMQPubServerChannel(opts)
  482. server_channel.pre_fork(self.process_manager, kwargs={
  483. 'log_queue': salt.log.setup.get_multiprocessing_logging_queue()
  484. })
  485. pub_uri = 'tcp://{interface}:{publish_port}'.format(**server_channel.opts)
  486. send_num = 1
  487. expect = []
  488. results = []
  489. gather = threading.Thread(target=self._gather_results,
  490. args=(self.minion_config, pub_uri, results,),
  491. kwargs={'messages': 2})
  492. gather.start()
  493. # Allow time for server channel to start, especially on windows
  494. time.sleep(2)
  495. expect.append(send_num)
  496. load = {'tgt_type': 'glob', 'tgt': '*', 'jid': send_num}
  497. with patch('salt.utils.minions.CkMinions.check_minions',
  498. MagicMock(return_value={'minions': ['minion'], 'missing': [],
  499. 'ssh_minions': False})):
  500. server_channel.publish(load)
  501. server_channel.publish(
  502. {'tgt_type': 'glob', 'tgt': '*', 'stop': True}
  503. )
  504. gather.join()
  505. server_channel.pub_close()
  506. assert len(results) == send_num, (len(results), set(expect).difference(results))
  507. def test_publish_to_pubserv_tcp(self):
  508. '''
  509. Test sending 10K messags to ZeroMQPubServerChannel using TCP transport
  510. '''
  511. opts = dict(self.master_config, ipc_mode='tcp', pub_hwm=0)
  512. server_channel = salt.transport.zeromq.ZeroMQPubServerChannel(opts)
  513. server_channel.pre_fork(self.process_manager, kwargs={
  514. 'log_queue': salt.log.setup.get_multiprocessing_logging_queue()
  515. })
  516. pub_uri = 'tcp://{interface}:{publish_port}'.format(**server_channel.opts)
  517. send_num = 10000
  518. expect = []
  519. results = []
  520. gather = threading.Thread(target=self._gather_results, args=(self.minion_config, pub_uri, results,))
  521. gather.start()
  522. # Allow time for server channel to start, especially on windows
  523. time.sleep(2)
  524. for i in range(send_num):
  525. expect.append(i)
  526. load = {'tgt_type': 'glob', 'tgt': '*', 'jid': i}
  527. server_channel.publish(load)
  528. gather.join()
  529. server_channel.pub_close()
  530. assert len(results) == send_num, (len(results), set(expect).difference(results))
  531. @staticmethod
  532. def _send_small(opts, sid, num=10):
  533. server_channel = salt.transport.zeromq.ZeroMQPubServerChannel(opts)
  534. for i in range(num):
  535. load = {'tgt_type': 'glob', 'tgt': '*', 'jid': '{}-{}'.format(sid, i)}
  536. server_channel.publish(load)
  537. @staticmethod
  538. def _send_large(opts, sid, num=10, size=250000 * 3):
  539. server_channel = salt.transport.zeromq.ZeroMQPubServerChannel(opts)
  540. for i in range(num):
  541. load = {'tgt_type': 'glob', 'tgt': '*', 'jid': '{}-{}'.format(sid, i), 'xdata': '0' * size}
  542. server_channel.publish(load)
  543. def test_issue_36469_tcp(self):
  544. '''
  545. Test sending both large and small messags to publisher using TCP
  546. https://github.com/saltstack/salt/issues/36469
  547. '''
  548. opts = dict(self.master_config, ipc_mode='tcp', pub_hwm=0)
  549. server_channel = salt.transport.zeromq.ZeroMQPubServerChannel(opts)
  550. server_channel.pre_fork(self.process_manager, kwargs={
  551. 'log_queue': salt.log.setup.get_multiprocessing_logging_queue()
  552. })
  553. send_num = 10 * 4
  554. expect = []
  555. results = []
  556. pub_uri = 'tcp://{interface}:{publish_port}'.format(**opts)
  557. # Allow time for server channel to start, especially on windows
  558. time.sleep(2)
  559. gather = threading.Thread(target=self._gather_results, args=(self.minion_config, pub_uri, results,))
  560. gather.start()
  561. with ThreadPoolExecutor(max_workers=4) as executor:
  562. executor.submit(self._send_small, opts, 1)
  563. executor.submit(self._send_small, opts, 2)
  564. executor.submit(self._send_small, opts, 3)
  565. executor.submit(self._send_large, opts, 4)
  566. expect = ['{}-{}'.format(a, b) for a in range(10) for b in (1, 2, 3, 4)]
  567. time.sleep(0.1)
  568. server_channel.publish({'tgt_type': 'glob', 'tgt': '*', 'stop': True})
  569. gather.join()
  570. server_channel.pub_close()
  571. assert len(results) == send_num, (len(results), set(expect).difference(results))
  572. @pytest.mark.skipif('grains["os_family"] == "Windows"', reason='Skip on Windows')
  573. def test_issue_36469_udp(self):
  574. '''
  575. Test sending both large and small messags to publisher using UDP
  576. https://github.com/saltstack/salt/issues/36469
  577. '''
  578. opts = dict(self.master_config, ipc_mode='udp', pub_hwm=0)
  579. server_channel = salt.transport.zeromq.ZeroMQPubServerChannel(opts)
  580. server_channel.pre_fork(self.process_manager, kwargs={
  581. 'log_queue': salt.log.setup.get_multiprocessing_logging_queue()
  582. })
  583. send_num = 10 * 4
  584. expect = []
  585. results = []
  586. pub_uri = 'tcp://{interface}:{publish_port}'.format(**opts)
  587. # Allow time for server channel to start, especially on windows
  588. time.sleep(2)
  589. gather = threading.Thread(target=self._gather_results, args=(self.minion_config, pub_uri, results,))
  590. gather.start()
  591. with ThreadPoolExecutor(max_workers=4) as executor:
  592. executor.submit(self._send_small, opts, 1)
  593. executor.submit(self._send_small, opts, 2)
  594. executor.submit(self._send_small, opts, 3)
  595. executor.submit(self._send_large, opts, 4)
  596. expect = ['{}-{}'.format(a, b) for a in range(10) for b in (1, 2, 3, 4)]
  597. time.sleep(0.1)
  598. server_channel.publish({'tgt_type': 'glob', 'tgt': '*', 'stop': True})
  599. gather.join()
  600. server_channel.pub_close()
  601. assert len(results) == send_num, (len(results), set(expect).difference(results))