storage_file.py 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487
  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 assertVolumePath(self, vm, dev_name, expected, rw=True):
  278. # :pylint: disable=invalid-name
  279. volumes = vm.volumes
  280. b_dev = volumes[dev_name].block_device()
  281. self.assertEqual(b_dev.rw, rw)
  282. self.assertEqual(b_dev.path, expected)
  283. class TC_03_FilePool(qubes.tests.QubesTestCase):
  284. """ Test the paths for the default file based pool (``FilePool``).
  285. """
  286. POOL_DIR = '/tmp/test-pool'
  287. APPVMS_DIR = '/tmp/test-pool/appvms'
  288. TEMPLATES_DIR = '/tmp/test-pool/vm-templates'
  289. SERVICE_DIR = '/tmp/test-pool/servicevms'
  290. POOL_NAME = 'test-pool'
  291. POOL_CONFIG = {'driver': 'file', 'dir_path': POOL_DIR, 'name': POOL_NAME}
  292. def setUp(self):
  293. """ Add a test file based storage pool """
  294. super(TC_03_FilePool, self).setUp()
  295. self.test_base_dir = '/tmp/qubes-test-dir'
  296. self.base_dir_patch = unittest.mock.patch.dict(qubes.config.system_path,
  297. {'qubes_base_dir': self.test_base_dir})
  298. self.base_dir_patch2 = unittest.mock.patch(
  299. 'qubes.config.qubes_base_dir', self.test_base_dir)
  300. self.base_dir_patch3 = unittest.mock.patch.dict(
  301. qubes.config.defaults['pool_configs']['varlibqubes'],
  302. {'dir_path': self.test_base_dir})
  303. self.base_dir_patch.start()
  304. self.base_dir_patch2.start()
  305. self.base_dir_patch3.start()
  306. self.app = TestApp()
  307. self.app.add_pool(**self.POOL_CONFIG)
  308. self.app.create_dummy_template()
  309. def tearDown(self):
  310. """ Remove the file based storage pool after testing """
  311. self.app.remove_pool("test-pool")
  312. self.app.cleanup()
  313. self.app.close()
  314. del self.app
  315. self.base_dir_patch3.stop()
  316. self.base_dir_patch2.stop()
  317. self.base_dir_patch.stop()
  318. super(TC_03_FilePool, self).tearDown()
  319. shutil.rmtree(self.POOL_DIR, ignore_errors=True)
  320. if os.path.exists('/tmp/qubes-test-dir'):
  321. shutil.rmtree('/tmp/qubes-test-dir')
  322. def test_001_pool_exists(self):
  323. """ Check if the storage pool was added to the storage pool config """
  324. self.assertIn('test-pool', self.app.pools.keys())
  325. def test_002_pool_dir_create(self):
  326. """ Check if the storage pool dir and subdirs were created """
  327. # The dir should not exists before
  328. pool_name = 'foo'
  329. pool_dir = '/tmp/foo'
  330. appvms_dir = '/tmp/foo/appvms'
  331. templates_dir = '/tmp/foo/vm-templates'
  332. self.assertFalse(os.path.exists(pool_dir))
  333. self.app.add_pool(name=pool_name, dir_path=pool_dir, driver='file')
  334. self.assertTrue(os.path.exists(pool_dir))
  335. self.assertTrue(os.path.exists(appvms_dir))
  336. self.assertTrue(os.path.exists(templates_dir))
  337. shutil.rmtree(pool_dir, ignore_errors=True)
  338. def test_003_size(self):
  339. pool = self.app.get_pool(self.POOL_NAME)
  340. with self.assertNotRaises(NotImplementedError):
  341. size = pool.size
  342. statvfs = os.statvfs(self.POOL_DIR)
  343. self.assertEqual(size, statvfs.f_blocks * statvfs.f_frsize)
  344. def test_004_usage(self):
  345. pool = self.app.get_pool(self.POOL_NAME)
  346. with self.assertNotRaises(NotImplementedError):
  347. usage = pool.usage
  348. statvfs = os.statvfs(self.POOL_DIR)
  349. self.assertEqual(usage,
  350. statvfs.f_frsize * (statvfs.f_blocks - statvfs.f_bfree))
  351. def test_005_revisions_to_keep(self):
  352. pool = self.app.get_pool(self.POOL_NAME)
  353. self.assertEqual(pool.revisions_to_keep, 1)
  354. with self.assertRaises((NotImplementedError, ValueError)):
  355. pool.revisions_to_keep = 2
  356. self.assertEqual(pool.revisions_to_keep, 1)
  357. def test_011_appvm_file_images(self):
  358. """ Check if all the needed image files are created for an AppVm"""
  359. vmname = self.make_vm_name('appvm')
  360. vm = self.app.add_new_vm(qubes.vm.appvm.AppVM, name=vmname,
  361. template=self.app.default_template,
  362. volume_config={
  363. 'private': {
  364. 'pool': 'test-pool'
  365. },
  366. 'volatile': {
  367. 'pool': 'test-pool'
  368. }
  369. }, label='red')
  370. loop = asyncio.get_event_loop()
  371. loop.run_until_complete(vm.create_on_disk())
  372. expected_vmdir = os.path.join(self.APPVMS_DIR, vm.name)
  373. expected_private_path = os.path.join(expected_vmdir, 'private.img')
  374. self.assertEqual(vm.volumes['private'].path, expected_private_path)
  375. expected_volatile_path = os.path.join(expected_vmdir, 'volatile.img')
  376. vm.volumes['volatile'].reset()
  377. self.assertEqualAndExists(vm.volumes['volatile'].path,
  378. expected_volatile_path)
  379. def test_013_template_file_images(self):
  380. """ Check if root.img, private.img, volatile.img and root-cow.img are
  381. created propertly by the storage system
  382. """
  383. vmname = self.make_vm_name('tmvm')
  384. vm = self.app.add_new_vm(qubes.vm.templatevm.TemplateVM, name=vmname,
  385. volume_config={
  386. 'root': {
  387. 'pool': 'test-pool'
  388. },
  389. 'private': {
  390. 'pool': 'test-pool'
  391. },
  392. 'volatile': {
  393. 'pool': 'test-pool'
  394. }
  395. }, label='red')
  396. loop = asyncio.get_event_loop()
  397. loop.run_until_complete(vm.create_on_disk())
  398. expected_vmdir = os.path.join(self.TEMPLATES_DIR, vm.name)
  399. expected_root_origin_path = os.path.join(expected_vmdir, 'root.img')
  400. expected_root_cow_path = os.path.join(expected_vmdir, 'root-cow.img')
  401. expected_root_path = '%s:%s' % (expected_root_origin_path,
  402. expected_root_cow_path)
  403. self.assertEqual(vm.volumes['root'].block_device().path,
  404. expected_root_path)
  405. self.assertExist(vm.volumes['root'].path)
  406. expected_private_path = os.path.join(expected_vmdir, 'private.img')
  407. self.assertEqualAndExists(vm.volumes['private'].path,
  408. expected_private_path)
  409. expected_rootcow_path = os.path.join(expected_vmdir, 'root-cow.img')
  410. self.assertEqual(vm.volumes['root'].path_cow, expected_rootcow_path)
  411. def assertEqualAndExists(self, result_path, expected_path):
  412. """ Check if the ``result_path``, matches ``expected_path`` and exists.
  413. See also: :meth:``assertExist``
  414. """
  415. # :pylint: disable=invalid-name
  416. self.assertEqual(result_path, expected_path)
  417. self.assertExist(result_path)
  418. def assertExist(self, path):
  419. """ Assert that the given path exists. """
  420. # :pylint: disable=invalid-name
  421. self.assertTrue(
  422. os.path.exists(path), "Path {!s} does not exist".format(path))