salt.py 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409
  1. # -*- encoding: utf-8 -*-
  2. #
  3. # The Qubes OS Project, http://www.qubes-os.org
  4. #
  5. # Copyright (C) 2017 Marek Marczykowski-Górecki
  6. # <marmarek@invisiblethingslab.com>
  7. #
  8. # This program is free software; you can redistribute it and/or modify
  9. # it under the terms of the GNU General Public License as published by
  10. # the Free Software Foundation; either version 2 of the License, or
  11. # (at your option) any later version.
  12. #
  13. # This program is distributed in the hope that it will be useful,
  14. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  15. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  16. # GNU General Public License for more details.
  17. #
  18. # You should have received a copy of the GNU General Public License along
  19. # with this program; if not, see <http://www.gnu.org/licenses/>.
  20. import asyncio
  21. import json
  22. import os
  23. import shutil
  24. import subprocess
  25. import sys
  26. import qubes.tests
  27. class SaltTestMixin(object):
  28. def setUp(self):
  29. super().setUp()
  30. self.salt_testdir = '/srv/salt/test_salt'
  31. os.makedirs(self.salt_testdir, exist_ok=True)
  32. def tearDown(self):
  33. shutil.rmtree(self.salt_testdir)
  34. try:
  35. tops = '/srv/salt/_tops/base'
  36. for top_link in os.listdir(tops):
  37. path = os.path.join(tops, top_link)
  38. target = os.readlink(path)
  39. if target.startswith(self.salt_testdir):
  40. os.unlink(path)
  41. except FileNotFoundError:
  42. pass
  43. super().tearDown()
  44. def salt_call(self, cmd):
  45. full_cmd = ['qubesctl']
  46. if '--dom0-only' in cmd:
  47. full_cmd.insert(1, '--dom0-only')
  48. cmd.remove('--dom0-only')
  49. full_cmd.extend(cmd)
  50. full_cmd.append('--out=json')
  51. p = self.loop.run_until_complete(asyncio.create_subprocess_exec(
  52. *full_cmd, stdout=subprocess.PIPE))
  53. output, _ = self.loop.run_until_complete(p.communicate())
  54. if p.returncode != 0:
  55. raise AssertionError(
  56. 'Salt command \'{}\' failed with code {}. '
  57. 'Full output: {}'.format(full_cmd, p.returncode, output))
  58. return output.decode()
  59. def dom0_salt_call_json(self, cmd):
  60. return json.loads(self.salt_call(['--dom0-only'] + cmd))
  61. class TC_00_Dom0(SaltTestMixin, qubes.tests.SystemTestCase):
  62. def test_000_top_enable_disable(self):
  63. with open(os.path.join(self.salt_testdir, 'something.sls'), 'w') as f:
  64. f.write('test-top-enable:\n')
  65. f.write(' test.succeed_without_changes: []\n')
  66. with open(os.path.join(self.salt_testdir, 'something.top'), 'w') as f:
  67. f.write('base:\n')
  68. f.write(' dom0:\n')
  69. f.write(' - test_salt.something\n')
  70. cmd_output = self.dom0_salt_call_json(
  71. ['top.enable', 'test_salt.something'])
  72. self.assertEqual(cmd_output,
  73. {'local': {'test_salt.something.top': {'status': 'enabled'}}})
  74. cmd_output = self.dom0_salt_call_json(['state.show_top'])
  75. self.assertIn('local', cmd_output)
  76. self.assertIn('base', cmd_output['local'])
  77. self.assertIn('test_salt.something', cmd_output['local']['base'])
  78. cmd_output = self.dom0_salt_call_json(
  79. ['top.disable', 'test_salt.something'])
  80. #self.assertEqual(cmd_output,
  81. # {'local': {'test_salt.something.top': {'status': 'disabled'}}})
  82. cmd_output = self.dom0_salt_call_json(['state.show_top'])
  83. self.assertIn('local', cmd_output)
  84. self.assertNotIn('test_salt.something', cmd_output['local'].get('base', []))
  85. def test_001_state_sls(self):
  86. with open(os.path.join(self.salt_testdir, 'something.sls'), 'w') as f:
  87. f.write('test-top-enable:\n')
  88. f.write(' test.succeed_without_changes: []\n')
  89. cmd_output = self.dom0_salt_call_json(
  90. ['state.sls', 'test_salt.something'])
  91. state_id = 'test_|-test-top-enable_|-test-top-enable_|-succeed_without_changes'
  92. self.assertIn('local', cmd_output)
  93. self.assertIn(state_id, cmd_output['local'])
  94. self.assertIn('start_time', cmd_output['local'][state_id])
  95. del cmd_output['local'][state_id]['start_time']
  96. self.assertIn('duration', cmd_output['local'][state_id])
  97. del cmd_output['local'][state_id]['duration']
  98. self.assertEqual(cmd_output,
  99. {'local': {state_id: {
  100. 'name': 'test-top-enable',
  101. 'comment': 'Success!',
  102. 'result': True,
  103. '__run_num__': 0,
  104. '__sls__': 'test_salt.something',
  105. 'changes': {},
  106. '__id__': 'test-top-enable'
  107. }}})
  108. def test_010_create_vm(self):
  109. vmname = self.make_vm_name('appvm')
  110. with open(os.path.join(self.salt_testdir, 'create_vm.sls'), 'w') as f:
  111. f.write(vmname + ':\n')
  112. f.write(' qvm.vm:\n')
  113. f.write(' - present:\n')
  114. f.write(' - label: orange\n')
  115. f.write(' - prefs:\n')
  116. f.write(' - vcpus: 1\n')
  117. cmd_output = self.dom0_salt_call_json(
  118. ['state.sls', 'test_salt.create_vm'])
  119. state_out = list(cmd_output['local'].values())[0]
  120. del state_out['start_time']
  121. del state_out['duration']
  122. self.assertEqual(state_out, {
  123. 'comment': '====== [\'present\'] ======\n'
  124. '/usr/bin/qvm-create {} --class=AppVM --label=orange \n'
  125. '\n'
  126. '====== [\'prefs\'] ======\n'.format(vmname),
  127. 'name': vmname,
  128. 'result': True,
  129. 'changes': {
  130. 'qvm.prefs': {'qvm.create': {
  131. 'vcpus': {'new': 1, 'old': '*default*'}
  132. }
  133. },
  134. },
  135. '__sls__': 'test_salt.create_vm',
  136. '__run_num__': 0,
  137. '__id__': vmname,
  138. })
  139. self.assertIn(vmname, self.app.domains)
  140. vm = self.app.domains[vmname]
  141. self.assertEqual(str(vm.label), 'orange')
  142. self.assertEqual(vm.vcpus, 1)
  143. def test_011_set_prefs(self):
  144. vmname = self.make_vm_name('appvm')
  145. vm = self.app.add_new_vm('AppVM', label='red',
  146. name=vmname)
  147. self.loop.run_until_complete(vm.create_on_disk())
  148. with open(os.path.join(self.salt_testdir, 'create_vm.sls'), 'w') as f:
  149. f.write(vmname + ':\n')
  150. f.write(' qvm.vm:\n')
  151. f.write(' - present:\n')
  152. f.write(' - label: orange\n')
  153. f.write(' - prefs:\n')
  154. f.write(' - vcpus: 1\n')
  155. cmd_output = self.dom0_salt_call_json(
  156. ['state.sls', 'test_salt.create_vm'])
  157. state_out = list(cmd_output['local'].values())[0]
  158. del state_out['start_time']
  159. del state_out['duration']
  160. self.assertEqual(state_out, {
  161. 'comment': '====== [\'present\'] ======\n'
  162. '[SKIP] A VM with the name \'{}\' already exists.\n'
  163. '\n'
  164. '====== [\'prefs\'] ======\n'.format(vmname),
  165. 'name': vmname,
  166. 'result': True,
  167. 'changes': {
  168. 'qvm.prefs': {'qvm.create': {
  169. 'vcpus': {'new': 1, 'old': '*default*'}
  170. }
  171. },
  172. },
  173. '__sls__': 'test_salt.create_vm',
  174. '__run_num__': 0,
  175. '__id__': vmname,
  176. })
  177. self.assertIn(vmname, self.app.domains)
  178. vm = self.app.domains[vmname]
  179. self.assertEqual(str(vm.label), 'red')
  180. self.assertEqual(vm.vcpus, 1)
  181. def test_012_tags(self):
  182. vmname = self.make_vm_name('appvm')
  183. vm = self.app.add_new_vm('AppVM', label='red',
  184. name=vmname)
  185. self.loop.run_until_complete(vm.create_on_disk())
  186. new_tags = list(sorted(list(vm.tags) + ['tag1', 'tag2']))
  187. vm.tags.add('tag1')
  188. vm.tags.add('tag3')
  189. old_tags = list(sorted(vm.tags))
  190. with open(os.path.join(self.salt_testdir, 'test_state.sls'), 'w') as f:
  191. f.write(vmname + ':\n')
  192. f.write(' qvm.vm:\n')
  193. f.write(' - tags:\n')
  194. f.write(' - present:\n')
  195. f.write(' - tag1\n')
  196. f.write(' - tag2\n')
  197. f.write(' - absent:\n')
  198. f.write(' - tag3\n')
  199. f.write(' - tag4\n')
  200. cmd_output = self.dom0_salt_call_json(
  201. ['state.sls', 'test_salt.test_state'])
  202. state_out = list(cmd_output['local'].values())[0]
  203. del state_out['start_time']
  204. del state_out['duration']
  205. self.maxDiff = None
  206. self.assertEqual(state_out, {
  207. 'comment': '====== [\'tags\'] ======\n',
  208. 'name': vmname,
  209. 'result': True,
  210. 'changes': {
  211. 'qvm.tags': {'qvm.tags': {
  212. 'new': new_tags, 'old': old_tags,
  213. }
  214. },
  215. },
  216. '__sls__': 'test_salt.test_state',
  217. '__run_num__': 0,
  218. '__id__': vmname,
  219. })
  220. self.assertIn(vmname, self.app.domains)
  221. vm = self.app.domains[vmname]
  222. self.assertEqual(set(vm.tags), set(new_tags))
  223. def test_020_qubes_pillar(self):
  224. vmname = self.make_vm_name('appvm')
  225. vm = self.app.add_new_vm('AppVM', label='red',
  226. name=vmname)
  227. self.loop.run_until_complete(vm.create_on_disk())
  228. cmd_output = self.dom0_salt_call_json(
  229. ['pillar.items', '--id=' + vmname])
  230. self.assertIn('local', cmd_output)
  231. self.assertIn('qubes', cmd_output['local'])
  232. qubes_pillar = cmd_output['local']['qubes']
  233. self.assertEqual(qubes_pillar, {
  234. 'type': 'app',
  235. 'netvm': str(vm.netvm),
  236. 'template': str(vm.template),
  237. })
  238. class SaltVMTestMixin(SaltTestMixin):
  239. template = None
  240. def setUp(self):
  241. if self.template.startswith('whonix'):
  242. self.skipTest('Whonix not supported as salt VM')
  243. super(SaltVMTestMixin, self).setUp()
  244. self.init_default_template(self.template)
  245. dispvm_tpl_name = self.make_vm_name('disp-tpl')
  246. dispvm_tpl = self.app.add_new_vm('AppVM', label='red',
  247. template_for_dispvms=True, name=dispvm_tpl_name)
  248. self.loop.run_until_complete(dispvm_tpl.create_on_disk())
  249. self.app.default_dispvm = dispvm_tpl
  250. def tearDown(self):
  251. self.app.default_dispvm = None
  252. super(SaltVMTestMixin, self).tearDown()
  253. def test_000_simple_sls(self):
  254. vmname = self.make_vm_name('target')
  255. self.vm = self.app.add_new_vm('AppVM', name=vmname, label='red')
  256. self.loop.run_until_complete(self.vm.create_on_disk())
  257. # start the VM manually, so it stays running after applying salt state
  258. self.loop.run_until_complete(self.vm.start())
  259. with open(os.path.join(self.salt_testdir, 'something.sls'), 'w') as f:
  260. f.write('/home/user/testfile:\n')
  261. f.write(' file.managed:\n')
  262. f.write(' - contents: |\n')
  263. f.write(' this is test\n')
  264. with open(os.path.join(self.salt_testdir, 'something.top'), 'w') as f:
  265. f.write('base:\n')
  266. f.write(' {}:\n'.format(vmname))
  267. f.write(' - test_salt.something\n')
  268. # enable so state.show_top will not be empty, otherwise qubesctl will
  269. # skip the VM; but we don't use state.highstate
  270. self.dom0_salt_call_json(['top.enable', 'test_salt.something'])
  271. state_output = self.salt_call(
  272. ['--skip-dom0', '--show-output', '--targets=' + vmname,
  273. 'state.sls', 'test_salt.something'])
  274. expected_output = vmname + ':\n'
  275. self.assertTrue(state_output.startswith(expected_output),
  276. 'Full output: ' + state_output)
  277. state_id = 'file_|-/home/user/testfile_|-/home/user/testfile_|-managed'
  278. # drop the header
  279. state_output_json = json.loads(state_output[len(expected_output):])
  280. state_output_json = state_output_json[vmname][state_id]
  281. try:
  282. del state_output_json['duration']
  283. del state_output_json['start_time']
  284. except KeyError:
  285. pass
  286. try:
  287. del state_output_json['pchanges']
  288. except KeyError:
  289. pass
  290. try:
  291. # older salt do not report this
  292. self.assertEqual(state_output_json['__id__'], '/home/user/testfile')
  293. del state_output_json['__id__']
  294. except KeyError:
  295. pass
  296. try:
  297. # or sls file
  298. self.assertEqual(state_output_json['__sls__'],
  299. 'test_salt.something')
  300. del state_output_json['__sls__']
  301. except KeyError:
  302. pass
  303. # different output depending on salt version
  304. expected_output = {
  305. '__run_num__': 0,
  306. 'changes': {
  307. 'diff': 'New file',
  308. },
  309. 'name': '/home/user/testfile',
  310. 'comment': 'File /home/user/testfile updated',
  311. 'result': True,
  312. }
  313. self.assertEqual(state_output_json, expected_output)
  314. stdout, stderr = self.loop.run_until_complete(self.vm.run_for_stdio(
  315. 'cat /home/user/testfile'))
  316. self.assertEqual(stdout, b'this is test\n')
  317. self.assertEqual(stderr, b'')
  318. def test_001_multi_state_highstate(self):
  319. vmname = self.make_vm_name('target')
  320. self.vm = self.app.add_new_vm('AppVM', name=vmname, label='red')
  321. self.loop.run_until_complete(self.vm.create_on_disk())
  322. # start the VM manually, so it stays running after applying salt state
  323. self.loop.run_until_complete(self.vm.start())
  324. states = ('something', 'something2')
  325. for state in states:
  326. with open(os.path.join(self.salt_testdir, state + '.sls'), 'w') as f:
  327. f.write('/home/user/{}:\n'.format(state))
  328. f.write(' file.managed:\n')
  329. f.write(' - contents: |\n')
  330. f.write(' this is test\n')
  331. with open(os.path.join(self.salt_testdir, state + '.top'), 'w') as f:
  332. f.write('base:\n')
  333. f.write(' {}:\n'.format(vmname))
  334. f.write(' - test_salt.{}\n'.format(state))
  335. self.dom0_salt_call_json(['top.enable', 'test_salt.something'])
  336. self.dom0_salt_call_json(['top.enable', 'test_salt.something2'])
  337. state_output = self.salt_call(
  338. ['--skip-dom0', '--show-output', '--targets=' + vmname,
  339. 'state.highstate'])
  340. expected_output = vmname + ':\n'
  341. self.assertTrue(state_output.startswith(expected_output),
  342. 'Full output: ' + state_output)
  343. state_output_json = json.loads(state_output[len(expected_output):])
  344. for state in states:
  345. state_id = \
  346. 'file_|-/home/user/{0}_|-/home/user/{0}_|-managed'.format(state)
  347. # drop the header
  348. self.assertIn(state_id, state_output_json[vmname])
  349. state_output_single = state_output_json[vmname][state_id]
  350. self.assertTrue(state_output_single['result'])
  351. self.assertNotEqual(state_output_single['changes'], {})
  352. stdout, stderr = self.loop.run_until_complete(self.vm.run_for_stdio(
  353. 'cat /home/user/' + state))
  354. self.assertEqual(stdout, b'this is test\n')
  355. self.assertEqual(stderr, b'')
  356. def create_testcases_for_templates():
  357. return qubes.tests.create_testcases_for_templates('TC_10_VMSalt',
  358. SaltVMTestMixin, qubes.tests.SystemTestCase,
  359. module=sys.modules[__name__])
  360. def load_tests(loader, tests, pattern):
  361. tests.addTests(loader.loadTestsFromNames(
  362. create_testcases_for_templates()))
  363. return tests
  364. qubes.tests.maybe_create_testcases_on_import(create_testcases_for_templates)