1
0

test_zeromq.py 27 KB

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