storage_file.py 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444
  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 program is free software; you can redistribute it and/or modify
  7. # it under the terms of the GNU General Public License as published by
  8. # the Free Software Foundation; either version 2 of the License, or
  9. # (at your option) any later version.
  10. #
  11. # This program 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
  14. # GNU General Public License for more details.
  15. #
  16. # You should have received a copy of the GNU General Public License along
  17. # with this program; if not, write to the Free Software Foundation, Inc.,
  18. # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
  19. #
  20. ''' Tests for the file storage backend '''
  21. import os
  22. import shutil
  23. import asyncio
  24. import unittest.mock
  25. import qubes.storage
  26. import qubes.tests.storage
  27. from qubes.config import defaults
  28. # :pylint: disable=invalid-name
  29. class TestApp(qubes.Qubes):
  30. ''' A Mock App object '''
  31. def __init__(self, *args, **kwargs): # pylint: disable=unused-argument
  32. super(TestApp, self).__init__('/tmp/qubes-test.xml', load=False,
  33. offline_mode=True, **kwargs)
  34. self.load_initial_values()
  35. self.pools['linux-kernel'].dir_path = '/tmp/qubes-test-kernel'
  36. dummy_kernel = os.path.join(self.pools['linux-kernel'].dir_path,
  37. 'dummy')
  38. os.makedirs(dummy_kernel)
  39. open(os.path.join(dummy_kernel, 'vmlinuz'), 'w').close()
  40. open(os.path.join(dummy_kernel, 'modules.img'), 'w').close()
  41. open(os.path.join(dummy_kernel, 'initramfs'), 'w').close()
  42. self.default_kernel = 'dummy'
  43. def cleanup(self):
  44. ''' Remove temporary directories '''
  45. shutil.rmtree(self.pools['linux-kernel'].dir_path)
  46. if os.path.exists(self.store):
  47. os.unlink(self.store)
  48. def create_dummy_template(self):
  49. ''' Initalizes a dummy TemplateVM as the `default_template` '''
  50. template = self.add_new_vm(qubes.vm.templatevm.TemplateVM,
  51. name='test-template', label='red',
  52. memory=1024, maxmem=1024)
  53. self.default_template = template
  54. class TC_00_FilePool(qubes.tests.QubesTestCase):
  55. """ This class tests some properties of the 'default' pool.
  56. This test might become obsolete if we change the driver for the default
  57. pool to something else as 'file'.
  58. """
  59. def setUp(self):
  60. super(TC_00_FilePool, self).setUp()
  61. self.app = TestApp()
  62. def tearDown(self):
  63. self.app.cleanup()
  64. self.app.close()
  65. del self.app
  66. super(TC_00_FilePool, self).tearDown()
  67. def test000_default_pool_dir(self):
  68. """ The predefined dir for the default pool should be ``/var/lib/qubes``
  69. .. sealso::
  70. Data :data:``qubes.qubes.defaults['pool_config']``.
  71. """
  72. result = self.app.get_pool("varlibqubes").dir_path
  73. expected = '/var/lib/qubes'
  74. self.assertEqual(result, expected)
  75. def test001_default_storage_class(self):
  76. """ Check when using default pool the Storage is
  77. ``qubes.storage.Storage``. """
  78. result = self._init_app_vm().storage
  79. self.assertIsInstance(result, qubes.storage.Storage)
  80. def _init_app_vm(self):
  81. """ Return initalised, but not created, AppVm. """
  82. vmname = self.make_vm_name('appvm')
  83. self.app.create_dummy_template()
  84. return self.app.add_new_vm(qubes.vm.appvm.AppVM, name=vmname,
  85. template=self.app.default_template,
  86. label='red')
  87. class TC_01_FileVolumes(qubes.tests.QubesTestCase):
  88. ''' Test correct handling of different types of volumes '''
  89. POOL_DIR = '/tmp/test-pool'
  90. POOL_NAME = 'test-pool'
  91. POOL_CONF = {'driver': 'file', 'dir_path': POOL_DIR, 'name': POOL_NAME}
  92. def setUp(self):
  93. """ Add a test file based storage pool """
  94. super(TC_01_FileVolumes, self).setUp()
  95. self.app = TestApp()
  96. self.app.create_dummy_template()
  97. self.app.add_pool(**self.POOL_CONF)
  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. expected = vm.template.dir_path + '/root.img:' + vm.template.dir_path \
  238. + '/root-cow.img:' + vm.dir_path + '/root-cow.img'
  239. self.assertVolumePath(vm, 'root', expected, rw=False)
  240. expected = vm.dir_path + '/private.img:' + \
  241. vm.dir_path + '/private-cow.img'
  242. self.assertVolumePath(vm, 'private', expected, rw=True)
  243. expected = vm.dir_path + '/volatile.img'
  244. self.assertVolumePath(vm, 'volatile', expected, rw=True)
  245. def test_006_template_volumes(self):
  246. ''' Check if TemplateVM volumes are propertly initialized '''
  247. vmname = self.make_vm_name('appvm')
  248. vm = self.app.add_new_vm(qubes.vm.templatevm.TemplateVM, name=vmname,
  249. label='red')
  250. expected = vm.dir_path + '/root.img:' + vm.dir_path + '/root-cow.img'
  251. self.assertVolumePath(vm, 'root', expected, rw=True)
  252. expected = vm.dir_path + '/private.img:' + \
  253. vm.dir_path + '/private-cow.img'
  254. self.assertVolumePath(vm, 'private', expected, rw=True)
  255. expected = vm.dir_path + '/volatile.img'
  256. self.assertVolumePath(vm, 'volatile', expected, rw=True)
  257. def assertVolumePath(self, vm, dev_name, expected, rw=True):
  258. # :pylint: disable=invalid-name
  259. volumes = vm.volumes
  260. b_dev = volumes[dev_name].block_device()
  261. self.assertEqual(b_dev.rw, rw)
  262. self.assertEqual(b_dev.path, expected)
  263. class TC_03_FilePool(qubes.tests.QubesTestCase):
  264. """ Test the paths for the default file based pool (``FilePool``).
  265. """
  266. POOL_DIR = '/tmp/test-pool'
  267. APPVMS_DIR = '/tmp/test-pool/appvms'
  268. TEMPLATES_DIR = '/tmp/test-pool/vm-templates'
  269. SERVICE_DIR = '/tmp/test-pool/servicevms'
  270. POOL_NAME = 'test-pool'
  271. POOL_CONFIG = {'driver': 'file', 'dir_path': POOL_DIR, 'name': POOL_NAME}
  272. def setUp(self):
  273. """ Add a test file based storage pool """
  274. super(TC_03_FilePool, self).setUp()
  275. self.test_base_dir = '/tmp/qubes-test-dir'
  276. self.base_dir_patch = unittest.mock.patch.dict(qubes.config.system_path,
  277. {'qubes_base_dir': self.test_base_dir})
  278. self.base_dir_patch2 = unittest.mock.patch(
  279. 'qubes.config.qubes_base_dir', self.test_base_dir)
  280. self.base_dir_patch3 = unittest.mock.patch.dict(
  281. qubes.config.defaults['pool_configs']['varlibqubes'],
  282. {'dir_path': self.test_base_dir})
  283. self.base_dir_patch.start()
  284. self.base_dir_patch2.start()
  285. self.base_dir_patch3.start()
  286. self.app = TestApp()
  287. self.app.add_pool(**self.POOL_CONFIG)
  288. self.app.create_dummy_template()
  289. def tearDown(self):
  290. """ Remove the file based storage pool after testing """
  291. self.app.remove_pool("test-pool")
  292. self.app.cleanup()
  293. self.app.close()
  294. del self.app
  295. self.base_dir_patch3.stop()
  296. self.base_dir_patch2.stop()
  297. self.base_dir_patch.stop()
  298. super(TC_03_FilePool, self).tearDown()
  299. shutil.rmtree(self.POOL_DIR, ignore_errors=True)
  300. if os.path.exists('/tmp/qubes-test-dir'):
  301. shutil.rmtree('/tmp/qubes-test-dir')
  302. def test_001_pool_exists(self):
  303. """ Check if the storage pool was added to the storage pool config """
  304. self.assertIn('test-pool', self.app.pools.keys())
  305. def test_002_pool_dir_create(self):
  306. """ Check if the storage pool dir and subdirs were created """
  307. # The dir should not exists before
  308. pool_name = 'foo'
  309. pool_dir = '/tmp/foo'
  310. appvms_dir = '/tmp/foo/appvms'
  311. templates_dir = '/tmp/foo/vm-templates'
  312. self.assertFalse(os.path.exists(pool_dir))
  313. self.app.add_pool(name=pool_name, dir_path=pool_dir, driver='file')
  314. self.assertTrue(os.path.exists(pool_dir))
  315. self.assertTrue(os.path.exists(appvms_dir))
  316. self.assertTrue(os.path.exists(templates_dir))
  317. shutil.rmtree(pool_dir, ignore_errors=True)
  318. def test_011_appvm_file_images(self):
  319. """ Check if all the needed image files are created for an AppVm"""
  320. vmname = self.make_vm_name('appvm')
  321. vm = self.app.add_new_vm(qubes.vm.appvm.AppVM, name=vmname,
  322. template=self.app.default_template,
  323. volume_config={
  324. 'private': {
  325. 'pool': 'test-pool'
  326. },
  327. 'volatile': {
  328. 'pool': 'test-pool'
  329. }
  330. }, label='red')
  331. loop = asyncio.get_event_loop()
  332. loop.run_until_complete(vm.create_on_disk())
  333. expected_vmdir = os.path.join(self.APPVMS_DIR, vm.name)
  334. expected_private_path = os.path.join(expected_vmdir, 'private.img')
  335. self.assertEqual(vm.volumes['private'].path, expected_private_path)
  336. expected_volatile_path = os.path.join(expected_vmdir, 'volatile.img')
  337. vm.volumes['volatile'].reset()
  338. self.assertEqualAndExists(vm.volumes['volatile'].path,
  339. expected_volatile_path)
  340. def test_013_template_file_images(self):
  341. """ Check if root.img, private.img, volatile.img and root-cow.img are
  342. created propertly by the storage system
  343. """
  344. vmname = self.make_vm_name('tmvm')
  345. vm = self.app.add_new_vm(qubes.vm.templatevm.TemplateVM, name=vmname,
  346. volume_config={
  347. 'root': {
  348. 'pool': 'test-pool'
  349. },
  350. 'private': {
  351. 'pool': 'test-pool'
  352. },
  353. 'volatile': {
  354. 'pool': 'test-pool'
  355. }
  356. }, label='red')
  357. loop = asyncio.get_event_loop()
  358. loop.run_until_complete(vm.create_on_disk())
  359. expected_vmdir = os.path.join(self.TEMPLATES_DIR, vm.name)
  360. expected_root_origin_path = os.path.join(expected_vmdir, 'root.img')
  361. expected_root_cow_path = os.path.join(expected_vmdir, 'root-cow.img')
  362. expected_root_path = '%s:%s' % (expected_root_origin_path,
  363. expected_root_cow_path)
  364. self.assertEqual(vm.volumes['root'].block_device().path,
  365. expected_root_path)
  366. self.assertExist(vm.volumes['root'].path)
  367. expected_private_path = os.path.join(expected_vmdir, 'private.img')
  368. self.assertEqualAndExists(vm.volumes['private'].path,
  369. expected_private_path)
  370. expected_rootcow_path = os.path.join(expected_vmdir, 'root-cow.img')
  371. self.assertEqual(vm.volumes['root'].path_cow, expected_rootcow_path)
  372. def assertEqualAndExists(self, result_path, expected_path):
  373. """ Check if the ``result_path``, matches ``expected_path`` and exists.
  374. See also: :meth:``assertExist``
  375. """
  376. # :pylint: disable=invalid-name
  377. self.assertEqual(result_path, expected_path)
  378. self.assertExist(result_path)
  379. def assertExist(self, path):
  380. """ Assert that the given path exists. """
  381. # :pylint: disable=invalid-name
  382. self.assertTrue(
  383. os.path.exists(path), "Path {!s} does not exist".format(path))