salt.py 15 KB

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