1
0

test_zeromq.py 28 KB

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