test_reactor.py 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553
  1. # -*- coding: utf-8 -*-
  2. from __future__ import absolute_import, print_function, unicode_literals
  3. import codecs
  4. import glob
  5. import logging
  6. import os
  7. import textwrap
  8. import salt.loader
  9. import salt.utils.data
  10. import salt.utils.files
  11. import salt.utils.reactor as reactor
  12. import salt.utils.yaml
  13. from tests.support.unit import TestCase
  14. from tests.support.mixins import AdaptedConfigurationTestCaseMixin
  15. from tests.support.mock import (
  16. patch,
  17. MagicMock,
  18. Mock,
  19. mock_open,
  20. )
  21. REACTOR_CONFIG = '''\
  22. reactor:
  23. - old_runner:
  24. - /srv/reactor/old_runner.sls
  25. - old_wheel:
  26. - /srv/reactor/old_wheel.sls
  27. - old_local:
  28. - /srv/reactor/old_local.sls
  29. - old_cmd:
  30. - /srv/reactor/old_cmd.sls
  31. - old_caller:
  32. - /srv/reactor/old_caller.sls
  33. - new_runner:
  34. - /srv/reactor/new_runner.sls
  35. - new_wheel:
  36. - /srv/reactor/new_wheel.sls
  37. - new_local:
  38. - /srv/reactor/new_local.sls
  39. - new_cmd:
  40. - /srv/reactor/new_cmd.sls
  41. - new_caller:
  42. - /srv/reactor/new_caller.sls
  43. '''
  44. REACTOR_DATA = {
  45. 'runner': {'data': {'message': 'This is an error'}},
  46. 'wheel': {'data': {'id': 'foo'}},
  47. 'local': {'data': {'pkg': 'zsh', 'repo': 'updates'}},
  48. 'cmd': {'data': {'pkg': 'zsh', 'repo': 'updates'}},
  49. 'caller': {'data': {'path': '/tmp/foo'}},
  50. }
  51. SLS = {
  52. '/srv/reactor/old_runner.sls': textwrap.dedent('''\
  53. raise_error:
  54. runner.error.error:
  55. - name: Exception
  56. - message: {{ data['data']['message'] }}
  57. '''),
  58. '/srv/reactor/old_wheel.sls': textwrap.dedent('''\
  59. remove_key:
  60. wheel.key.delete:
  61. - match: {{ data['data']['id'] }}
  62. '''),
  63. '/srv/reactor/old_local.sls': textwrap.dedent('''\
  64. install_zsh:
  65. local.state.single:
  66. - tgt: test
  67. - arg:
  68. - pkg.installed
  69. - {{ data['data']['pkg'] }}
  70. - kwarg:
  71. fromrepo: {{ data['data']['repo'] }}
  72. '''),
  73. '/srv/reactor/old_cmd.sls': textwrap.dedent('''\
  74. install_zsh:
  75. cmd.state.single:
  76. - tgt: test
  77. - arg:
  78. - pkg.installed
  79. - {{ data['data']['pkg'] }}
  80. - kwarg:
  81. fromrepo: {{ data['data']['repo'] }}
  82. '''),
  83. '/srv/reactor/old_caller.sls': textwrap.dedent('''\
  84. touch_file:
  85. caller.file.touch:
  86. - args:
  87. - {{ data['data']['path'] }}
  88. '''),
  89. '/srv/reactor/new_runner.sls': textwrap.dedent('''\
  90. raise_error:
  91. runner.error.error:
  92. - args:
  93. - name: Exception
  94. - message: {{ data['data']['message'] }}
  95. '''),
  96. '/srv/reactor/new_wheel.sls': textwrap.dedent('''\
  97. remove_key:
  98. wheel.key.delete:
  99. - args:
  100. - match: {{ data['data']['id'] }}
  101. '''),
  102. '/srv/reactor/new_local.sls': textwrap.dedent('''\
  103. install_zsh:
  104. local.state.single:
  105. - tgt: test
  106. - args:
  107. - fun: pkg.installed
  108. - name: {{ data['data']['pkg'] }}
  109. - fromrepo: {{ data['data']['repo'] }}
  110. '''),
  111. '/srv/reactor/new_cmd.sls': textwrap.dedent('''\
  112. install_zsh:
  113. cmd.state.single:
  114. - tgt: test
  115. - args:
  116. - fun: pkg.installed
  117. - name: {{ data['data']['pkg'] }}
  118. - fromrepo: {{ data['data']['repo'] }}
  119. '''),
  120. '/srv/reactor/new_caller.sls': textwrap.dedent('''\
  121. touch_file:
  122. caller.file.touch:
  123. - args:
  124. - name: {{ data['data']['path'] }}
  125. '''),
  126. }
  127. LOW_CHUNKS = {
  128. # Note that the "name" value in the chunk has been overwritten by the
  129. # "name" argument in the SLS. This is one reason why the new schema was
  130. # needed.
  131. 'old_runner': [{
  132. 'state': 'runner',
  133. '__id__': 'raise_error',
  134. '__sls__': '/srv/reactor/old_runner.sls',
  135. 'order': 1,
  136. 'fun': 'error.error',
  137. 'name': 'Exception',
  138. 'message': 'This is an error',
  139. }],
  140. 'old_wheel': [{
  141. 'state': 'wheel',
  142. '__id__': 'remove_key',
  143. 'name': 'remove_key',
  144. '__sls__': '/srv/reactor/old_wheel.sls',
  145. 'order': 1,
  146. 'fun': 'key.delete',
  147. 'match': 'foo',
  148. }],
  149. 'old_local': [{
  150. 'state': 'local',
  151. '__id__': 'install_zsh',
  152. 'name': 'install_zsh',
  153. '__sls__': '/srv/reactor/old_local.sls',
  154. 'order': 1,
  155. 'tgt': 'test',
  156. 'fun': 'state.single',
  157. 'arg': ['pkg.installed', 'zsh'],
  158. 'kwarg': {'fromrepo': 'updates'},
  159. }],
  160. 'old_cmd': [{
  161. 'state': 'local', # 'cmd' should be aliased to 'local'
  162. '__id__': 'install_zsh',
  163. 'name': 'install_zsh',
  164. '__sls__': '/srv/reactor/old_cmd.sls',
  165. 'order': 1,
  166. 'tgt': 'test',
  167. 'fun': 'state.single',
  168. 'arg': ['pkg.installed', 'zsh'],
  169. 'kwarg': {'fromrepo': 'updates'},
  170. }],
  171. 'old_caller': [{
  172. 'state': 'caller',
  173. '__id__': 'touch_file',
  174. 'name': 'touch_file',
  175. '__sls__': '/srv/reactor/old_caller.sls',
  176. 'order': 1,
  177. 'fun': 'file.touch',
  178. 'args': ['/tmp/foo'],
  179. }],
  180. 'new_runner': [{
  181. 'state': 'runner',
  182. '__id__': 'raise_error',
  183. 'name': 'raise_error',
  184. '__sls__': '/srv/reactor/new_runner.sls',
  185. 'order': 1,
  186. 'fun': 'error.error',
  187. 'args': [
  188. {'name': 'Exception'},
  189. {'message': 'This is an error'},
  190. ],
  191. }],
  192. 'new_wheel': [{
  193. 'state': 'wheel',
  194. '__id__': 'remove_key',
  195. 'name': 'remove_key',
  196. '__sls__': '/srv/reactor/new_wheel.sls',
  197. 'order': 1,
  198. 'fun': 'key.delete',
  199. 'args': [
  200. {'match': 'foo'},
  201. ],
  202. }],
  203. 'new_local': [{
  204. 'state': 'local',
  205. '__id__': 'install_zsh',
  206. 'name': 'install_zsh',
  207. '__sls__': '/srv/reactor/new_local.sls',
  208. 'order': 1,
  209. 'tgt': 'test',
  210. 'fun': 'state.single',
  211. 'args': [
  212. {'fun': 'pkg.installed'},
  213. {'name': 'zsh'},
  214. {'fromrepo': 'updates'},
  215. ],
  216. }],
  217. 'new_cmd': [{
  218. 'state': 'local',
  219. '__id__': 'install_zsh',
  220. 'name': 'install_zsh',
  221. '__sls__': '/srv/reactor/new_cmd.sls',
  222. 'order': 1,
  223. 'tgt': 'test',
  224. 'fun': 'state.single',
  225. 'args': [
  226. {'fun': 'pkg.installed'},
  227. {'name': 'zsh'},
  228. {'fromrepo': 'updates'},
  229. ],
  230. }],
  231. 'new_caller': [{
  232. 'state': 'caller',
  233. '__id__': 'touch_file',
  234. 'name': 'touch_file',
  235. '__sls__': '/srv/reactor/new_caller.sls',
  236. 'order': 1,
  237. 'fun': 'file.touch',
  238. 'args': [
  239. {'name': '/tmp/foo'},
  240. ],
  241. }],
  242. }
  243. WRAPPER_CALLS = {
  244. 'old_runner': (
  245. 'error.error',
  246. {
  247. '__state__': 'runner',
  248. '__id__': 'raise_error',
  249. '__sls__': '/srv/reactor/old_runner.sls',
  250. '__user__': 'Reactor',
  251. 'order': 1,
  252. 'arg': [],
  253. 'kwarg': {
  254. 'name': 'Exception',
  255. 'message': 'This is an error',
  256. },
  257. 'name': 'Exception',
  258. 'message': 'This is an error',
  259. },
  260. ),
  261. 'old_wheel': (
  262. 'key.delete',
  263. {
  264. '__state__': 'wheel',
  265. '__id__': 'remove_key',
  266. 'name': 'remove_key',
  267. '__sls__': '/srv/reactor/old_wheel.sls',
  268. 'order': 1,
  269. '__user__': 'Reactor',
  270. 'arg': ['foo'],
  271. 'kwarg': {},
  272. 'match': 'foo',
  273. },
  274. ),
  275. 'old_local': {
  276. 'args': ('test', 'state.single'),
  277. 'kwargs': {
  278. 'state': 'local',
  279. '__id__': 'install_zsh',
  280. 'name': 'install_zsh',
  281. '__sls__': '/srv/reactor/old_local.sls',
  282. 'order': 1,
  283. 'arg': ['pkg.installed', 'zsh'],
  284. 'kwarg': {'fromrepo': 'updates'},
  285. },
  286. },
  287. 'old_cmd': {
  288. 'args': ('test', 'state.single'),
  289. 'kwargs': {
  290. 'state': 'local',
  291. '__id__': 'install_zsh',
  292. 'name': 'install_zsh',
  293. '__sls__': '/srv/reactor/old_cmd.sls',
  294. 'order': 1,
  295. 'arg': ['pkg.installed', 'zsh'],
  296. 'kwarg': {'fromrepo': 'updates'},
  297. },
  298. },
  299. 'old_caller': {
  300. 'args': ('file.touch', '/tmp/foo'),
  301. 'kwargs': {},
  302. },
  303. 'new_runner': (
  304. 'error.error',
  305. {
  306. '__state__': 'runner',
  307. '__id__': 'raise_error',
  308. 'name': 'raise_error',
  309. '__sls__': '/srv/reactor/new_runner.sls',
  310. '__user__': 'Reactor',
  311. 'order': 1,
  312. 'arg': (),
  313. 'kwarg': {
  314. 'name': 'Exception',
  315. 'message': 'This is an error',
  316. },
  317. },
  318. ),
  319. 'new_wheel': (
  320. 'key.delete',
  321. {
  322. '__state__': 'wheel',
  323. '__id__': 'remove_key',
  324. 'name': 'remove_key',
  325. '__sls__': '/srv/reactor/new_wheel.sls',
  326. 'order': 1,
  327. '__user__': 'Reactor',
  328. 'arg': (),
  329. 'kwarg': {'match': 'foo'},
  330. },
  331. ),
  332. 'new_local': {
  333. 'args': ('test', 'state.single'),
  334. 'kwargs': {
  335. 'state': 'local',
  336. '__id__': 'install_zsh',
  337. 'name': 'install_zsh',
  338. '__sls__': '/srv/reactor/new_local.sls',
  339. 'order': 1,
  340. 'arg': (),
  341. 'kwarg': {
  342. 'fun': 'pkg.installed',
  343. 'name': 'zsh',
  344. 'fromrepo': 'updates',
  345. },
  346. },
  347. },
  348. 'new_cmd': {
  349. 'args': ('test', 'state.single'),
  350. 'kwargs': {
  351. 'state': 'local',
  352. '__id__': 'install_zsh',
  353. 'name': 'install_zsh',
  354. '__sls__': '/srv/reactor/new_cmd.sls',
  355. 'order': 1,
  356. 'arg': (),
  357. 'kwarg': {
  358. 'fun': 'pkg.installed',
  359. 'name': 'zsh',
  360. 'fromrepo': 'updates',
  361. },
  362. },
  363. },
  364. 'new_caller': {
  365. 'args': ('file.touch',),
  366. 'kwargs': {'name': '/tmp/foo'},
  367. },
  368. }
  369. log = logging.getLogger(__name__)
  370. class TestReactor(TestCase, AdaptedConfigurationTestCaseMixin):
  371. '''
  372. Tests for constructing the low chunks to be executed via the Reactor
  373. '''
  374. @classmethod
  375. def setUpClass(cls):
  376. '''
  377. Load the reactor config for mocking
  378. '''
  379. cls.opts = cls.get_temp_config('master')
  380. reactor_config = salt.utils.yaml.safe_load(REACTOR_CONFIG)
  381. cls.opts.update(reactor_config)
  382. cls.reactor = reactor.Reactor(cls.opts)
  383. cls.reaction_map = salt.utils.data.repack_dictlist(reactor_config['reactor'])
  384. renderers = salt.loader.render(cls.opts, {})
  385. cls.render_pipe = [(renderers[x], '') for x in ('jinja', 'yaml')]
  386. @classmethod
  387. def tearDownClass(cls):
  388. del cls.opts
  389. del cls.reactor
  390. del cls.render_pipe
  391. def test_list_reactors(self):
  392. '''
  393. Ensure that list_reactors() returns the correct list of reactor SLS
  394. files for each tag.
  395. '''
  396. for schema in ('old', 'new'):
  397. for rtype in REACTOR_DATA:
  398. tag = '_'.join((schema, rtype))
  399. self.assertEqual(
  400. self.reactor.list_reactors(tag),
  401. self.reaction_map[tag]
  402. )
  403. def test_reactions(self):
  404. '''
  405. Ensure that the correct reactions are built from the configured SLS
  406. files and tag data.
  407. '''
  408. for schema in ('old', 'new'):
  409. for rtype in REACTOR_DATA:
  410. tag = '_'.join((schema, rtype))
  411. log.debug('test_reactions: processing %s', tag)
  412. reactors = self.reactor.list_reactors(tag)
  413. log.debug('test_reactions: %s reactors: %s', tag, reactors)
  414. # No globbing in our example SLS, and the files don't actually
  415. # exist, so mock glob.glob to just return back the path passed
  416. # to it.
  417. with patch.object(
  418. glob,
  419. 'glob',
  420. MagicMock(side_effect=lambda x: [x])):
  421. # The below four mocks are all so that
  422. # salt.template.compile_template() will read the templates
  423. # we've mocked up in the SLS global variable above.
  424. with patch.object(
  425. os.path, 'isfile',
  426. MagicMock(return_value=True)):
  427. with patch.object(
  428. salt.utils.files, 'is_empty',
  429. MagicMock(return_value=False)):
  430. with patch.object(
  431. codecs, 'open',
  432. mock_open(read_data=SLS[reactors[0]])):
  433. with patch.object(
  434. salt.template, 'template_shebang',
  435. MagicMock(return_value=self.render_pipe)):
  436. reactions = self.reactor.reactions(
  437. tag,
  438. REACTOR_DATA[rtype],
  439. reactors,
  440. )
  441. log.debug(
  442. 'test_reactions: %s reactions: %s',
  443. tag, reactions
  444. )
  445. self.assertEqual(reactions, LOW_CHUNKS[tag])
  446. class TestReactWrap(TestCase, AdaptedConfigurationTestCaseMixin):
  447. '''
  448. Tests that we are formulating the wrapper calls properly
  449. '''
  450. @classmethod
  451. def setUpClass(cls):
  452. cls.wrap = reactor.ReactWrap(cls.get_temp_config('master'))
  453. @classmethod
  454. def tearDownClass(cls):
  455. del cls.wrap
  456. def test_runner(self):
  457. '''
  458. Test runner reactions using both the old and new config schema
  459. '''
  460. for schema in ('old', 'new'):
  461. tag = '_'.join((schema, 'runner'))
  462. chunk = LOW_CHUNKS[tag][0]
  463. thread_pool = Mock()
  464. thread_pool.fire_async = Mock()
  465. with patch.object(self.wrap, 'pool', thread_pool):
  466. self.wrap.run(chunk)
  467. thread_pool.fire_async.assert_called_with(
  468. self.wrap.client_cache['runner'].low,
  469. args=WRAPPER_CALLS[tag]
  470. )
  471. def test_wheel(self):
  472. '''
  473. Test wheel reactions using both the old and new config schema
  474. '''
  475. for schema in ('old', 'new'):
  476. tag = '_'.join((schema, 'wheel'))
  477. chunk = LOW_CHUNKS[tag][0]
  478. thread_pool = Mock()
  479. thread_pool.fire_async = Mock()
  480. with patch.object(self.wrap, 'pool', thread_pool):
  481. self.wrap.run(chunk)
  482. thread_pool.fire_async.assert_called_with(
  483. self.wrap.client_cache['wheel'].low,
  484. args=WRAPPER_CALLS[tag]
  485. )
  486. def test_local(self):
  487. '''
  488. Test local reactions using both the old and new config schema
  489. '''
  490. for schema in ('old', 'new'):
  491. tag = '_'.join((schema, 'local'))
  492. chunk = LOW_CHUNKS[tag][0]
  493. client_cache = {'local': Mock()}
  494. client_cache['local'].cmd_async = Mock()
  495. with patch.object(self.wrap, 'client_cache', client_cache):
  496. self.wrap.run(chunk)
  497. client_cache['local'].cmd_async.assert_called_with(
  498. *WRAPPER_CALLS[tag]['args'],
  499. **WRAPPER_CALLS[tag]['kwargs']
  500. )
  501. def test_cmd(self):
  502. '''
  503. Test cmd reactions (alias for 'local') using both the old and new
  504. config schema
  505. '''
  506. for schema in ('old', 'new'):
  507. tag = '_'.join((schema, 'cmd'))
  508. chunk = LOW_CHUNKS[tag][0]
  509. client_cache = {'local': Mock()}
  510. client_cache['local'].cmd_async = Mock()
  511. with patch.object(self.wrap, 'client_cache', client_cache):
  512. self.wrap.run(chunk)
  513. client_cache['local'].cmd_async.assert_called_with(
  514. *WRAPPER_CALLS[tag]['args'],
  515. **WRAPPER_CALLS[tag]['kwargs']
  516. )
  517. def test_caller(self):
  518. '''
  519. Test caller reactions using both the old and new config schema
  520. '''
  521. for schema in ('old', 'new'):
  522. tag = '_'.join((schema, 'caller'))
  523. chunk = LOW_CHUNKS[tag][0]
  524. client_cache = {'caller': Mock()}
  525. client_cache['caller'].cmd = Mock()
  526. with patch.object(self.wrap, 'client_cache', client_cache):
  527. self.wrap.run(chunk)
  528. client_cache['caller'].cmd.assert_called_with(
  529. *WRAPPER_CALLS[tag]['args'],
  530. **WRAPPER_CALLS[tag]['kwargs']
  531. )