test_minion.py 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369
  1. # -*- coding: utf-8 -*-
  2. '''
  3. :codeauthor: Mike Place <mp@saltstack.com>
  4. '''
  5. # Import python libs
  6. from __future__ import absolute_import
  7. import copy
  8. import os
  9. # Import Salt Testing libs
  10. from tests.support.unit import TestCase, skipIf
  11. from tests.support.mock import NO_MOCK, NO_MOCK_REASON, patch, MagicMock
  12. from tests.support.mixins import AdaptedConfigurationTestCaseMixin
  13. from tests.support.helpers import skip_if_not_root
  14. # Import salt libs
  15. import salt.minion
  16. import salt.utils.event as event
  17. from salt.exceptions import SaltSystemExit, SaltMasterUnresolvableError
  18. import salt.syspaths
  19. import tornado
  20. import tornado.testing
  21. from salt.ext.six.moves import range
  22. __opts__ = {}
  23. @skipIf(NO_MOCK, NO_MOCK_REASON)
  24. class MinionTestCase(TestCase, AdaptedConfigurationTestCaseMixin):
  25. def test_invalid_master_address(self):
  26. with patch.dict(__opts__, {'ipv6': False, 'master': float('127.0'), 'master_port': '4555', 'retry_dns': False}):
  27. self.assertRaises(SaltSystemExit, salt.minion.resolve_dns, __opts__)
  28. def test_source_int_name_local(self):
  29. '''
  30. test when file_client local and
  31. source_interface_name is set
  32. '''
  33. interfaces = {'bond0.1234': {'hwaddr': '01:01:01:d0:d0:d0',
  34. 'up': True, 'inet':
  35. [{'broadcast': '111.1.111.255',
  36. 'netmask': '111.1.0.0',
  37. 'label': 'bond0',
  38. 'address': '111.1.0.1'}]}}
  39. with patch.dict(__opts__, {'ipv6': False, 'master': '127.0.0.1',
  40. 'master_port': '4555', 'file_client': 'local',
  41. 'source_interface_name': 'bond0.1234',
  42. 'source_ret_port': 49017,
  43. 'source_publish_port': 49018}), \
  44. patch('salt.utils.network.interfaces',
  45. MagicMock(return_value=interfaces)):
  46. assert salt.minion.resolve_dns(__opts__) == {'master_ip': '127.0.0.1',
  47. 'source_ip': '111.1.0.1',
  48. 'source_ret_port': 49017,
  49. 'source_publish_port': 49018,
  50. 'master_uri': 'tcp://127.0.0.1:4555'}
  51. def test_source_int_name_remote(self):
  52. '''
  53. test when file_client remote and
  54. source_interface_name is set and
  55. interface is down
  56. '''
  57. interfaces = {'bond0.1234': {'hwaddr': '01:01:01:d0:d0:d0',
  58. 'up': False, 'inet':
  59. [{'broadcast': '111.1.111.255',
  60. 'netmask': '111.1.0.0',
  61. 'label': 'bond0',
  62. 'address': '111.1.0.1'}]}}
  63. with patch.dict(__opts__, {'ipv6': False, 'master': '127.0.0.1',
  64. 'master_port': '4555', 'file_client': 'remote',
  65. 'source_interface_name': 'bond0.1234',
  66. 'source_ret_port': 49017,
  67. 'source_publish_port': 49018}), \
  68. patch('salt.utils.network.interfaces',
  69. MagicMock(return_value=interfaces)):
  70. assert salt.minion.resolve_dns(__opts__) == {'master_ip': '127.0.0.1',
  71. 'source_ret_port': 49017,
  72. 'source_publish_port': 49018,
  73. 'master_uri': 'tcp://127.0.0.1:4555'}
  74. def test_source_address(self):
  75. '''
  76. test when source_address is set
  77. '''
  78. interfaces = {'bond0.1234': {'hwaddr': '01:01:01:d0:d0:d0',
  79. 'up': False, 'inet':
  80. [{'broadcast': '111.1.111.255',
  81. 'netmask': '111.1.0.0',
  82. 'label': 'bond0',
  83. 'address': '111.1.0.1'}]}}
  84. with patch.dict(__opts__, {'ipv6': False, 'master': '127.0.0.1',
  85. 'master_port': '4555', 'file_client': 'local',
  86. 'source_interface_name': '',
  87. 'source_address': '111.1.0.1',
  88. 'source_ret_port': 49017,
  89. 'source_publish_port': 49018}), \
  90. patch('salt.utils.network.interfaces',
  91. MagicMock(return_value=interfaces)):
  92. assert salt.minion.resolve_dns(__opts__) == {'source_publish_port': 49018,
  93. 'source_ret_port': 49017,
  94. 'master_uri': 'tcp://127.0.0.1:4555',
  95. 'source_ip': '111.1.0.1',
  96. 'master_ip': '127.0.0.1'}
  97. # Tests for _handle_decoded_payload in the salt.minion.Minion() class: 3
  98. def test_handle_decoded_payload_jid_match_in_jid_queue(self):
  99. '''
  100. Tests that the _handle_decoded_payload function returns when a jid is given that is already present
  101. in the jid_queue.
  102. Note: This test doesn't contain all of the patch decorators above the function like the other tests
  103. for _handle_decoded_payload below. This is essential to this test as the call to the function must
  104. return None BEFORE any of the processes are spun up because we should be avoiding firing duplicate
  105. jobs.
  106. '''
  107. mock_opts = salt.config.DEFAULT_MINION_OPTS
  108. mock_data = {'fun': 'foo.bar',
  109. 'jid': 123}
  110. mock_jid_queue = [123]
  111. minion = salt.minion.Minion(mock_opts, jid_queue=copy.copy(mock_jid_queue), io_loop=tornado.ioloop.IOLoop())
  112. try:
  113. ret = minion._handle_decoded_payload(mock_data).result()
  114. self.assertEqual(minion.jid_queue, mock_jid_queue)
  115. self.assertIsNone(ret)
  116. finally:
  117. minion.destroy()
  118. def test_handle_decoded_payload_jid_queue_addition(self):
  119. '''
  120. Tests that the _handle_decoded_payload function adds a jid to the minion's jid_queue when the new
  121. jid isn't already present in the jid_queue.
  122. '''
  123. with patch('salt.minion.Minion.ctx', MagicMock(return_value={})), \
  124. patch('salt.utils.process.SignalHandlingProcess.start', MagicMock(return_value=True)), \
  125. patch('salt.utils.process.SignalHandlingProcess.join', MagicMock(return_value=True)):
  126. mock_jid = 11111
  127. mock_opts = salt.config.DEFAULT_MINION_OPTS
  128. mock_data = {'fun': 'foo.bar',
  129. 'jid': mock_jid}
  130. mock_jid_queue = [123, 456]
  131. minion = salt.minion.Minion(mock_opts, jid_queue=copy.copy(mock_jid_queue), io_loop=tornado.ioloop.IOLoop())
  132. try:
  133. # Assert that the minion's jid_queue attribute matches the mock_jid_queue as a baseline
  134. # This can help debug any test failures if the _handle_decoded_payload call fails.
  135. self.assertEqual(minion.jid_queue, mock_jid_queue)
  136. # Call the _handle_decoded_payload function and update the mock_jid_queue to include the new
  137. # mock_jid. The mock_jid should have been added to the jid_queue since the mock_jid wasn't
  138. # previously included. The minion's jid_queue attribute and the mock_jid_queue should be equal.
  139. minion._handle_decoded_payload(mock_data).result()
  140. mock_jid_queue.append(mock_jid)
  141. self.assertEqual(minion.jid_queue, mock_jid_queue)
  142. finally:
  143. minion.destroy()
  144. def test_handle_decoded_payload_jid_queue_reduced_minion_jid_queue_hwm(self):
  145. '''
  146. Tests that the _handle_decoded_payload function removes a jid from the minion's jid_queue when the
  147. minion's jid_queue high water mark (minion_jid_queue_hwm) is hit.
  148. '''
  149. with patch('salt.minion.Minion.ctx', MagicMock(return_value={})), \
  150. patch('salt.utils.process.SignalHandlingProcess.start', MagicMock(return_value=True)), \
  151. patch('salt.utils.process.SignalHandlingProcess.join', MagicMock(return_value=True)):
  152. mock_opts = salt.config.DEFAULT_MINION_OPTS
  153. mock_opts['minion_jid_queue_hwm'] = 2
  154. mock_data = {'fun': 'foo.bar',
  155. 'jid': 789}
  156. mock_jid_queue = [123, 456]
  157. minion = salt.minion.Minion(mock_opts, jid_queue=copy.copy(mock_jid_queue), io_loop=tornado.ioloop.IOLoop())
  158. try:
  159. # Assert that the minion's jid_queue attribute matches the mock_jid_queue as a baseline
  160. # This can help debug any test failures if the _handle_decoded_payload call fails.
  161. self.assertEqual(minion.jid_queue, mock_jid_queue)
  162. # Call the _handle_decoded_payload function and check that the queue is smaller by one item
  163. # and contains the new jid
  164. minion._handle_decoded_payload(mock_data).result()
  165. self.assertEqual(len(minion.jid_queue), 2)
  166. self.assertEqual(minion.jid_queue, [456, 789])
  167. finally:
  168. minion.destroy()
  169. def test_process_count_max(self):
  170. '''
  171. Tests that the _handle_decoded_payload function does not spawn more than the configured amount of processes,
  172. as per process_count_max.
  173. '''
  174. with patch('salt.minion.Minion.ctx', MagicMock(return_value={})), \
  175. patch('salt.utils.process.SignalHandlingProcess.start', MagicMock(return_value=True)), \
  176. patch('salt.utils.process.SignalHandlingProcess.join', MagicMock(return_value=True)), \
  177. patch('salt.utils.minion.running', MagicMock(return_value=[])), \
  178. patch('tornado.gen.sleep', MagicMock(return_value=tornado.concurrent.Future())):
  179. process_count_max = 10
  180. mock_opts = salt.config.DEFAULT_MINION_OPTS
  181. mock_opts['minion_jid_queue_hwm'] = 100
  182. mock_opts["process_count_max"] = process_count_max
  183. io_loop = tornado.ioloop.IOLoop()
  184. minion = salt.minion.Minion(mock_opts, jid_queue=[], io_loop=io_loop)
  185. try:
  186. # mock gen.sleep to throw a special Exception when called, so that we detect it
  187. class SleepCalledException(Exception):
  188. """Thrown when sleep is called"""
  189. pass
  190. tornado.gen.sleep.return_value.set_exception(SleepCalledException())
  191. # up until process_count_max: gen.sleep does not get called, processes are started normally
  192. for i in range(process_count_max):
  193. mock_data = {'fun': 'foo.bar',
  194. 'jid': i}
  195. io_loop.run_sync(lambda data=mock_data: minion._handle_decoded_payload(data))
  196. self.assertEqual(salt.utils.process.SignalHandlingProcess.start.call_count, i + 1)
  197. self.assertEqual(len(minion.jid_queue), i + 1)
  198. salt.utils.minion.running.return_value += [i]
  199. # above process_count_max: gen.sleep does get called, JIDs are created but no new processes are started
  200. mock_data = {'fun': 'foo.bar',
  201. 'jid': process_count_max + 1}
  202. self.assertRaises(SleepCalledException,
  203. lambda: io_loop.run_sync(lambda: minion._handle_decoded_payload(mock_data)))
  204. self.assertEqual(salt.utils.process.SignalHandlingProcess.start.call_count,
  205. process_count_max)
  206. self.assertEqual(len(minion.jid_queue), process_count_max + 1)
  207. finally:
  208. minion.destroy()
  209. def test_beacons_before_connect(self):
  210. '''
  211. Tests that the 'beacons_before_connect' option causes the beacons to be initialized before connect.
  212. '''
  213. with patch('salt.minion.Minion.ctx', MagicMock(return_value={})), \
  214. patch('salt.minion.Minion.sync_connect_master', MagicMock(side_effect=RuntimeError('stop execution'))), \
  215. patch('salt.utils.process.SignalHandlingProcess.start', MagicMock(return_value=True)), \
  216. patch('salt.utils.process.SignalHandlingProcess.join', MagicMock(return_value=True)):
  217. mock_opts = self.get_config('minion', from_scratch=True)
  218. mock_opts['beacons_before_connect'] = True
  219. io_loop = tornado.ioloop.IOLoop()
  220. io_loop.make_current()
  221. minion = salt.minion.Minion(mock_opts, io_loop=io_loop)
  222. try:
  223. try:
  224. minion.tune_in(start=True)
  225. except RuntimeError:
  226. pass
  227. # Make sure beacons are initialized but the sheduler is not
  228. self.assertTrue('beacons' in minion.periodic_callbacks)
  229. self.assertTrue('schedule' not in minion.periodic_callbacks)
  230. finally:
  231. minion.destroy()
  232. def test_scheduler_before_connect(self):
  233. '''
  234. Tests that the 'scheduler_before_connect' option causes the scheduler to be initialized before connect.
  235. '''
  236. with patch('salt.minion.Minion.ctx', MagicMock(return_value={})), \
  237. patch('salt.minion.Minion.sync_connect_master', MagicMock(side_effect=RuntimeError('stop execution'))), \
  238. patch('salt.utils.process.SignalHandlingProcess.start', MagicMock(return_value=True)), \
  239. patch('salt.utils.process.SignalHandlingProcess.join', MagicMock(return_value=True)):
  240. mock_opts = self.get_config('minion', from_scratch=True)
  241. mock_opts['scheduler_before_connect'] = True
  242. io_loop = tornado.ioloop.IOLoop()
  243. io_loop.make_current()
  244. minion = salt.minion.Minion(mock_opts, io_loop=io_loop)
  245. try:
  246. try:
  247. minion.tune_in(start=True)
  248. except RuntimeError:
  249. pass
  250. # Make sure the scheduler is initialized but the beacons are not
  251. self.assertTrue('schedule' in minion.periodic_callbacks)
  252. self.assertTrue('beacons' not in minion.periodic_callbacks)
  253. finally:
  254. minion.destroy()
  255. def test_when_ping_interval_is_set_the_callback_should_be_added_to_periodic_callbacks(self):
  256. with patch('salt.minion.Minion.ctx', MagicMock(return_value={})), \
  257. patch('salt.minion.Minion.sync_connect_master', MagicMock(side_effect=RuntimeError('stop execution'))), \
  258. patch('salt.utils.process.SignalHandlingProcess.start', MagicMock(return_value=True)), \
  259. patch('salt.utils.process.SignalHandlingProcess.join', MagicMock(return_value=True)):
  260. mock_opts = self.get_config('minion', from_scratch=True)
  261. mock_opts['ping_interval'] = 10
  262. io_loop = tornado.ioloop.IOLoop()
  263. io_loop.make_current()
  264. minion = salt.minion.Minion(mock_opts, io_loop=io_loop)
  265. try:
  266. try:
  267. minion.connected = MagicMock(side_effect=(False, True))
  268. minion._fire_master_minion_start = MagicMock()
  269. minion.tune_in(start=False)
  270. except RuntimeError:
  271. pass
  272. # Make sure the scheduler is initialized but the beacons are not
  273. self.assertTrue('ping' in minion.periodic_callbacks)
  274. finally:
  275. minion.destroy()
  276. def test_minion_retry_dns_count(self):
  277. '''
  278. Tests that the resolve_dns will retry dns look ups for a maximum of
  279. 3 times before raising a SaltMasterUnresolvableError exception.
  280. '''
  281. with patch.dict(__opts__, {'ipv6': False, 'master': 'dummy',
  282. 'master_port': '4555',
  283. 'retry_dns': 1, 'retry_dns_count': 3}):
  284. self.assertRaises(SaltMasterUnresolvableError,
  285. salt.minion.resolve_dns, __opts__)
  286. def test_gen_modules_executors(self):
  287. '''
  288. Ensure gen_modules is called with the correct arguments #54429
  289. '''
  290. mock_opts = self.get_config('minion', from_scratch=True)
  291. io_loop = tornado.ioloop.IOLoop()
  292. io_loop.make_current()
  293. minion = salt.minion.Minion(mock_opts, io_loop=io_loop)
  294. class MockPillarCompiler(object):
  295. def compile_pillar(self):
  296. return {}
  297. try:
  298. with patch('salt.pillar.get_pillar', return_value=MockPillarCompiler()):
  299. with patch('salt.loader.executors') as execmock:
  300. minion.gen_modules()
  301. assert execmock.called_with(minion.opts, minion.functions)
  302. finally:
  303. minion.destroy()
  304. @skipIf(NO_MOCK, NO_MOCK_REASON)
  305. class MinionAsyncTestCase(TestCase, AdaptedConfigurationTestCaseMixin, tornado.testing.AsyncTestCase):
  306. @skip_if_not_root
  307. def test_sock_path_len(self):
  308. '''
  309. This tests whether or not a larger hash causes the sock path to exceed
  310. the system's max sock path length. See the below link for more
  311. information.
  312. https://github.com/saltstack/salt/issues/12172#issuecomment-43903643
  313. '''
  314. opts = {
  315. 'id': 'salt-testing',
  316. 'hash_type': 'sha512',
  317. 'sock_dir': os.path.join(salt.syspaths.SOCK_DIR, 'minion'),
  318. 'extension_modules': ''
  319. }
  320. with patch.dict(__opts__, opts):
  321. try:
  322. event_publisher = event.AsyncEventPublisher(__opts__)
  323. result = True
  324. except ValueError:
  325. # There are rare cases where we operate a closed socket, especially in containers.
  326. # In this case, don't fail the test because we'll catch it down the road.
  327. result = True
  328. except SaltSystemExit:
  329. result = False
  330. self.assertTrue(result)