1
0

test_minion.py 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370
  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.copy()
  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.copy()
  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.copy()
  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.copy()
  181. mock_opts['__role'] = 'minion'
  182. mock_opts['minion_jid_queue_hwm'] = 100
  183. mock_opts["process_count_max"] = process_count_max
  184. io_loop = tornado.ioloop.IOLoop()
  185. minion = salt.minion.Minion(mock_opts, jid_queue=[], io_loop=io_loop)
  186. try:
  187. # mock gen.sleep to throw a special Exception when called, so that we detect it
  188. class SleepCalledException(Exception):
  189. """Thrown when sleep is called"""
  190. pass
  191. tornado.gen.sleep.return_value.set_exception(SleepCalledException())
  192. # up until process_count_max: gen.sleep does not get called, processes are started normally
  193. for i in range(process_count_max):
  194. mock_data = {'fun': 'foo.bar',
  195. 'jid': i}
  196. io_loop.run_sync(lambda data=mock_data: minion._handle_decoded_payload(data))
  197. self.assertEqual(salt.utils.process.SignalHandlingProcess.start.call_count, i + 1)
  198. self.assertEqual(len(minion.jid_queue), i + 1)
  199. salt.utils.minion.running.return_value += [i]
  200. # above process_count_max: gen.sleep does get called, JIDs are created but no new processes are started
  201. mock_data = {'fun': 'foo.bar',
  202. 'jid': process_count_max + 1}
  203. self.assertRaises(SleepCalledException,
  204. lambda: io_loop.run_sync(lambda: minion._handle_decoded_payload(mock_data)))
  205. self.assertEqual(salt.utils.process.SignalHandlingProcess.start.call_count,
  206. process_count_max)
  207. self.assertEqual(len(minion.jid_queue), process_count_max + 1)
  208. finally:
  209. minion.destroy()
  210. def test_beacons_before_connect(self):
  211. '''
  212. Tests that the 'beacons_before_connect' option causes the beacons to be initialized before connect.
  213. '''
  214. with patch('salt.minion.Minion.ctx', MagicMock(return_value={})), \
  215. patch('salt.minion.Minion.sync_connect_master', MagicMock(side_effect=RuntimeError('stop execution'))), \
  216. patch('salt.utils.process.SignalHandlingProcess.start', MagicMock(return_value=True)), \
  217. patch('salt.utils.process.SignalHandlingProcess.join', MagicMock(return_value=True)):
  218. mock_opts = self.get_config('minion', from_scratch=True)
  219. mock_opts['beacons_before_connect'] = True
  220. io_loop = tornado.ioloop.IOLoop()
  221. io_loop.make_current()
  222. minion = salt.minion.Minion(mock_opts, io_loop=io_loop)
  223. try:
  224. try:
  225. minion.tune_in(start=True)
  226. except RuntimeError:
  227. pass
  228. # Make sure beacons are initialized but the sheduler is not
  229. self.assertTrue('beacons' in minion.periodic_callbacks)
  230. self.assertTrue('schedule' not in minion.periodic_callbacks)
  231. finally:
  232. minion.destroy()
  233. def test_scheduler_before_connect(self):
  234. '''
  235. Tests that the 'scheduler_before_connect' option causes the scheduler to be initialized before connect.
  236. '''
  237. with patch('salt.minion.Minion.ctx', MagicMock(return_value={})), \
  238. patch('salt.minion.Minion.sync_connect_master', MagicMock(side_effect=RuntimeError('stop execution'))), \
  239. patch('salt.utils.process.SignalHandlingProcess.start', MagicMock(return_value=True)), \
  240. patch('salt.utils.process.SignalHandlingProcess.join', MagicMock(return_value=True)):
  241. mock_opts = self.get_config('minion', from_scratch=True)
  242. mock_opts['scheduler_before_connect'] = True
  243. io_loop = tornado.ioloop.IOLoop()
  244. io_loop.make_current()
  245. minion = salt.minion.Minion(mock_opts, io_loop=io_loop)
  246. try:
  247. try:
  248. minion.tune_in(start=True)
  249. except RuntimeError:
  250. pass
  251. # Make sure the scheduler is initialized but the beacons are not
  252. self.assertTrue('schedule' in minion.periodic_callbacks)
  253. self.assertTrue('beacons' not in minion.periodic_callbacks)
  254. finally:
  255. minion.destroy()
  256. def test_when_ping_interval_is_set_the_callback_should_be_added_to_periodic_callbacks(self):
  257. with patch('salt.minion.Minion.ctx', MagicMock(return_value={})), \
  258. patch('salt.minion.Minion.sync_connect_master', MagicMock(side_effect=RuntimeError('stop execution'))), \
  259. patch('salt.utils.process.SignalHandlingProcess.start', MagicMock(return_value=True)), \
  260. patch('salt.utils.process.SignalHandlingProcess.join', MagicMock(return_value=True)):
  261. mock_opts = self.get_config('minion', from_scratch=True)
  262. mock_opts['ping_interval'] = 10
  263. io_loop = tornado.ioloop.IOLoop()
  264. io_loop.make_current()
  265. minion = salt.minion.Minion(mock_opts, io_loop=io_loop)
  266. try:
  267. try:
  268. minion.connected = MagicMock(side_effect=(False, True))
  269. minion._fire_master_minion_start = MagicMock()
  270. minion.tune_in(start=False)
  271. except RuntimeError:
  272. pass
  273. # Make sure the scheduler is initialized but the beacons are not
  274. self.assertTrue('ping' in minion.periodic_callbacks)
  275. finally:
  276. minion.destroy()
  277. def test_minion_retry_dns_count(self):
  278. '''
  279. Tests that the resolve_dns will retry dns look ups for a maximum of
  280. 3 times before raising a SaltMasterUnresolvableError exception.
  281. '''
  282. with patch.dict(__opts__, {'ipv6': False, 'master': 'dummy',
  283. 'master_port': '4555',
  284. 'retry_dns': 1, 'retry_dns_count': 3}):
  285. self.assertRaises(SaltMasterUnresolvableError,
  286. salt.minion.resolve_dns, __opts__)
  287. def test_gen_modules_executors(self):
  288. '''
  289. Ensure gen_modules is called with the correct arguments #54429
  290. '''
  291. mock_opts = self.get_config('minion', from_scratch=True)
  292. io_loop = tornado.ioloop.IOLoop()
  293. io_loop.make_current()
  294. minion = salt.minion.Minion(mock_opts, io_loop=io_loop)
  295. class MockPillarCompiler(object):
  296. def compile_pillar(self):
  297. return {}
  298. try:
  299. with patch('salt.pillar.get_pillar', return_value=MockPillarCompiler()):
  300. with patch('salt.loader.executors') as execmock:
  301. minion.gen_modules()
  302. assert execmock.called_with(minion.opts, minion.functions)
  303. finally:
  304. minion.destroy()
  305. @skipIf(NO_MOCK, NO_MOCK_REASON)
  306. class MinionAsyncTestCase(TestCase, AdaptedConfigurationTestCaseMixin, tornado.testing.AsyncTestCase):
  307. @skip_if_not_root
  308. def test_sock_path_len(self):
  309. '''
  310. This tests whether or not a larger hash causes the sock path to exceed
  311. the system's max sock path length. See the below link for more
  312. information.
  313. https://github.com/saltstack/salt/issues/12172#issuecomment-43903643
  314. '''
  315. opts = {
  316. 'id': 'salt-testing',
  317. 'hash_type': 'sha512',
  318. 'sock_dir': os.path.join(salt.syspaths.SOCK_DIR, 'minion'),
  319. 'extension_modules': ''
  320. }
  321. with patch.dict(__opts__, opts):
  322. try:
  323. event_publisher = event.AsyncEventPublisher(__opts__)
  324. result = True
  325. except ValueError:
  326. # There are rare cases where we operate a closed socket, especially in containers.
  327. # In this case, don't fail the test because we'll catch it down the road.
  328. result = True
  329. except SaltSystemExit:
  330. result = False
  331. self.assertTrue(result)