basic.py 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663
  1. # pylint: disable=invalid-name
  2. #
  3. # The Qubes OS Project, https://www.qubes-os.org/
  4. #
  5. # Copyright (C) 2014-2015
  6. # Marek Marczykowski-Górecki <marmarek@invisiblethingslab.com>
  7. # Copyright (C) 2015 Wojtek Porczyk <woju@invisiblethingslab.com>
  8. #
  9. # This library is free software; you can redistribute it and/or
  10. # modify it under the terms of the GNU Lesser General Public
  11. # License as published by the Free Software Foundation; either
  12. # version 2.1 of the License, or (at your option) any later version.
  13. #
  14. # This library is distributed in the hope that it will be useful,
  15. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  16. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  17. # Lesser General Public License for more details.
  18. #
  19. # You should have received a copy of the GNU Lesser General Public
  20. # License along with this library; if not, see <https://www.gnu.org/licenses/>.
  21. #
  22. from distutils import spawn
  23. import asyncio
  24. import os
  25. import subprocess
  26. import tempfile
  27. import time
  28. import unittest
  29. import collections
  30. import pkg_resources
  31. import shutil
  32. import sys
  33. import qubes
  34. import qubes.firewall
  35. import qubes.tests
  36. import qubes.storage
  37. import qubes.vm.appvm
  38. import qubes.vm.qubesvm
  39. import qubes.vm.standalonevm
  40. import qubes.vm.templatevm
  41. import libvirt # pylint: disable=import-error
  42. class TC_00_Basic(qubes.tests.SystemTestCase):
  43. def setUp(self):
  44. super(TC_00_Basic, self).setUp()
  45. self.init_default_template()
  46. def test_000_qubes_create(self):
  47. self.assertIsInstance(self.app, qubes.Qubes)
  48. def test_100_qvm_create(self):
  49. vmname = self.make_vm_name('appvm')
  50. vm = self.app.add_new_vm(qubes.vm.appvm.AppVM,
  51. name=vmname, template=self.app.default_template,
  52. label='red')
  53. self.assertIsNotNone(vm)
  54. self.assertEqual(vm.name, vmname)
  55. self.assertEqual(vm.template, self.app.default_template)
  56. self.loop.run_until_complete(vm.create_on_disk())
  57. with self.assertNotRaises(qubes.exc.QubesException):
  58. self.loop.run_until_complete(vm.storage.verify())
  59. def test_040_qdb_watch(self):
  60. flag = set()
  61. def handler(vm, event, path):
  62. if path == '/test-watch-path':
  63. flag.add(True)
  64. vm = self.app.domains[0]
  65. vm.watch_qdb_path('/test-watch-path')
  66. vm.add_handler('domain-qdb-change:/test-watch-path', handler)
  67. self.assertFalse(flag)
  68. vm.untrusted_qdb.write('/test-watch-path', 'test-value')
  69. self.loop.run_until_complete(asyncio.sleep(0.1))
  70. self.assertTrue(flag)
  71. @unittest.skipUnless(
  72. spawn.find_executable('xdotool'), "xdotool not installed")
  73. def test_120_start_standalone_with_cdrom_dom0(self):
  74. vmname = self.make_vm_name('appvm')
  75. self.vm = self.app.add_new_vm('StandaloneVM', label='red', name=vmname)
  76. self.loop.run_until_complete(self.vm.create_on_disk())
  77. self.vm.kernel = None
  78. self.vm.virt_mode = 'hvm'
  79. iso_path = self.create_bootable_iso()
  80. # start the VM using qvm-start tool, to test --cdrom option there
  81. p = self.loop.run_until_complete(asyncio.create_subprocess_exec(
  82. 'qvm-start', '--cdrom=dom0:' + iso_path, self.vm.name,
  83. stdout=subprocess.PIPE, stderr=subprocess.STDOUT))
  84. (stdout, _) = self.loop.run_until_complete(p.communicate())
  85. self.assertEqual(p.returncode, 0, stdout)
  86. # check if VM do not crash instantly
  87. self.loop.run_until_complete(asyncio.sleep(5))
  88. self.assertTrue(self.vm.is_running())
  89. # Type 'poweroff'
  90. subprocess.check_call(['xdotool', 'search', '--name', self.vm.name,
  91. 'type', '--window', '%1', 'poweroff\r'])
  92. for _ in range(10):
  93. if not self.vm.is_running():
  94. break
  95. self.loop.run_until_complete(asyncio.sleep(1))
  96. self.assertFalse(self.vm.is_running())
  97. def test_130_autostart_disable_on_remove(self):
  98. vm = self.app.add_new_vm(qubes.vm.appvm.AppVM,
  99. name=self.make_vm_name('vm'),
  100. template=self.app.default_template,
  101. label='red')
  102. self.assertIsNotNone(vm)
  103. self.loop.run_until_complete(vm.create_on_disk())
  104. vm.autostart = True
  105. self.assertTrue(os.path.exists(
  106. '/etc/systemd/system/multi-user.target.wants/'
  107. 'qubes-vm@{}.service'.format(vm.name)),
  108. "systemd service not enabled by autostart=True")
  109. del self.app.domains[vm]
  110. self.loop.run_until_complete(vm.remove_from_disk())
  111. self.assertFalse(os.path.exists(
  112. '/etc/systemd/system/multi-user.target.wants/'
  113. 'qubes-vm@{}.service'.format(vm.name)),
  114. "systemd service not disabled on domain remove")
  115. def _test_200_on_domain_start(self, vm, event, **_kwargs):
  116. '''Simulate domain crash just after startup'''
  117. vm.libvirt_domain.destroy()
  118. def test_200_shutdown_event_race(self):
  119. '''Regression test for 3164'''
  120. vmname = self.make_vm_name('appvm')
  121. self.vm = self.app.add_new_vm(qubes.vm.appvm.AppVM,
  122. name=vmname, template=self.app.default_template,
  123. label='red')
  124. # help the luck a little - don't wait for qrexec to easier win the race
  125. self.vm.features['qrexec'] = False
  126. self.loop.run_until_complete(self.vm.create_on_disk())
  127. # another way to help the luck a little - make sure the private
  128. # volume is first in (normally unordered) dict - this way if any
  129. # volume action fails, it will be at or after private volume - not
  130. # before (preventing private volume action)
  131. old_volumes = self.vm.volumes
  132. self.vm.volumes = collections.OrderedDict()
  133. self.vm.volumes['private'] = old_volumes.pop('private')
  134. self.vm.volumes.update(old_volumes.items())
  135. del old_volumes
  136. self.loop.run_until_complete(self.vm.start())
  137. # kill it the way it does not give a chance for domain-shutdown it
  138. # execute
  139. self.vm.libvirt_domain.destroy()
  140. # now, lets try to start the VM again, before domain-shutdown event
  141. # got handled (#3164), and immediately trigger second domain-shutdown
  142. self.vm.add_handler('domain-start', self._test_200_on_domain_start)
  143. self.loop.run_until_complete(self.vm.start())
  144. # and give a chance for both domain-shutdown handlers to execute
  145. self.loop.run_until_complete(asyncio.sleep(1))
  146. with self.assertNotRaises(qubes.exc.QubesException):
  147. # if the above caused two domain-shutdown handlers being called
  148. # one after another, private volume is gone
  149. self.loop.run_until_complete(self.vm.storage.verify())
  150. def _test_201_on_domain_pre_start(self, vm, event, **_kwargs):
  151. '''Simulate domain crash just after startup'''
  152. if not self.domain_shutdown_handled and not self.test_failure_reason:
  153. self.test_failure_reason = \
  154. 'domain-shutdown event was not dispatched before subsequent ' \
  155. 'start'
  156. self.domain_shutdown_handled = False
  157. def _test_201_domain_shutdown_handler(self, vm, event, **kwargs):
  158. if self.domain_shutdown_handled and not self.test_failure_reason:
  159. self.test_failure_reason = 'domain-shutdown event received twice'
  160. self.domain_shutdown_handled = True
  161. def test_201_shutdown_event_race(self):
  162. '''Regression test for 3164 - pure events edition'''
  163. vmname = self.make_vm_name('appvm')
  164. self.vm = self.app.add_new_vm(qubes.vm.appvm.AppVM,
  165. name=vmname, template=self.app.default_template,
  166. label='red')
  167. # help the luck a little - don't wait for qrexec to easier win the race
  168. self.vm.features['qrexec'] = False
  169. self.loop.run_until_complete(self.vm.create_on_disk())
  170. # do not throw exception from inside event handler - test framework
  171. # will not recover from it (various objects leaks)
  172. self.test_failure_reason = None
  173. self.domain_shutdown_handled = False
  174. self.vm.add_handler('domain-shutdown',
  175. self._test_201_domain_shutdown_handler)
  176. self.loop.run_until_complete(self.vm.start())
  177. if self.test_failure_reason:
  178. self.fail(self.test_failure_reason)
  179. self.vm.add_handler('domain-pre-start',
  180. self._test_201_on_domain_pre_start)
  181. # kill it the way it does not give a chance for domain-shutdown it
  182. # execute
  183. self.vm.libvirt_domain.destroy()
  184. # now, lets try to start the VM again, before domain-shutdown event
  185. # got handled (#3164), and immediately trigger second domain-shutdown
  186. self.vm.add_handler('domain-start', self._test_200_on_domain_start)
  187. self.loop.run_until_complete(self.vm.start())
  188. if self.test_failure_reason:
  189. self.fail(self.test_failure_reason)
  190. while self.vm.get_power_state() != 'Halted':
  191. self.loop.run_until_complete(asyncio.sleep(1))
  192. # and give a chance for both domain-shutdown handlers to execute
  193. self.loop.run_until_complete(asyncio.sleep(3))
  194. # wait for running shutdown handler to complete
  195. self.loop.run_until_complete(self.vm._domain_stopped_lock.acquire())
  196. self.vm._domain_stopped_lock.release()
  197. if self.test_failure_reason:
  198. self.fail(self.test_failure_reason)
  199. self.assertTrue(self.domain_shutdown_handled,
  200. 'second domain-shutdown event was not dispatched after domain '
  201. 'shutdown')
  202. def _check_udev_for_uuid(self, uuid_value):
  203. udev_data_path = '/run/udev/data'
  204. for udev_item in os.listdir(udev_data_path):
  205. # check only block devices
  206. if not udev_item.startswith('b'):
  207. continue
  208. with open(os.path.join(udev_data_path, udev_item)) as udev_file:
  209. self.assertNotIn(uuid_value, udev_file.read(),
  210. 'udev parsed filesystem UUID! ' + udev_item)
  211. def assertVolumesExcludedFromUdev(self, vm):
  212. try:
  213. # first boot, mkfs private volume
  214. self.loop.run_until_complete(vm.start())
  215. self.loop.run_until_complete(self.wait_for_session(vm))
  216. # get private volume UUID
  217. private_uuid, _ = self.loop.run_until_complete(
  218. vm.run_for_stdio('blkid -o value /dev/xvdb', user='root'))
  219. private_uuid = private_uuid.decode().splitlines()[0]
  220. # now check if dom0 udev know about it - it shouldn't
  221. self._check_udev_for_uuid(private_uuid)
  222. # now restart the VM and check again
  223. self.loop.run_until_complete(vm.shutdown(wait=True))
  224. self.loop.run_until_complete(vm.start())
  225. self._check_udev_for_uuid(private_uuid)
  226. finally:
  227. del vm
  228. def _test_140_on_domain_paused(self, vm, event, **kwargs):
  229. self.domain_paused_received = True
  230. def test_140_libvirt_events_reconnect(self):
  231. vmname = self.make_vm_name('vm')
  232. self.vm = self.app.add_new_vm(qubes.vm.appvm.AppVM,
  233. name=vmname, template=self.app.default_template,
  234. label='red')
  235. self.loop.run_until_complete(self.vm.create_on_disk())
  236. self.loop.run_until_complete(self.vm.start())
  237. p = self.loop.run_until_complete(asyncio.create_subprocess_exec(
  238. 'systemctl', 'restart', 'libvirtd'))
  239. self.loop.run_until_complete(p.communicate())
  240. # check if events still works
  241. self.domain_paused_received = False
  242. self.vm.add_handler('domain-paused', self._test_140_on_domain_paused)
  243. self.loop.run_until_complete(self.vm.pause())
  244. self.loop.run_until_complete(self.vm.kill())
  245. self.loop.run_until_complete(asyncio.sleep(1))
  246. self.assertTrue(self.domain_paused_received,
  247. 'event not received after libvirt restart')
  248. def test_141_libvirt_objects_reconnect(self):
  249. vmname = self.make_vm_name('vm')
  250. # make sure libvirt object is cached
  251. self.app.domains[0].libvirt_domain.isActive()
  252. p = self.loop.run_until_complete(asyncio.create_subprocess_exec(
  253. 'systemctl', 'restart', 'libvirtd'))
  254. self.loop.run_until_complete(p.communicate())
  255. # trigger reconnect
  256. with self.assertNotRaises(libvirt.libvirtError):
  257. self.app.vmm.libvirt_conn.getHostname()
  258. # check if vm object still works
  259. with self.assertNotRaises(libvirt.libvirtError):
  260. self.app.domains[0].libvirt_domain.isActive()
  261. def test_202_udev_block_exclude_default(self):
  262. '''Check if VM images are excluded from udev parsing -
  263. default volume pool'''
  264. vmname = self.make_vm_name('appvm')
  265. self.vm = self.app.add_new_vm(qubes.vm.appvm.AppVM,
  266. name=vmname, template=self.app.default_template,
  267. label='red')
  268. self.loop.run_until_complete(self.vm.create_on_disk())
  269. self.assertVolumesExcludedFromUdev(self.vm)
  270. def test_203_udev_block_exclude_varlibqubes(self):
  271. '''Check if VM images are excluded from udev parsing -
  272. varlibqubes pool'''
  273. vmname = self.make_vm_name('appvm')
  274. self.vm = self.app.add_new_vm(qubes.vm.appvm.AppVM,
  275. name=vmname, template=self.app.default_template,
  276. label='red')
  277. self.loop.run_until_complete(self.vm.create_on_disk(
  278. pool=self.app.pools['varlibqubes']))
  279. self.assertVolumesExcludedFromUdev(self.vm)
  280. def test_204_udev_block_exclude_custom_file(self):
  281. '''Check if VM images are excluded from udev parsing -
  282. custom file pool'''
  283. vmname = self.make_vm_name('appvm')
  284. pool_path = tempfile.mkdtemp(
  285. prefix='qubes-pool-', dir='/var/tmp')
  286. self.addCleanup(shutil.rmtree, pool_path)
  287. pool = self.loop.run_until_complete(
  288. self.app.add_pool('test-filep', dir_path=pool_path, driver='file'))
  289. self.vm = self.app.add_new_vm(qubes.vm.appvm.AppVM,
  290. name=vmname, template=self.app.default_template,
  291. label='red')
  292. self.loop.run_until_complete(self.vm.create_on_disk(
  293. pool=pool))
  294. self.assertVolumesExcludedFromUdev(self.vm)
  295. class TC_01_Properties(qubes.tests.SystemTestCase):
  296. # pylint: disable=attribute-defined-outside-init
  297. def setUp(self):
  298. super(TC_01_Properties, self).setUp()
  299. self.init_default_template()
  300. self.vmname = self.make_vm_name('appvm')
  301. self.vm = self.app.add_new_vm(qubes.vm.appvm.AppVM, name=self.vmname,
  302. template=self.app.default_template,
  303. label='red')
  304. self.loop.run_until_complete(self.vm.create_on_disk())
  305. self.addCleanup(self.cleanup_props)
  306. def cleanup_props(self):
  307. del self.vm
  308. def test_020_name_conflict_app(self):
  309. # TODO decide what exception should be here
  310. with self.assertRaises((qubes.exc.QubesException, ValueError)):
  311. self.vm2 = self.app.add_new_vm(qubes.vm.appvm.AppVM,
  312. name=self.vmname, template=self.app.default_template,
  313. label='red')
  314. self.loop.run_until_complete(self.vm2.create_on_disk())
  315. def test_021_name_conflict_template(self):
  316. # TODO decide what exception should be here
  317. with self.assertRaises((qubes.exc.QubesException, ValueError)):
  318. self.vm2 = self.app.add_new_vm(qubes.vm.templatevm.TemplateVM,
  319. name=self.vmname, label='red')
  320. self.loop.run_until_complete(self.vm2.create_on_disk())
  321. class TC_03_QvmRevertTemplateChanges(qubes.tests.SystemTestCase):
  322. # pylint: disable=attribute-defined-outside-init
  323. def setUp(self):
  324. super(TC_03_QvmRevertTemplateChanges, self).setUp()
  325. self.init_default_template()
  326. def cleanup_template(self):
  327. del self.test_template
  328. def setup_template(self):
  329. self.test_template = self.app.add_new_vm(
  330. qubes.vm.templatevm.TemplateVM,
  331. name=self.make_vm_name("pv-clone"),
  332. label='red'
  333. )
  334. self.addCleanup(self.cleanup_template)
  335. self.test_template.clone_properties(self.app.default_template)
  336. self.test_template.features.update(self.app.default_template.features)
  337. self.test_template.tags.update(self.app.default_template.tags)
  338. self.loop.run_until_complete(
  339. self.test_template.clone_disk_files(self.app.default_template))
  340. self.test_template.volumes['root'].revisions_to_keep = 3
  341. self.app.save()
  342. def get_rootimg_checksum(self):
  343. path = self.loop.run_until_complete(
  344. self.test_template.storage.export('root'))
  345. try:
  346. return subprocess.check_output(['sha1sum', path]).\
  347. decode().split(' ')[0]
  348. finally:
  349. self.loop.run_until_complete(
  350. self.test_template.storage.export_end('root', path))
  351. def _do_test(self):
  352. checksum_before = self.get_rootimg_checksum()
  353. self.loop.run_until_complete(self.test_template.start())
  354. self.loop.run_until_complete(self.wait_for_session(self.test_template))
  355. self.shutdown_and_wait(self.test_template)
  356. checksum_changed = self.get_rootimg_checksum()
  357. if checksum_before == checksum_changed:
  358. self.log.warning("template not modified, test result will be "
  359. "unreliable")
  360. self.assertNotEqual(self.test_template.volumes['root'].revisions, {})
  361. revert_cmd = ['qvm-volume', 'revert', self.test_template.name + ':root']
  362. p = self.loop.run_until_complete(asyncio.create_subprocess_exec(
  363. *revert_cmd))
  364. self.loop.run_until_complete(p.wait())
  365. self.assertEqual(p.returncode, 0)
  366. del p
  367. checksum_after = self.get_rootimg_checksum()
  368. self.assertEqual(checksum_before, checksum_after)
  369. def test_000_revert_linux(self):
  370. """
  371. Test qvm-revert-template-changes for PV template
  372. """
  373. self.setup_template()
  374. self._do_test()
  375. @unittest.skip('TODO: some non-linux system')
  376. def test_001_revert_non_linux(self):
  377. """
  378. Test qvm-revert-template-changes for HVM template
  379. """
  380. # TODO: have some system there, so the root.img will get modified
  381. self.setup_template()
  382. self._do_test()
  383. class TC_30_Gui_daemon(qubes.tests.SystemTestCase):
  384. def setUp(self):
  385. super(TC_30_Gui_daemon, self).setUp()
  386. self.init_default_template()
  387. @unittest.skipUnless(
  388. spawn.find_executable('xdotool'),
  389. "xdotool not installed")
  390. def test_000_clipboard(self):
  391. testvm1 = self.app.add_new_vm(qubes.vm.appvm.AppVM,
  392. name=self.make_vm_name('vm1'), label='red')
  393. self.loop.run_until_complete(testvm1.create_on_disk())
  394. testvm2 = self.app.add_new_vm(qubes.vm.appvm.AppVM,
  395. name=self.make_vm_name('vm2'), label='red')
  396. self.loop.run_until_complete(testvm2.create_on_disk())
  397. self.app.save()
  398. self.loop.run_until_complete(asyncio.gather(
  399. testvm1.start(),
  400. testvm2.start()))
  401. self.loop.run_until_complete(asyncio.gather(
  402. self.wait_for_session(testvm1),
  403. self.wait_for_session(testvm2)))
  404. window_title = 'user@{}'.format(testvm1.name)
  405. self.loop.run_until_complete(testvm1.run(
  406. 'zenity --text-info --editable --title={}'.format(window_title)))
  407. self.wait_for_window(window_title)
  408. time.sleep(0.5)
  409. test_string = "test{}".format(testvm1.xid)
  410. # Type and copy some text
  411. subprocess.check_call(['xdotool', 'search', '--name', window_title,
  412. 'windowactivate', '--sync',
  413. 'type', test_string])
  414. # second xdotool call because type --terminator do not work (SEGV)
  415. # additionally do not use search here, so window stack will be empty
  416. # and xdotool will use XTEST instead of generating events manually -
  417. # this will be much better - at least because events will have
  418. # correct timestamp (so gui-daemon would not drop the copy request)
  419. subprocess.check_call(['xdotool',
  420. 'key', 'ctrl+a', 'ctrl+c', 'ctrl+shift+c',
  421. 'Escape'])
  422. clipboard_content = \
  423. open('/var/run/qubes/qubes-clipboard.bin', 'r').read().strip()
  424. self.assertEqual(clipboard_content, test_string,
  425. "Clipboard copy operation failed - content")
  426. clipboard_source = \
  427. open('/var/run/qubes/qubes-clipboard.bin.source',
  428. 'r').read().strip()
  429. self.assertEqual(clipboard_source, testvm1.name,
  430. "Clipboard copy operation failed - owner")
  431. # Then paste it to the other window
  432. window_title = 'user@{}'.format(testvm2.name)
  433. p = self.loop.run_until_complete(testvm2.run(
  434. 'zenity --entry --title={} > /tmp/test.txt'.format(window_title)))
  435. self.wait_for_window(window_title)
  436. subprocess.check_call(['xdotool', 'key', '--delay', '100',
  437. 'ctrl+shift+v', 'ctrl+v', 'Return'])
  438. self.loop.run_until_complete(p.wait())
  439. # And compare the result
  440. (test_output, _) = self.loop.run_until_complete(
  441. testvm2.run_for_stdio('cat /tmp/test.txt'))
  442. self.assertEqual(test_string, test_output.strip().decode('ascii'))
  443. clipboard_content = \
  444. open('/var/run/qubes/qubes-clipboard.bin', 'r').read().strip()
  445. self.assertEqual(clipboard_content, "",
  446. "Clipboard not wiped after paste - content")
  447. clipboard_source = \
  448. open('/var/run/qubes/qubes-clipboard.bin.source', 'r').\
  449. read().strip()
  450. self.assertEqual(clipboard_source, "",
  451. "Clipboard not wiped after paste - owner")
  452. class TC_05_StandaloneVMMixin(object):
  453. def setUp(self):
  454. super(TC_05_StandaloneVMMixin, self).setUp()
  455. self.init_default_template(self.template)
  456. def test_000_create_start(self):
  457. self.testvm1 = self.app.add_new_vm(qubes.vm.standalonevm.StandaloneVM,
  458. name=self.make_vm_name('vm1'), label='red')
  459. self.testvm1.features.update(self.app.default_template.features)
  460. self.loop.run_until_complete(
  461. self.testvm1.clone_disk_files(self.app.default_template))
  462. self.app.save()
  463. self.loop.run_until_complete(self.testvm1.start())
  464. self.assertEqual(self.testvm1.get_power_state(), "Running")
  465. def test_100_resize_root_img(self):
  466. self.testvm1 = self.app.add_new_vm(qubes.vm.standalonevm.StandaloneVM,
  467. name=self.make_vm_name('vm1'), label='red')
  468. self.testvm1.features.update(self.app.default_template.features)
  469. self.loop.run_until_complete(
  470. self.testvm1.clone_disk_files(self.app.default_template))
  471. self.app.save()
  472. try:
  473. self.loop.run_until_complete(
  474. self.testvm1.storage.resize(self.testvm1.volumes['root'],
  475. 20 * 1024 ** 3))
  476. except (subprocess.CalledProcessError,
  477. qubes.storage.StoragePoolException) as e:
  478. # exception object would leak VM reference
  479. self.fail(str(e))
  480. self.assertEqual(self.testvm1.volumes['root'].size, 20 * 1024 ** 3)
  481. self.loop.run_until_complete(self.testvm1.start())
  482. # new_size in 1k-blocks
  483. (new_size, _) = self.loop.run_until_complete(
  484. self.testvm1.run_for_stdio('df --output=size /|tail -n 1'))
  485. # some safety margin for FS metadata
  486. self.assertGreater(int(new_size.strip()), 19 * 1024 ** 2)
  487. def test_101_resize_root_img_online(self):
  488. self.testvm1 = self.app.add_new_vm(qubes.vm.standalonevm.StandaloneVM,
  489. name=self.make_vm_name('vm1'), label='red')
  490. self.testvm1.features['qrexec'] = True
  491. self.loop.run_until_complete(
  492. self.testvm1.clone_disk_files(self.app.default_template))
  493. self.testvm1.features.update(self.app.default_template.features)
  494. self.app.save()
  495. self.loop.run_until_complete(self.testvm1.start())
  496. try:
  497. self.loop.run_until_complete(
  498. self.testvm1.storage.resize(self.testvm1.volumes['root'],
  499. 20 * 1024 ** 3))
  500. except (subprocess.CalledProcessError,
  501. qubes.storage.StoragePoolException) as e:
  502. # exception object would leak VM reference
  503. self.fail(str(e))
  504. self.assertEqual(self.testvm1.volumes['root'].size, 20 * 1024 ** 3)
  505. # new_size in 1k-blocks
  506. (new_size, _) = self.loop.run_until_complete(
  507. self.testvm1.run_for_stdio('df --output=size /|tail -n 1'))
  508. # some safety margin for FS metadata
  509. self.assertGreater(int(new_size.strip()), 19 * 1024 ** 2)
  510. class TC_06_AppVMMixin(object):
  511. template = None
  512. def setUp(self):
  513. super(TC_06_AppVMMixin, self).setUp()
  514. self.init_default_template(self.template)
  515. @unittest.skipUnless(
  516. spawn.find_executable('xdotool'), "xdotool not installed")
  517. def test_121_start_standalone_with_cdrom_vm(self):
  518. cdrom_vmname = self.make_vm_name('cdrom')
  519. self.cdrom_vm = self.app.add_new_vm('AppVM', label='red',
  520. name=cdrom_vmname)
  521. self.loop.run_until_complete(self.cdrom_vm.create_on_disk())
  522. self.loop.run_until_complete(self.cdrom_vm.start())
  523. iso_path = self.create_bootable_iso()
  524. with open(iso_path, 'rb') as iso_f:
  525. self.loop.run_until_complete(
  526. self.cdrom_vm.run_for_stdio('cat > /home/user/boot.iso',
  527. stdin=iso_f))
  528. vmname = self.make_vm_name('appvm')
  529. self.vm = self.app.add_new_vm('StandaloneVM', label='red', name=vmname)
  530. self.loop.run_until_complete(self.vm.create_on_disk())
  531. self.vm.kernel = None
  532. self.vm.virt_mode = 'hvm'
  533. # start the VM using qvm-start tool, to test --cdrom option there
  534. p = self.loop.run_until_complete(asyncio.create_subprocess_exec(
  535. 'qvm-start', '--cdrom=' + cdrom_vmname + ':/home/user/boot.iso',
  536. self.vm.name,
  537. stdout=subprocess.PIPE, stderr=subprocess.STDOUT))
  538. (stdout, _) = self.loop.run_until_complete(p.communicate())
  539. self.assertEqual(p.returncode, 0, stdout)
  540. # check if VM do not crash instantly
  541. self.loop.run_until_complete(asyncio.sleep(5))
  542. self.assertTrue(self.vm.is_running())
  543. # Type 'poweroff'
  544. subprocess.check_call(['xdotool', 'search', '--name', self.vm.name,
  545. 'type', '--window', '%1', 'poweroff\r'])
  546. for _ in range(10):
  547. if not self.vm.is_running():
  548. break
  549. self.loop.run_until_complete(asyncio.sleep(1))
  550. self.assertFalse(self.vm.is_running())
  551. def create_testcases_for_templates():
  552. yield from qubes.tests.create_testcases_for_templates('TC_05_StandaloneVM',
  553. TC_05_StandaloneVMMixin, qubes.tests.SystemTestCase,
  554. module=sys.modules[__name__])
  555. yield from qubes.tests.create_testcases_for_templates('TC_06_AppVM',
  556. TC_06_AppVMMixin, qubes.tests.SystemTestCase,
  557. module=sys.modules[__name__])
  558. def load_tests(loader, tests, pattern):
  559. tests.addTests(loader.loadTestsFromNames(
  560. create_testcases_for_templates()))
  561. return tests
  562. qubes.tests.maybe_create_testcases_on_import(create_testcases_for_templates)
  563. # vim: ts=4 sw=4 et