storage_file.py 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529
  1. #
  2. # The Qubes OS Project, https://www.qubes-os.org/
  3. #
  4. # Copyright (C) 2015 Bahtiar `kalkin-` Gadimov <bahtiar@gadimov.de>
  5. #
  6. # This library is free software; you can redistribute it and/or
  7. # modify it under the terms of the GNU Lesser General Public
  8. # License as published by the Free Software Foundation; either
  9. # version 2.1 of the License, or (at your option) any later version.
  10. #
  11. # This library is distributed in the hope that it will be useful,
  12. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  13. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  14. # Lesser General Public License for more details.
  15. #
  16. # You should have received a copy of the GNU Lesser General Public
  17. # License along with this library; if not, see <https://www.gnu.org/licenses/>.
  18. #
  19. ''' Tests for the file storage backend '''
  20. import os
  21. import shutil
  22. import asyncio
  23. import unittest.mock
  24. import qubes.storage
  25. import qubes.tests.storage
  26. from qubes.config import defaults
  27. # :pylint: disable=invalid-name
  28. class TestApp(qubes.Qubes):
  29. ''' A Mock App object '''
  30. def __init__(self, *args, **kwargs): # pylint: disable=unused-argument
  31. super(TestApp, self).__init__('/tmp/qubes-test.xml', load=False,
  32. offline_mode=True, **kwargs)
  33. self.load_initial_values()
  34. self.pools['linux-kernel'].dir_path = '/tmp/qubes-test-kernel'
  35. dummy_kernel = os.path.join(self.pools['linux-kernel'].dir_path,
  36. 'dummy')
  37. os.makedirs(dummy_kernel, exist_ok=True)
  38. open(os.path.join(dummy_kernel, 'vmlinuz'), 'w').close()
  39. open(os.path.join(dummy_kernel, 'modules.img'), 'w').close()
  40. open(os.path.join(dummy_kernel, 'initramfs'), 'w').close()
  41. self.default_kernel = 'dummy'
  42. def cleanup(self):
  43. ''' Remove temporary directories '''
  44. shutil.rmtree(self.pools['linux-kernel'].dir_path)
  45. if os.path.exists(self.store):
  46. os.unlink(self.store)
  47. def create_dummy_template(self):
  48. ''' Initalizes a dummy TemplateVM as the `default_template` '''
  49. template = self.add_new_vm(qubes.vm.templatevm.TemplateVM,
  50. name='test-template', label='red',
  51. memory=1024, maxmem=1024)
  52. self.default_template = template
  53. class TC_00_FilePool(qubes.tests.QubesTestCase):
  54. """ This class tests some properties of the 'default' pool.
  55. This test might become obsolete if we change the driver for the default
  56. pool to something else as 'file'.
  57. """
  58. def setUp(self):
  59. super(TC_00_FilePool, self).setUp()
  60. self.app = TestApp()
  61. def tearDown(self):
  62. self.app.cleanup()
  63. self.app.close()
  64. del self.app
  65. super(TC_00_FilePool, self).tearDown()
  66. def test000_default_pool_dir(self):
  67. """ The predefined dir for the default pool should be ``/var/lib/qubes``
  68. .. sealso::
  69. Data :data:``qubes.qubes.defaults['pool_config']``.
  70. """
  71. result = self.app.get_pool("varlibqubes").dir_path
  72. expected = '/var/lib/qubes'
  73. self.assertEqual(result, expected)
  74. def test001_default_storage_class(self):
  75. """ Check when using default pool the Storage is
  76. ``qubes.storage.Storage``. """
  77. result = self._init_app_vm().storage
  78. self.assertIsInstance(result, qubes.storage.Storage)
  79. def _init_app_vm(self):
  80. """ Return initalised, but not created, AppVm. """
  81. vmname = self.make_vm_name('appvm')
  82. self.app.create_dummy_template()
  83. return self.app.add_new_vm(qubes.vm.appvm.AppVM, name=vmname,
  84. template=self.app.default_template,
  85. label='red')
  86. class TC_01_FileVolumes(qubes.tests.QubesTestCase):
  87. ''' Test correct handling of different types of volumes '''
  88. POOL_DIR = '/tmp/test-pool'
  89. POOL_NAME = 'test-pool'
  90. POOL_CONF = {'driver': 'file', 'dir_path': POOL_DIR, 'name': POOL_NAME}
  91. def setUp(self):
  92. """ Add a test file based storage pool """
  93. super(TC_01_FileVolumes, self).setUp()
  94. self.app = TestApp()
  95. self.app.add_pool(**self.POOL_CONF)
  96. self.app.default_pool = self.app.get_pool(self.POOL_NAME)
  97. self.app.create_dummy_template()
  98. def tearDown(self):
  99. """ Remove the file based storage pool after testing """
  100. self.app.remove_pool("test-pool")
  101. self.app.cleanup()
  102. self.app.close()
  103. del self.app
  104. super(TC_01_FileVolumes, self).tearDown()
  105. shutil.rmtree(self.POOL_DIR, ignore_errors=True)
  106. def test_000_origin_volume(self):
  107. config = {
  108. 'name': 'root',
  109. 'pool': self.POOL_NAME,
  110. 'save_on_stop': True,
  111. 'rw': True,
  112. 'size': defaults['root_img_size'],
  113. }
  114. vm = qubes.tests.storage.TestVM(self)
  115. volume = self.app.get_pool(self.POOL_NAME).init_volume(vm, config)
  116. self.assertEqual(volume.name, 'root')
  117. self.assertEqual(volume.pool, self.POOL_NAME)
  118. self.assertEqual(volume.size, defaults['root_img_size'])
  119. self.assertFalse(volume.snap_on_start)
  120. self.assertTrue(volume.save_on_stop)
  121. self.assertTrue(volume.rw)
  122. block = volume.block_device()
  123. self.assertEqual(block.path,
  124. '{base}.img:{base}-cow.img'.format(
  125. base=self.POOL_DIR + '/appvms/' + vm.name + '/root'))
  126. self.assertEqual(block.script, 'block-origin')
  127. self.assertEqual(block.rw, True)
  128. self.assertEqual(block.name, 'root')
  129. self.assertEqual(block.devtype, 'disk')
  130. self.assertIsNone(block.domain)
  131. def test_001_snapshot_volume(self):
  132. template_vm = self.app.default_template
  133. vm = qubes.tests.storage.TestVM(self, template=template_vm)
  134. original_size = qubes.config.defaults['root_img_size']
  135. source_config = {
  136. 'name': 'root',
  137. 'pool': self.POOL_NAME,
  138. 'save_on_stop': True,
  139. 'rw': False,
  140. 'size': original_size,
  141. }
  142. source = self.app.get_pool(self.POOL_NAME).init_volume(template_vm,
  143. source_config)
  144. config = {
  145. 'name': 'root',
  146. 'pool': self.POOL_NAME,
  147. 'snap_on_start': True,
  148. 'rw': False,
  149. 'source': source,
  150. 'size': original_size,
  151. }
  152. volume = self.app.get_pool(self.POOL_NAME).init_volume(vm, config)
  153. self.assertEqual(volume.name, 'root')
  154. self.assertEqual(volume.pool, self.POOL_NAME)
  155. self.assertEqual(volume.size, original_size)
  156. self.assertTrue(volume.snap_on_start)
  157. self.assertTrue(volume.snap_on_start)
  158. self.assertFalse(volume.save_on_stop)
  159. self.assertFalse(volume.rw)
  160. self.assertEqual(volume.usage, 0)
  161. block = volume.block_device()
  162. assert isinstance(block, qubes.storage.BlockDevice)
  163. self.assertEqual(block.path,
  164. '{base}/{src}.img:{base}/{src}-cow.img:'
  165. '{base}/{dst}-cow.img'.format(
  166. base=self.POOL_DIR,
  167. src='vm-templates/' + template_vm.name + '/root',
  168. dst='appvms/' + vm.name + '/root',
  169. ))
  170. self.assertEqual(block.name, 'root')
  171. self.assertEqual(block.script, 'block-snapshot')
  172. self.assertEqual(block.rw, False)
  173. self.assertEqual(block.devtype, 'disk')
  174. def test_002_read_write_volume(self):
  175. config = {
  176. 'name': 'root',
  177. 'pool': self.POOL_NAME,
  178. 'rw': True,
  179. 'save_on_stop': True,
  180. 'size': defaults['root_img_size'],
  181. }
  182. vm = qubes.tests.storage.TestVM(self)
  183. volume = self.app.get_pool(self.POOL_NAME).init_volume(vm, config)
  184. self.assertEqual(volume.name, 'root')
  185. self.assertEqual(volume.pool, self.POOL_NAME)
  186. self.assertEqual(volume.size, defaults['root_img_size'])
  187. self.assertFalse(volume.snap_on_start)
  188. self.assertTrue(volume.save_on_stop)
  189. self.assertTrue(volume.rw)
  190. block = volume.block_device()
  191. self.assertEqual(block.name, 'root')
  192. self.assertEqual(block.path, '{base}.img:{base}-cow.img'.format(
  193. base=self.POOL_DIR + '/appvms/' + vm.name + '/root'))
  194. self.assertEqual(block.rw, True)
  195. self.assertEqual(block.script, 'block-origin')
  196. def test_003_read_only_volume(self):
  197. template = self.app.default_template
  198. vid = template.volumes['root'].vid
  199. config = {
  200. 'name': 'root',
  201. 'pool': self.POOL_NAME,
  202. 'rw': False,
  203. 'vid': vid,
  204. }
  205. vm = qubes.tests.storage.TestVM(self, template=template)
  206. volume = self.app.get_pool(self.POOL_NAME).init_volume(vm, config)
  207. self.assertEqual(volume.name, 'root')
  208. self.assertEqual(volume.pool, self.POOL_NAME)
  209. # original_size = qubes.config.defaults['root_img_size']
  210. # FIXME: self.assertEqual(volume.size, original_size)
  211. self.assertFalse(volume.snap_on_start)
  212. self.assertFalse(volume.save_on_stop)
  213. self.assertFalse(volume.rw)
  214. block = volume.block_device()
  215. self.assertEqual(block.rw, False)
  216. def test_004_volatile_volume(self):
  217. config = {
  218. 'name': 'root',
  219. 'pool': self.POOL_NAME,
  220. 'size': defaults['root_img_size'],
  221. 'rw': True,
  222. }
  223. vm = qubes.tests.storage.TestVM(self)
  224. volume = self.app.get_pool(self.POOL_NAME).init_volume(vm, config)
  225. self.assertEqual(volume.name, 'root')
  226. self.assertEqual(volume.pool, self.POOL_NAME)
  227. self.assertEqual(volume.size, defaults['root_img_size'])
  228. self.assertFalse(volume.snap_on_start)
  229. self.assertFalse(volume.save_on_stop)
  230. self.assertTrue(volume.rw)
  231. def test_005_appvm_volumes(self):
  232. ''' Check if AppVM volumes are propertly initialized '''
  233. vmname = self.make_vm_name('appvm')
  234. vm = self.app.add_new_vm(qubes.vm.appvm.AppVM, name=vmname,
  235. template=self.app.default_template,
  236. label='red')
  237. template_dir = os.path.join(self.POOL_DIR, 'vm-templates',
  238. vm.template.name)
  239. vm_dir = os.path.join(self.POOL_DIR, 'appvms', vmname)
  240. expected = template_dir + '/root.img:' + \
  241. template_dir + '/root-cow.img:' + \
  242. vm_dir + '/root-cow.img'
  243. self.assertVolumePath(vm, 'root', expected, rw=True)
  244. expected = vm_dir + '/private.img:' + \
  245. vm_dir + '/private-cow.img'
  246. self.assertVolumePath(vm, 'private', expected, rw=True)
  247. expected = vm_dir + '/volatile.img'
  248. self.assertVolumePath(vm, 'volatile', expected, rw=True)
  249. def test_006_template_volumes(self):
  250. ''' Check if TemplateVM volumes are propertly initialized '''
  251. vmname = self.make_vm_name('appvm')
  252. vm = self.app.add_new_vm(qubes.vm.templatevm.TemplateVM, name=vmname,
  253. label='red')
  254. vm_dir = os.path.join(self.POOL_DIR, 'vm-templates', vmname)
  255. expected = vm_dir + '/root.img:' + vm_dir + '/root-cow.img'
  256. self.assertVolumePath(vm, 'root', expected, rw=True)
  257. expected = vm_dir + '/private.img:' + \
  258. vm_dir + '/private-cow.img'
  259. self.assertVolumePath(vm, 'private', expected, rw=True)
  260. expected = vm_dir + '/volatile.img'
  261. self.assertVolumePath(vm, 'volatile', expected, rw=True)
  262. def test_010_revisions_to_keep_reject_invalid(self):
  263. ''' Check if TemplateVM volumes are propertly initialized '''
  264. config = {
  265. 'name': 'root',
  266. 'pool': self.POOL_NAME,
  267. 'save_on_stop': True,
  268. 'rw': True,
  269. 'size': defaults['root_img_size'],
  270. }
  271. vm = qubes.tests.storage.TestVM(self)
  272. volume = self.app.get_pool(self.POOL_NAME).init_volume(vm, config)
  273. self.assertEqual(volume.revisions_to_keep, 1)
  274. with self.assertRaises((NotImplementedError, ValueError)):
  275. volume.revisions_to_keep = 2
  276. self.assertEqual(volume.revisions_to_keep, 1)
  277. def test_020_import_data(self):
  278. config = {
  279. 'name': 'root',
  280. 'pool': self.POOL_NAME,
  281. 'save_on_stop': True,
  282. 'rw': True,
  283. 'size': 1024 * 1024,
  284. }
  285. vm = qubes.tests.storage.TestVM(self)
  286. volume = self.app.get_pool(self.POOL_NAME).init_volume(vm, config)
  287. volume.create()
  288. import_path = volume.import_data()
  289. self.assertNotEqual(volume.path, import_path)
  290. with open(import_path, 'w+') as import_file:
  291. import_file.write('test')
  292. volume.import_data_end(True)
  293. self.assertFalse(os.path.exists(import_path), import_path)
  294. with open(volume.path) as volume_file:
  295. volume_data = volume_file.read().strip('\0')
  296. self.assertEqual(volume_data, 'test')
  297. def test_021_import_data_fail(self):
  298. config = {
  299. 'name': 'root',
  300. 'pool': self.POOL_NAME,
  301. 'save_on_stop': True,
  302. 'rw': True,
  303. 'size': 1024 * 1024,
  304. }
  305. vm = qubes.tests.storage.TestVM(self)
  306. volume = self.app.get_pool(self.POOL_NAME).init_volume(vm, config)
  307. volume.create()
  308. import_path = volume.import_data()
  309. self.assertNotEqual(volume.path, import_path)
  310. with open(import_path, 'w+') as import_file:
  311. import_file.write('test')
  312. volume.import_data_end(False)
  313. self.assertFalse(os.path.exists(import_path), import_path)
  314. with open(volume.path) as volume_file:
  315. volume_data = volume_file.read().strip('\0')
  316. self.assertNotEqual(volume_data, 'test')
  317. def assertVolumePath(self, vm, dev_name, expected, rw=True):
  318. # :pylint: disable=invalid-name
  319. volumes = vm.volumes
  320. b_dev = volumes[dev_name].block_device()
  321. self.assertEqual(b_dev.rw, rw)
  322. self.assertEqual(b_dev.path, expected)
  323. class TC_03_FilePool(qubes.tests.QubesTestCase):
  324. """ Test the paths for the default file based pool (``FilePool``).
  325. """
  326. POOL_DIR = '/tmp/test-pool'
  327. APPVMS_DIR = '/tmp/test-pool/appvms'
  328. TEMPLATES_DIR = '/tmp/test-pool/vm-templates'
  329. SERVICE_DIR = '/tmp/test-pool/servicevms'
  330. POOL_NAME = 'test-pool'
  331. POOL_CONFIG = {'driver': 'file', 'dir_path': POOL_DIR, 'name': POOL_NAME}
  332. def setUp(self):
  333. """ Add a test file based storage pool """
  334. super(TC_03_FilePool, self).setUp()
  335. self.test_base_dir = '/tmp/qubes-test-dir'
  336. self.base_dir_patch = unittest.mock.patch.dict(qubes.config.system_path,
  337. {'qubes_base_dir': self.test_base_dir})
  338. self.base_dir_patch2 = unittest.mock.patch(
  339. 'qubes.config.qubes_base_dir', self.test_base_dir)
  340. self.base_dir_patch3 = unittest.mock.patch.dict(
  341. qubes.config.defaults['pool_configs']['varlibqubes'],
  342. {'dir_path': self.test_base_dir})
  343. self.base_dir_patch.start()
  344. self.base_dir_patch2.start()
  345. self.base_dir_patch3.start()
  346. self.app = TestApp()
  347. self.app.add_pool(**self.POOL_CONFIG)
  348. self.app.create_dummy_template()
  349. def tearDown(self):
  350. """ Remove the file based storage pool after testing """
  351. self.app.remove_pool("test-pool")
  352. self.app.cleanup()
  353. self.app.close()
  354. del self.app
  355. self.base_dir_patch3.stop()
  356. self.base_dir_patch2.stop()
  357. self.base_dir_patch.stop()
  358. super(TC_03_FilePool, self).tearDown()
  359. shutil.rmtree(self.POOL_DIR, ignore_errors=True)
  360. if os.path.exists('/tmp/qubes-test-dir'):
  361. shutil.rmtree('/tmp/qubes-test-dir')
  362. def test_001_pool_exists(self):
  363. """ Check if the storage pool was added to the storage pool config """
  364. self.assertIn('test-pool', self.app.pools.keys())
  365. def test_002_pool_dir_create(self):
  366. """ Check if the storage pool dir and subdirs were created """
  367. # The dir should not exists before
  368. pool_name = 'foo'
  369. pool_dir = '/tmp/foo'
  370. appvms_dir = '/tmp/foo/appvms'
  371. templates_dir = '/tmp/foo/vm-templates'
  372. self.assertFalse(os.path.exists(pool_dir))
  373. self.app.add_pool(name=pool_name, dir_path=pool_dir, driver='file')
  374. self.assertTrue(os.path.exists(pool_dir))
  375. self.assertTrue(os.path.exists(appvms_dir))
  376. self.assertTrue(os.path.exists(templates_dir))
  377. shutil.rmtree(pool_dir, ignore_errors=True)
  378. def test_003_size(self):
  379. pool = self.app.get_pool(self.POOL_NAME)
  380. with self.assertNotRaises(NotImplementedError):
  381. size = pool.size
  382. statvfs = os.statvfs(self.POOL_DIR)
  383. self.assertEqual(size, statvfs.f_blocks * statvfs.f_frsize)
  384. def test_004_usage(self):
  385. pool = self.app.get_pool(self.POOL_NAME)
  386. with self.assertNotRaises(NotImplementedError):
  387. usage = pool.usage
  388. statvfs = os.statvfs(self.POOL_DIR)
  389. self.assertEqual(usage,
  390. statvfs.f_frsize * (statvfs.f_blocks - statvfs.f_bfree))
  391. def test_005_revisions_to_keep(self):
  392. pool = self.app.get_pool(self.POOL_NAME)
  393. self.assertEqual(pool.revisions_to_keep, 1)
  394. with self.assertRaises((NotImplementedError, ValueError)):
  395. pool.revisions_to_keep = 2
  396. self.assertEqual(pool.revisions_to_keep, 1)
  397. def test_011_appvm_file_images(self):
  398. """ Check if all the needed image files are created for an AppVm"""
  399. vmname = self.make_vm_name('appvm')
  400. vm = self.app.add_new_vm(qubes.vm.appvm.AppVM, name=vmname,
  401. template=self.app.default_template,
  402. volume_config={
  403. 'private': {
  404. 'pool': 'test-pool'
  405. },
  406. 'volatile': {
  407. 'pool': 'test-pool'
  408. }
  409. }, label='red')
  410. loop = asyncio.get_event_loop()
  411. loop.run_until_complete(vm.create_on_disk())
  412. expected_vmdir = os.path.join(self.APPVMS_DIR, vm.name)
  413. expected_private_path = os.path.join(expected_vmdir, 'private.img')
  414. self.assertEqual(vm.volumes['private'].path, expected_private_path)
  415. expected_volatile_path = os.path.join(expected_vmdir, 'volatile.img')
  416. vm.volumes['volatile'].reset()
  417. self.assertEqualAndExists(vm.volumes['volatile'].path,
  418. expected_volatile_path)
  419. def test_013_template_file_images(self):
  420. """ Check if root.img, private.img, volatile.img and root-cow.img are
  421. created propertly by the storage system
  422. """
  423. vmname = self.make_vm_name('tmvm')
  424. vm = self.app.add_new_vm(qubes.vm.templatevm.TemplateVM, name=vmname,
  425. volume_config={
  426. 'root': {
  427. 'pool': 'test-pool'
  428. },
  429. 'private': {
  430. 'pool': 'test-pool'
  431. },
  432. 'volatile': {
  433. 'pool': 'test-pool'
  434. }
  435. }, label='red')
  436. loop = asyncio.get_event_loop()
  437. loop.run_until_complete(vm.create_on_disk())
  438. expected_vmdir = os.path.join(self.TEMPLATES_DIR, vm.name)
  439. expected_root_origin_path = os.path.join(expected_vmdir, 'root.img')
  440. expected_root_cow_path = os.path.join(expected_vmdir, 'root-cow.img')
  441. expected_root_path = '%s:%s' % (expected_root_origin_path,
  442. expected_root_cow_path)
  443. self.assertEqual(vm.volumes['root'].block_device().path,
  444. expected_root_path)
  445. self.assertExist(vm.volumes['root'].path)
  446. expected_private_path = os.path.join(expected_vmdir, 'private.img')
  447. self.assertEqualAndExists(vm.volumes['private'].path,
  448. expected_private_path)
  449. expected_rootcow_path = os.path.join(expected_vmdir, 'root-cow.img')
  450. self.assertEqual(vm.volumes['root'].path_cow, expected_rootcow_path)
  451. def assertEqualAndExists(self, result_path, expected_path):
  452. """ Check if the ``result_path``, matches ``expected_path`` and exists.
  453. See also: :meth:``assertExist``
  454. """
  455. # :pylint: disable=invalid-name
  456. self.assertEqual(result_path, expected_path)
  457. self.assertExist(result_path)
  458. def assertExist(self, path):
  459. """ Assert that the given path exists. """
  460. # :pylint: disable=invalid-name
  461. self.assertTrue(
  462. os.path.exists(path), "Path {!s} does not exist".format(path))