app.py 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536
  1. # pylint: disable=protected-access,pointless-statement
  2. #
  3. # The Qubes OS Project, https://www.qubes-os.org/
  4. #
  5. # Copyright (C) 2014-2015 Joanna Rutkowska <joanna@invisiblethingslab.com>
  6. # Copyright (C) 2014-2015 Wojtek Porczyk <woju@invisiblethingslab.com>
  7. #
  8. # This library is free software; you can redistribute it and/or
  9. # modify it under the terms of the GNU Lesser General Public
  10. # License as published by the Free Software Foundation; either
  11. # version 2.1 of the License, or (at your option) any later version.
  12. #
  13. # This library 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 GNU
  16. # Lesser General Public License for more details.
  17. #
  18. # You should have received a copy of the GNU Lesser General Public
  19. # License along with this library; if not, see <https://www.gnu.org/licenses/>.
  20. #
  21. import os
  22. import unittest.mock as mock
  23. import lxml.etree
  24. import qubes
  25. import qubes.events
  26. import qubes.tests
  27. import qubes.tests.init
  28. class TestApp(qubes.tests.TestEmitter):
  29. pass
  30. class TC_20_QubesHost(qubes.tests.QubesTestCase):
  31. sample_xc_domain_getinfo = [
  32. {'paused': 0, 'cpu_time': 243951379111104, 'ssidref': 0,
  33. 'hvm': 0, 'shutdown_reason': 255, 'dying': 0,
  34. 'mem_kb': 3733212, 'domid': 0, 'max_vcpu_id': 7,
  35. 'crashed': 0, 'running': 1, 'maxmem_kb': 3734236,
  36. 'shutdown': 0, 'online_vcpus': 8,
  37. 'handle': [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
  38. 'cpupool': 0, 'blocked': 0},
  39. {'paused': 0, 'cpu_time': 2849496569205, 'ssidref': 0,
  40. 'hvm': 0, 'shutdown_reason': 255, 'dying': 0,
  41. 'mem_kb': 303916, 'domid': 1, 'max_vcpu_id': 0,
  42. 'crashed': 0, 'running': 0, 'maxmem_kb': 308224,
  43. 'shutdown': 0, 'online_vcpus': 1,
  44. 'handle': [116, 174, 229, 207, 17, 1, 79, 39, 191, 37, 41,
  45. 186, 205, 158, 219, 8],
  46. 'cpupool': 0, 'blocked': 1},
  47. {'paused': 0, 'cpu_time': 249658663079978, 'ssidref': 0,
  48. 'hvm': 0, 'shutdown_reason': 255, 'dying': 0,
  49. 'mem_kb': 3782668, 'domid': 11, 'max_vcpu_id': 7,
  50. 'crashed': 0, 'running': 0, 'maxmem_kb': 3783692,
  51. 'shutdown': 0, 'online_vcpus': 8,
  52. 'handle': [169, 95, 55, 127, 140, 94, 79, 220, 186, 210,
  53. 117, 5, 148, 11, 185, 206],
  54. 'cpupool': 0, 'blocked': 1}]
  55. def setUp(self):
  56. super(TC_20_QubesHost, self).setUp()
  57. self.app = TestApp()
  58. self.app.vmm = mock.Mock()
  59. self.qubes_host = qubes.app.QubesHost(self.app)
  60. def test_000_get_vm_stats_single(self):
  61. self.app.vmm.configure_mock(**{
  62. 'xc.domain_getinfo.return_value': self.sample_xc_domain_getinfo
  63. })
  64. info_time, info = self.qubes_host.get_vm_stats()
  65. self.assertEqual(self.app.vmm.mock_calls, [
  66. ('xc.domain_getinfo', (0, 1024), {}),
  67. ])
  68. self.assertIsNotNone(info_time)
  69. expected_info = {
  70. 0: {
  71. 'cpu_time': 243951379111104//8,
  72. 'cpu_usage': 0,
  73. 'memory_kb': 3733212,
  74. },
  75. 1: {
  76. 'cpu_time': 2849496569205,
  77. 'cpu_usage': 0,
  78. 'memory_kb': 303916,
  79. },
  80. 11: {
  81. 'cpu_time': 249658663079978//8,
  82. 'cpu_usage': 0,
  83. 'memory_kb': 3782668,
  84. },
  85. }
  86. self.assertEqual(info, expected_info)
  87. def test_001_get_vm_stats_twice(self):
  88. self.app.vmm.configure_mock(**{
  89. 'xc.domain_getinfo.return_value': self.sample_xc_domain_getinfo
  90. })
  91. prev_time, prev_info = self.qubes_host.get_vm_stats()
  92. prev_time -= 1
  93. prev_info[0]['cpu_time'] -= 10**8
  94. prev_info[1]['cpu_time'] -= 10**9
  95. prev_info[11]['cpu_time'] -= 125 * 10**6
  96. info_time, info = self.qubes_host.get_vm_stats(prev_time, prev_info)
  97. self.assertIsNotNone(info_time)
  98. expected_info = {
  99. 0: {
  100. 'cpu_time': 243951379111104//8,
  101. 'cpu_usage': 9,
  102. 'memory_kb': 3733212,
  103. },
  104. 1: {
  105. 'cpu_time': 2849496569205,
  106. 'cpu_usage': 99,
  107. 'memory_kb': 303916,
  108. },
  109. 11: {
  110. 'cpu_time': 249658663079978//8,
  111. 'cpu_usage': 12,
  112. 'memory_kb': 3782668,
  113. },
  114. }
  115. self.assertEqual(info, expected_info)
  116. self.assertEqual(self.app.vmm.mock_calls, [
  117. ('xc.domain_getinfo', (0, 1024), {}),
  118. ('xc.domain_getinfo', (0, 1024), {}),
  119. ])
  120. def test_002_get_vm_stats_one_vm(self):
  121. self.app.vmm.configure_mock(**{
  122. 'xc.domain_getinfo.return_value': [self.sample_xc_domain_getinfo[1]]
  123. })
  124. vm = mock.Mock
  125. vm.xid = 1
  126. vm.name = 'somevm'
  127. info_time, info = self.qubes_host.get_vm_stats(only_vm=vm)
  128. self.assertIsNotNone(info_time)
  129. self.assertEqual(self.app.vmm.mock_calls, [
  130. ('xc.domain_getinfo', (1, 1), {}),
  131. ])
  132. class TC_30_VMCollection(qubes.tests.QubesTestCase):
  133. def setUp(self):
  134. super().setUp()
  135. self.app = TestApp()
  136. self.vms = qubes.app.VMCollection(self.app)
  137. self.testvm1 = qubes.tests.init.TestVM(
  138. None, None, qid=1, name='testvm1')
  139. self.testvm2 = qubes.tests.init.TestVM(
  140. None, None, qid=2, name='testvm2')
  141. self.addCleanup(self.cleanup_vmcollection)
  142. def cleanup_vmcollection(self):
  143. self.testvm1.close()
  144. self.testvm2.close()
  145. self.vms.close()
  146. del self.testvm1
  147. del self.testvm2
  148. del self.vms
  149. del self.app
  150. def test_000_contains(self):
  151. self.vms._dict = {1: self.testvm1}
  152. self.assertIn(1, self.vms)
  153. self.assertIn('testvm1', self.vms)
  154. self.assertIn(self.testvm1, self.vms)
  155. self.assertNotIn(2, self.vms)
  156. self.assertNotIn('testvm2', self.vms)
  157. self.assertNotIn(self.testvm2, self.vms)
  158. def test_001_getitem(self):
  159. self.vms._dict = {1: self.testvm1}
  160. self.assertIs(self.vms[1], self.testvm1)
  161. self.assertIs(self.vms['testvm1'], self.testvm1)
  162. self.assertIs(self.vms[self.testvm1], self.testvm1)
  163. def test_002_add(self):
  164. self.vms.add(self.testvm1)
  165. self.assertIn(1, self.vms)
  166. self.assertEventFired(self.app, 'domain-add',
  167. kwargs={'vm': self.testvm1})
  168. with self.assertRaises(TypeError):
  169. self.vms.add(object())
  170. testvm_qid_collision = qubes.tests.init.TestVM(
  171. None, None, name='testvm2', qid=1)
  172. testvm_name_collision = qubes.tests.init.TestVM(
  173. None, None, name='testvm1', qid=2)
  174. with self.assertRaises(ValueError):
  175. self.vms.add(testvm_qid_collision)
  176. with self.assertRaises(ValueError):
  177. self.vms.add(testvm_name_collision)
  178. def test_003_qids(self):
  179. self.vms.add(self.testvm1)
  180. self.vms.add(self.testvm2)
  181. self.assertCountEqual(self.vms.qids(), [1, 2])
  182. self.assertCountEqual(self.vms.keys(), [1, 2])
  183. def test_004_names(self):
  184. self.vms.add(self.testvm1)
  185. self.vms.add(self.testvm2)
  186. self.assertCountEqual(self.vms.names(), ['testvm1', 'testvm2'])
  187. def test_005_vms(self):
  188. self.vms.add(self.testvm1)
  189. self.vms.add(self.testvm2)
  190. self.assertCountEqual(self.vms.vms(), [self.testvm1, self.testvm2])
  191. self.assertCountEqual(self.vms.values(), [self.testvm1, self.testvm2])
  192. def test_006_items(self):
  193. self.vms.add(self.testvm1)
  194. self.vms.add(self.testvm2)
  195. self.assertCountEqual(self.vms.items(),
  196. [(1, self.testvm1), (2, self.testvm2)])
  197. def test_007_len(self):
  198. self.vms.add(self.testvm1)
  199. self.vms.add(self.testvm2)
  200. self.assertEqual(len(self.vms), 2)
  201. def test_008_delitem(self):
  202. self.vms.add(self.testvm1)
  203. self.vms.add(self.testvm2)
  204. del self.vms['testvm2']
  205. self.assertCountEqual(self.vms.vms(), [self.testvm1])
  206. self.assertEventFired(self.app, 'domain-delete',
  207. kwargs={'vm': self.testvm2})
  208. def test_100_get_new_unused_qid(self):
  209. self.vms.add(self.testvm1)
  210. self.vms.add(self.testvm2)
  211. self.vms.get_new_unused_qid()
  212. # def test_200_get_vms_based_on(self):
  213. # pass
  214. # def test_201_get_vms_connected_to(self):
  215. # pass
  216. class TC_89_QubesEmpty(qubes.tests.QubesTestCase):
  217. def tearDown(self):
  218. try:
  219. os.unlink('/tmp/qubestest.xml')
  220. except:
  221. pass
  222. try:
  223. self.app.close()
  224. del self.app
  225. except AttributeError:
  226. pass
  227. super().tearDown()
  228. @qubes.tests.skipUnlessDom0
  229. def test_000_init_empty(self):
  230. # pylint: disable=no-self-use,unused-variable,bare-except
  231. try:
  232. os.unlink('/tmp/qubestest.xml')
  233. except FileNotFoundError:
  234. pass
  235. qubes.Qubes.create_empty_store('/tmp/qubestest.xml').close()
  236. def test_100_property_migrate_default_fw_netvm(self):
  237. xml_template = '''<?xml version="1.0" encoding="utf-8" ?>
  238. <qubes version="3.0">
  239. <properties>
  240. <property name="default_netvm">{default_netvm}</property>
  241. <property name="default_fw_netvm">{default_fw_netvm}</property>
  242. </properties>
  243. <labels>
  244. <label id="label-1" color="#cc0000">red</label>
  245. </labels>
  246. <pools>
  247. <pool driver="file" dir_path="/tmp/qubes-test" name="default"/>
  248. </pools>
  249. <domains>
  250. <domain class="StandaloneVM" id="domain-1">
  251. <properties>
  252. <property name="qid">1</property>
  253. <property name="name">sys-net</property>
  254. <property name="provides_network">True</property>
  255. <property name="label" ref="label-1" />
  256. <property name="netvm"></property>
  257. <property name="uuid">2fcfc1f4-b2fe-4361-931a-c5294b35edfa</property>
  258. </properties>
  259. <features/>
  260. <devices class="pci"/>
  261. </domain>
  262. <domain class="StandaloneVM" id="domain-2">
  263. <properties>
  264. <property name="qid">2</property>
  265. <property name="name">sys-firewall</property>
  266. <property name="provides_network">True</property>
  267. <property name="label" ref="label-1" />
  268. <property name="uuid">9a6d9689-25f7-48c9-a15f-8205d6c5b7c6</property>
  269. </properties>
  270. </domain>
  271. <domain class="StandaloneVM" id="domain-3">
  272. <properties>
  273. <property name="qid">3</property>
  274. <property name="name">appvm</property>
  275. <property name="label" ref="label-1" />
  276. <property name="uuid">1d6aab41-3262-400a-b3d3-21aae8fdbec8</property>
  277. </properties>
  278. </domain>
  279. </domains>
  280. </qubes>
  281. '''
  282. with self.subTest('default_setup'):
  283. with open('/tmp/qubestest.xml', 'w') as xml_file:
  284. xml_file.write(xml_template.format(
  285. default_netvm='sys-firewall',
  286. default_fw_netvm='sys-net'))
  287. self.app = qubes.Qubes('/tmp/qubestest.xml', offline_mode=True)
  288. self.assertEqual(
  289. self.app.domains['sys-net'].netvm, None)
  290. self.assertEqual(
  291. self.app.domains['sys-firewall'].netvm, self.app.domains['sys-net'])
  292. # property is no longer "default"
  293. self.assertFalse(
  294. self.app.domains['sys-firewall'].property_is_default('netvm'))
  295. # verify that appvm.netvm is unaffected
  296. self.assertTrue(
  297. self.app.domains['appvm'].property_is_default('netvm'))
  298. self.assertEqual(
  299. self.app.domains['appvm'].netvm,
  300. self.app.domains['sys-firewall'])
  301. with self.assertRaises(AttributeError):
  302. self.app.default_fw_netvm
  303. self.app.close()
  304. del self.app
  305. with self.subTest('same'):
  306. with open('/tmp/qubestest.xml', 'w') as xml_file:
  307. xml_file.write(xml_template.format(
  308. default_netvm='sys-net',
  309. default_fw_netvm='sys-net'))
  310. self.app = qubes.Qubes('/tmp/qubestest.xml', offline_mode=True)
  311. self.assertEqual(
  312. self.app.domains['sys-net'].netvm, None)
  313. self.assertEqual(
  314. self.app.domains['sys-firewall'].netvm,
  315. self.app.domains['sys-net'])
  316. self.assertTrue(
  317. self.app.domains['sys-firewall'].property_is_default('netvm'))
  318. # verify that appvm.netvm is unaffected
  319. self.assertTrue(
  320. self.app.domains['appvm'].property_is_default('netvm'))
  321. self.assertEqual(
  322. self.app.domains['appvm'].netvm,
  323. self.app.domains['sys-net'])
  324. with self.assertRaises(AttributeError):
  325. self.app.default_fw_netvm
  326. with self.subTest('loop'):
  327. with open('/tmp/qubestest.xml', 'w') as xml_file:
  328. xml_file.write(xml_template.format(
  329. default_netvm='sys-firewall',
  330. default_fw_netvm='sys-firewall'))
  331. self.app = qubes.Qubes('/tmp/qubestest.xml', offline_mode=True)
  332. self.assertEqual(
  333. self.app.domains['sys-net'].netvm, None)
  334. # this was netvm loop, better set to none, to not crash qubesd
  335. self.assertEqual(
  336. self.app.domains['sys-firewall'].netvm, None)
  337. self.assertFalse(
  338. self.app.domains['sys-firewall'].property_is_default('netvm'))
  339. # verify that appvm.netvm is unaffected
  340. self.assertTrue(
  341. self.app.domains['appvm'].property_is_default('netvm'))
  342. self.assertEqual(
  343. self.app.domains['appvm'].netvm,
  344. self.app.domains['sys-firewall'])
  345. with self.assertRaises(AttributeError):
  346. self.app.default_fw_netvm
  347. class TC_90_Qubes(qubes.tests.QubesTestCase):
  348. def tearDown(self):
  349. try:
  350. os.unlink('/tmp/qubestest.xml')
  351. except:
  352. pass
  353. super().tearDown()
  354. def setUp(self):
  355. super(TC_90_Qubes, self).setUp()
  356. self.app = qubes.Qubes('/tmp/qubestest.xml', load=False,
  357. offline_mode=True)
  358. self.addCleanup(self.cleanup_qubes)
  359. self.app.load_initial_values()
  360. self.template = self.app.add_new_vm('TemplateVM', name='test-template',
  361. label='green')
  362. def cleanup_qubes(self):
  363. self.app.close()
  364. del self.app
  365. try:
  366. del self.template
  367. except AttributeError:
  368. pass
  369. def test_100_clockvm(self):
  370. appvm = self.app.add_new_vm('AppVM', name='test-vm', template=self.template,
  371. label='red')
  372. self.assertIsNone(self.app.clockvm)
  373. self.assertNotIn('service.clocksync', appvm.features)
  374. self.assertNotIn('service.clocksync', self.template.features)
  375. self.app.clockvm = appvm
  376. self.assertIn('service.clocksync', appvm.features)
  377. self.assertTrue(appvm.features['service.clocksync'])
  378. self.app.clockvm = self.template
  379. self.assertNotIn('service.clocksync', appvm.features)
  380. self.assertIn('service.clocksync', self.template.features)
  381. self.assertTrue(self.template.features['service.clocksync'])
  382. def test_110_netvm_loop(self):
  383. '''Netvm loop through default_netvm'''
  384. netvm = self.app.add_new_vm('AppVM', name='test-net',
  385. template=self.template, label='red')
  386. try:
  387. self.app.default_netvm = None
  388. netvm.netvm = qubes.property.DEFAULT
  389. with self.assertRaises(ValueError):
  390. self.app.default_netvm = netvm
  391. finally:
  392. del netvm
  393. def test_111_netvm_loop(self):
  394. '''Netvm loop through default_netvm'''
  395. netvm = self.app.add_new_vm('AppVM', name='test-net',
  396. template=self.template, label='red')
  397. try:
  398. netvm.netvm = None
  399. self.app.default_netvm = netvm
  400. with self.assertRaises(ValueError):
  401. netvm.netvm = qubes.property.DEFAULT
  402. finally:
  403. del netvm
  404. def test_200_remove_template(self):
  405. appvm = self.app.add_new_vm('AppVM', name='test-vm',
  406. template=self.template,
  407. label='red')
  408. with mock.patch.object(self.app, 'vmm'):
  409. with self.assertRaises(qubes.exc.QubesException):
  410. del self.app.domains[self.template]
  411. def test_201_remove_netvm(self):
  412. netvm = self.app.add_new_vm('AppVM', name='test-netvm',
  413. template=self.template, provides_network=True,
  414. label='red')
  415. appvm = self.app.add_new_vm('AppVM', name='test-vm',
  416. template=self.template,
  417. label='red')
  418. appvm.netvm = netvm
  419. with mock.patch.object(self.app, 'vmm'):
  420. with self.assertRaises(qubes.exc.QubesVMInUseError):
  421. del self.app.domains[netvm]
  422. def test_202_remove_default_netvm(self):
  423. netvm = self.app.add_new_vm('AppVM', name='test-netvm',
  424. template=self.template, provides_network=True,
  425. label='red')
  426. netvm.netvm = None
  427. self.app.default_netvm = netvm
  428. with mock.patch.object(self.app, 'vmm'):
  429. with self.assertRaises(qubes.exc.QubesVMInUseError):
  430. del self.app.domains[netvm]
  431. def test_203_remove_default_dispvm(self):
  432. appvm = self.app.add_new_vm('AppVM', name='test-appvm',
  433. template=self.template,
  434. label='red')
  435. self.app.default_dispvm = appvm
  436. with mock.patch.object(self.app, 'vmm'):
  437. with self.assertRaises(qubes.exc.QubesVMInUseError):
  438. del self.app.domains[appvm]
  439. def test_204_remove_appvm_dispvm(self):
  440. dispvm = self.app.add_new_vm('AppVM', name='test-appvm',
  441. template=self.template,
  442. label='red')
  443. appvm = self.app.add_new_vm('AppVM', name='test-appvm2',
  444. template=self.template, default_dispvm=dispvm,
  445. label='red')
  446. with mock.patch.object(self.app, 'vmm'):
  447. with self.assertRaises(qubes.exc.QubesVMInUseError):
  448. del self.app.domains[dispvm]
  449. def test_205_remove_appvm_dispvm(self):
  450. appvm = self.app.add_new_vm('AppVM', name='test-appvm',
  451. template=self.template, template_for_dispvms=True,
  452. label='red')
  453. dispvm = self.app.add_new_vm('DispVM', name='test-dispvm',
  454. template=appvm,
  455. label='red')
  456. with mock.patch.object(self.app, 'vmm'):
  457. with self.assertRaises(qubes.exc.QubesVMInUseError):
  458. del self.app.domains[appvm]
  459. @qubes.tests.skipUnlessGit
  460. def test_900_example_xml_in_doc(self):
  461. self.assertXMLIsValid(
  462. lxml.etree.parse(open(
  463. os.path.join(qubes.tests.in_git, 'doc/example.xml'), 'rb')),
  464. 'qubes.rng')