storage_lvm.py 49 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182
  1. #
  2. # The Qubes OS Project, http://www.qubes-os.org
  3. #
  4. # Copyright (C) 2016 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 lvm storage driver. By default tests are going to use the
  20. 'qubes_dom0/pool00'. An alternative LVM thin pool may be provided via
  21. :envvar:`DEFAULT_LVM_POOL` shell variable.
  22. Any pool variables prefixed with 'LVM_' or 'lvm_' represent a LVM
  23. 'volume_group/thin_pool' combination. Pool variables without a prefix
  24. represent a :py:class:`qubes.storage.lvm.ThinPool`.
  25. '''
  26. import os
  27. import subprocess
  28. import tempfile
  29. import unittest
  30. import unittest.mock
  31. import asyncio
  32. import qubes.tests
  33. import qubes.tests.storage
  34. import qubes.storage
  35. from qubes.storage.lvm import ThinPool, ThinVolume, qubes_lvm
  36. if 'DEFAULT_LVM_POOL' in os.environ.keys():
  37. DEFAULT_LVM_POOL = os.environ['DEFAULT_LVM_POOL']
  38. else:
  39. DEFAULT_LVM_POOL = 'qubes_dom0/vm-pool'
  40. def lvm_pool_exists(volume_group, thin_pool):
  41. ''' Returns ``True`` if thin pool exists in the volume group. '''
  42. path = "/dev/mapper/{!s}-{!s}".format(
  43. volume_group.replace('-', '--'),
  44. thin_pool.replace('-', '--'))
  45. return os.path.exists(path)
  46. def skipUnlessLvmPoolExists(test_item): # pylint: disable=invalid-name
  47. ''' Decorator that skips LVM tests if the default pool is missing. '''
  48. volume_group, thin_pool = DEFAULT_LVM_POOL.split('/', 1)
  49. result = lvm_pool_exists(volume_group, thin_pool)
  50. msg = 'LVM thin pool {!r} does not exist'.format(DEFAULT_LVM_POOL)
  51. return unittest.skipUnless(result, msg)(test_item)
  52. POOL_CONF = {'name': 'test-lvm',
  53. 'driver': 'lvm_thin',
  54. 'volume_group': DEFAULT_LVM_POOL.split('/')[0],
  55. 'thin_pool': DEFAULT_LVM_POOL.split('/')[1]}
  56. class ThinPoolBase(qubes.tests.QubesTestCase):
  57. ''' Sanity tests for :py:class:`qubes.storage.lvm.ThinPool` '''
  58. created_pool = False
  59. def setUp(self):
  60. super(ThinPoolBase, self).setUp()
  61. volume_group, thin_pool = DEFAULT_LVM_POOL.split('/', 1)
  62. self.pool = self._find_pool(volume_group, thin_pool)
  63. if not self.pool:
  64. self.pool = self.loop.run_until_complete(
  65. self.app.add_pool(**POOL_CONF))
  66. self.created_pool = True
  67. def cleanup_test_volumes(self):
  68. p = self.loop.run_until_complete(asyncio.create_subprocess_exec(
  69. 'sudo', 'lvs', '--noheadings', '-o', 'lv_name', self.pool.volume_group,
  70. stdout=subprocess.PIPE
  71. ))
  72. volumes, _ = self.loop.run_until_complete(p.communicate())
  73. for volume in volumes.decode().splitlines():
  74. volume = volume.strip()
  75. if not volume.startswith('vm-' + qubes.tests.VMPREFIX):
  76. continue
  77. p = self.loop.run_until_complete(asyncio.create_subprocess_exec(
  78. 'sudo', 'lvremove', '-f', '/'.join([self.pool.volume_group, volume])
  79. ))
  80. self.loop.run_until_complete(p.wait())
  81. def tearDown(self):
  82. ''' Remove the default lvm pool if it was created only for this test '''
  83. self.cleanup_test_volumes()
  84. if self.created_pool:
  85. self.loop.run_until_complete(self.app.remove_pool(self.pool.name))
  86. super(ThinPoolBase, self).tearDown()
  87. def _find_pool(self, volume_group, thin_pool):
  88. ''' Returns the pool matching the specified ``volume_group`` &
  89. ``thin_pool``, or None.
  90. '''
  91. pools = [p for p in self.app.pools.values()
  92. if issubclass(p.__class__, ThinPool)]
  93. for pool in pools:
  94. if pool.volume_group == volume_group \
  95. and pool.thin_pool == thin_pool:
  96. return pool
  97. return None
  98. @skipUnlessLvmPoolExists
  99. class TC_00_ThinPool(ThinPoolBase):
  100. ''' Sanity tests for :py:class:`qubes.storage.lvm.ThinPool` '''
  101. def setUp(self):
  102. xml_path = '/tmp/qubes-test.xml'
  103. self.app = qubes.Qubes.create_empty_store(store=xml_path,
  104. clockvm=None,
  105. updatevm=None,
  106. offline_mode=True,
  107. )
  108. os.environ['QUBES_XML_PATH'] = xml_path
  109. super(TC_00_ThinPool, self).setUp()
  110. def tearDown(self):
  111. super(TC_00_ThinPool, self).tearDown()
  112. os.unlink(self.app.store)
  113. self.app.close()
  114. del self.app
  115. for attr in dir(self):
  116. if isinstance(getattr(self, attr), qubes.vm.BaseVM):
  117. delattr(self, attr)
  118. def test_000_default_thin_pool(self):
  119. ''' Check whether :py:data`DEFAULT_LVM_POOL` exists. This pool is
  120. created by default, if at installation time LVM + Thin was chosen.
  121. '''
  122. msg = 'Thin pool {!r} does not exist'.format(DEFAULT_LVM_POOL)
  123. self.assertTrue(self.pool, msg)
  124. def test_001_origin_volume(self):
  125. ''' Test origin volume creation '''
  126. config = {
  127. 'name': 'root',
  128. 'pool': self.pool.name,
  129. 'save_on_stop': True,
  130. 'rw': True,
  131. 'size': qubes.config.defaults['root_img_size'],
  132. }
  133. vm = qubes.tests.storage.TestVM(self)
  134. volume = self.app.get_pool(self.pool.name).init_volume(vm, config)
  135. self.assertIsInstance(volume, ThinVolume)
  136. self.assertEqual(volume.name, 'root')
  137. self.assertEqual(volume.pool, self.pool.name)
  138. self.assertEqual(volume.size, qubes.config.defaults['root_img_size'])
  139. self.loop.run_until_complete(volume.create())
  140. path = "/dev/%s" % volume.vid
  141. self.assertTrue(os.path.exists(path), path)
  142. self.loop.run_until_complete(volume.remove())
  143. def test_003_read_write_volume(self):
  144. ''' Test read-write volume creation '''
  145. config = {
  146. 'name': 'root',
  147. 'pool': self.pool.name,
  148. 'rw': True,
  149. 'save_on_stop': True,
  150. 'size': qubes.config.defaults['root_img_size'],
  151. }
  152. vm = qubes.tests.storage.TestVM(self)
  153. volume = self.app.get_pool(self.pool.name).init_volume(vm, config)
  154. self.assertIsInstance(volume, ThinVolume)
  155. self.assertEqual(volume.name, 'root')
  156. self.assertEqual(volume.pool, self.pool.name)
  157. self.assertEqual(volume.size, qubes.config.defaults['root_img_size'])
  158. self.loop.run_until_complete(volume.create())
  159. path = "/dev/%s" % volume.vid
  160. self.assertTrue(os.path.exists(path), path)
  161. self.loop.run_until_complete(volume.remove())
  162. def test_004_size(self):
  163. with self.assertNotRaises(NotImplementedError):
  164. size = self.pool.size
  165. environ = os.environ.copy()
  166. environ['LC_ALL'] = 'C.utf8'
  167. pool_size = subprocess.check_output(['sudo', 'lvs', '--noheadings',
  168. '-o', 'lv_size',
  169. '--units', 'b', self.pool.volume_group + '/' + self.pool.thin_pool],
  170. env=environ)
  171. self.assertEqual(size, int(pool_size.strip()[:-1]))
  172. def test_005_usage(self):
  173. with self.assertNotRaises(NotImplementedError):
  174. usage = self.pool.usage
  175. environ = os.environ.copy()
  176. environ['LC_ALL'] = 'C.utf8'
  177. pool_info = subprocess.check_output(['sudo', 'lvs', '--noheadings',
  178. '-o', 'lv_size,data_percent',
  179. '--units', 'b', self.pool.volume_group + '/' + self.pool.thin_pool],
  180. env=environ)
  181. pool_size, pool_usage = pool_info.strip().split()
  182. pool_size = int(pool_size[:-1])
  183. pool_usage = float(pool_usage)
  184. self.assertEqual(usage, int(pool_size * pool_usage / 100))
  185. def _get_size(self, path):
  186. if os.getuid() != 0:
  187. return int(
  188. subprocess.check_output(
  189. ['sudo', 'blockdev', '--getsize64', path]))
  190. fd = os.open(path, os.O_RDONLY)
  191. try:
  192. return os.lseek(fd, 0, os.SEEK_END)
  193. finally:
  194. os.close(fd)
  195. def test_006_resize(self):
  196. config = {
  197. 'name': 'root',
  198. 'pool': self.pool.name,
  199. 'rw': True,
  200. 'save_on_stop': True,
  201. 'size': 32 * 1024**2,
  202. }
  203. vm = qubes.tests.storage.TestVM(self)
  204. volume = self.app.get_pool(self.pool.name).init_volume(vm, config)
  205. self.loop.run_until_complete(volume.create())
  206. self.addCleanup(self.loop.run_until_complete, volume.remove())
  207. path = "/dev/%s" % volume.vid
  208. new_size = 64 * 1024 ** 2
  209. self.loop.run_until_complete(volume.resize(new_size))
  210. self.assertEqual(self._get_size(path), new_size)
  211. self.assertEqual(volume.size, new_size)
  212. def test_007_resize_running(self):
  213. old_size = 32 * 1024**2
  214. config = {
  215. 'name': 'root',
  216. 'pool': self.pool.name,
  217. 'rw': True,
  218. 'save_on_stop': True,
  219. 'size': old_size,
  220. }
  221. vm = qubes.tests.storage.TestVM(self)
  222. volume = self.app.get_pool(self.pool.name).init_volume(vm, config)
  223. self.loop.run_until_complete(volume.create())
  224. self.addCleanup(self.loop.run_until_complete, volume.remove())
  225. self.loop.run_until_complete(volume.start())
  226. path = "/dev/%s" % volume.vid
  227. path2 = "/dev/%s" % volume._vid_snap
  228. new_size = 64 * 1024 ** 2
  229. self.loop.run_until_complete(volume.resize(new_size))
  230. self.assertEqual(self._get_size(path), old_size)
  231. self.assertEqual(self._get_size(path2), new_size)
  232. self.assertEqual(volume.size, new_size)
  233. self.loop.run_until_complete(volume.stop())
  234. self.assertEqual(self._get_size(path), new_size)
  235. self.assertEqual(volume.size, new_size)
  236. def _get_lv_uuid(self, lv):
  237. sudo = [] if os.getuid() == 0 else ['sudo']
  238. lvs_output = subprocess.check_output(
  239. sudo + ['lvs', '--noheadings', '-o', 'lv_uuid', lv])
  240. return lvs_output.strip()
  241. def _get_lv_origin_uuid(self, lv):
  242. sudo = [] if os.getuid() == 0 else ['sudo']
  243. if qubes.storage.lvm.lvm_is_very_old:
  244. # no support for origin_uuid directly
  245. lvs_output = subprocess.check_output(
  246. sudo + ['lvs', '--noheadings', '-o', 'origin', lv])
  247. lvs_output = subprocess.check_output(
  248. sudo + ['lvs', '--noheadings', '-o', 'lv_uuid',
  249. lv.rsplit('/', 1)[0] + '/' + lvs_output.strip().decode()])
  250. else:
  251. lvs_output = subprocess.check_output(
  252. sudo + ['lvs', '--noheadings', '-o', 'origin_uuid', lv])
  253. return lvs_output.strip()
  254. def test_008_commit(self):
  255. ''' Test volume changes commit'''
  256. config = {
  257. 'name': 'root',
  258. 'pool': self.pool.name,
  259. 'save_on_stop': True,
  260. 'rw': True,
  261. 'size': qubes.config.defaults['root_img_size'],
  262. }
  263. vm = qubes.tests.storage.TestVM(self)
  264. volume = self.app.get_pool(self.pool.name).init_volume(vm, config)
  265. self.loop.run_until_complete(volume.create())
  266. path_snap = '/dev/' + volume._vid_snap
  267. self.assertFalse(os.path.exists(path_snap), path_snap)
  268. origin_uuid = self._get_lv_uuid(volume.path)
  269. self.loop.run_until_complete(volume.start())
  270. snap_uuid = self._get_lv_uuid(path_snap)
  271. self.assertNotEqual(origin_uuid, snap_uuid)
  272. path = volume.path
  273. self.assertTrue(path.startswith('/dev/' + volume.vid),
  274. '{} does not start with /dev/{}'.format(path, volume.vid))
  275. self.assertTrue(os.path.exists(path), path)
  276. self.loop.run_until_complete(volume.remove())
  277. def test_009_interrupted_commit(self):
  278. ''' Test volume changes commit'''
  279. config = {
  280. 'name': 'root',
  281. 'pool': self.pool.name,
  282. 'save_on_stop': True,
  283. 'rw': True,
  284. 'revisions_to_keep': 2,
  285. 'size': qubes.config.defaults['root_img_size'],
  286. }
  287. vm = qubes.tests.storage.TestVM(self)
  288. volume = self.app.get_pool(self.pool.name).init_volume(vm, config)
  289. # mock logging, to not interfere with time.time() mock
  290. volume.log = unittest.mock.Mock()
  291. # do not call volume.create(), do it manually to simulate
  292. # interrupted commit
  293. revisions = ['-1521065904-back', '-1521065905-back', '-snap']
  294. orig_uuids = {}
  295. for rev in revisions:
  296. cmd = ['create', self.pool._pool_id,
  297. volume.vid.split('/')[1] + rev, str(config['size'])]
  298. qubes_lvm(cmd)
  299. orig_uuids[rev] = self._get_lv_uuid(volume.vid + rev)
  300. qubes.storage.lvm.reset_cache()
  301. path_snap = '/dev/' + volume._vid_snap
  302. self.assertTrue(volume.is_dirty())
  303. self.assertEqual(volume.path,
  304. '/dev/' + volume.vid + revisions[1])
  305. expected_revisions = {
  306. revisions[0].lstrip('-'): '2018-03-14T22:18:24',
  307. revisions[1].lstrip('-'): '2018-03-14T22:18:25',
  308. }
  309. self.assertEqual(volume.revisions, expected_revisions)
  310. self.loop.run_until_complete(volume.start())
  311. self.assertEqual(volume.revisions, expected_revisions)
  312. snap_uuid = self._get_lv_uuid(path_snap)
  313. self.assertEqual(orig_uuids['-snap'], snap_uuid)
  314. self.assertTrue(volume.is_dirty())
  315. self.assertEqual(volume.path,
  316. '/dev/' + volume.vid + revisions[1])
  317. with unittest.mock.patch('time.time') as mock_time:
  318. mock_time.side_effect = [521065906]
  319. self.loop.run_until_complete(volume.stop())
  320. expected_revisions = {
  321. revisions[0].lstrip('-'): '2018-03-14T22:18:24',
  322. revisions[1].lstrip('-'): '2018-03-14T22:18:25',
  323. }
  324. self.assertFalse(volume.is_dirty())
  325. self.assertEqual(volume.revisions, expected_revisions)
  326. self.assertEqual(volume.path, '/dev/' + volume.vid)
  327. self.assertEqual(snap_uuid, self._get_lv_uuid(volume.path))
  328. self.assertFalse(os.path.exists(path_snap), path_snap)
  329. self.loop.run_until_complete(volume.remove())
  330. def test_010_migration1(self):
  331. '''Start with old revisions, then start interacting using new code'''
  332. config = {
  333. 'name': 'root',
  334. 'pool': self.pool.name,
  335. 'save_on_stop': True,
  336. 'rw': True,
  337. 'revisions_to_keep': 2,
  338. 'size': qubes.config.defaults['root_img_size'],
  339. }
  340. vm = qubes.tests.storage.TestVM(self)
  341. volume = self.app.get_pool(self.pool.name).init_volume(vm, config)
  342. # mock logging, to not interfere with time.time() mock
  343. volume.log = unittest.mock.Mock()
  344. # do not call volume.create(), do it manually to have old LV naming
  345. revisions = ['', '-1521065904-back', '-1521065905-back']
  346. orig_uuids = {}
  347. for rev in revisions:
  348. cmd = ['create', self.pool._pool_id,
  349. volume.vid.split('/')[1] + rev, str(config['size'])]
  350. qubes_lvm(cmd)
  351. orig_uuids[rev] = self._get_lv_uuid(volume.vid + rev)
  352. qubes.storage.lvm.reset_cache()
  353. path_snap = '/dev/' + volume._vid_snap
  354. self.assertFalse(os.path.exists(path_snap), path_snap)
  355. expected_revisions = {
  356. revisions[1].lstrip('-'): '2018-03-14T22:18:24',
  357. revisions[2].lstrip('-'): '2018-03-14T22:18:25',
  358. }
  359. self.assertEqual(volume.revisions, expected_revisions)
  360. self.assertEqual(volume.path, '/dev/' + volume.vid)
  361. self.loop.run_until_complete(volume.start())
  362. snap_uuid = self._get_lv_uuid(path_snap)
  363. self.assertNotEqual(orig_uuids[''], snap_uuid)
  364. snap_origin_uuid = self._get_lv_origin_uuid(path_snap)
  365. self.assertEqual(orig_uuids[''], snap_origin_uuid)
  366. path = volume.path
  367. self.assertEqual(path, '/dev/' + volume.vid)
  368. self.assertTrue(os.path.exists(path), path)
  369. with unittest.mock.patch('time.time') as mock_time:
  370. mock_time.side_effect = ('1521065906', '1521065907')
  371. self.loop.run_until_complete(volume.stop())
  372. revisions.extend(['-1521065906-back'])
  373. expected_revisions = {
  374. revisions[2].lstrip('-'): '2018-03-14T22:18:25',
  375. revisions[3].lstrip('-'): '2018-03-14T22:18:26',
  376. }
  377. self.assertEqual(volume.revisions, expected_revisions)
  378. self.assertEqual(volume.path, '/dev/' + volume.vid)
  379. path_snap = '/dev/' + volume._vid_snap
  380. self.assertFalse(os.path.exists(path_snap), path_snap)
  381. self.assertTrue(os.path.exists('/dev/' + volume.vid))
  382. self.assertEqual(self._get_lv_uuid(volume.path), snap_uuid)
  383. prev_path = '/dev/' + volume.vid + revisions[3]
  384. self.assertEqual(self._get_lv_uuid(prev_path), orig_uuids[''])
  385. self.loop.run_until_complete(volume.remove())
  386. for rev in revisions:
  387. path = '/dev/' + volume.vid + rev
  388. self.assertFalse(os.path.exists(path), path)
  389. def test_011_migration2(self):
  390. '''VM started with old code, stopped with new'''
  391. config = {
  392. 'name': 'root',
  393. 'pool': self.pool.name,
  394. 'save_on_stop': True,
  395. 'rw': True,
  396. 'revisions_to_keep': 1,
  397. 'size': qubes.config.defaults['root_img_size'],
  398. }
  399. vm = qubes.tests.storage.TestVM(self)
  400. volume = self.app.get_pool(self.pool.name).init_volume(vm, config)
  401. # mock logging, to not interfere with time.time() mock
  402. volume.log = unittest.mock.Mock()
  403. # do not call volume.create(), do it manually to have old LV naming
  404. revisions = ['', '-snap']
  405. orig_uuids = {}
  406. for rev in revisions:
  407. cmd = ['create', self.pool._pool_id,
  408. volume.vid.split('/')[1] + rev, str(config['size'])]
  409. qubes_lvm(cmd)
  410. orig_uuids[rev] = self._get_lv_uuid(volume.vid + rev)
  411. qubes.storage.lvm.reset_cache()
  412. path_snap = '/dev/' + volume._vid_snap
  413. self.assertTrue(os.path.exists(path_snap), path_snap)
  414. expected_revisions = {}
  415. self.assertEqual(volume.revisions, expected_revisions)
  416. self.assertEqual(volume.path, '/dev/' + volume.vid)
  417. self.assertTrue(volume.is_dirty())
  418. path = volume.path
  419. self.assertEqual(path, '/dev/' + volume.vid)
  420. self.assertTrue(os.path.exists(path), path)
  421. with unittest.mock.patch('time.time') as mock_time:
  422. mock_time.side_effect = ('1521065906', '1521065907')
  423. self.loop.run_until_complete(volume.stop())
  424. revisions.extend(['-1521065906-back'])
  425. expected_revisions = {
  426. revisions[2].lstrip('-'): '2018-03-14T22:18:26',
  427. }
  428. self.assertEqual(volume.revisions, expected_revisions)
  429. self.assertEqual(volume.path, '/dev/' + volume.vid)
  430. path_snap = '/dev/' + volume._vid_snap
  431. self.assertFalse(os.path.exists(path_snap), path_snap)
  432. self.assertTrue(os.path.exists('/dev/' + volume.vid))
  433. self.assertEqual(self._get_lv_uuid(volume.path), orig_uuids['-snap'])
  434. prev_path = '/dev/' + volume.vid + revisions[2]
  435. self.assertEqual(self._get_lv_uuid(prev_path), orig_uuids[''])
  436. self.loop.run_until_complete(volume.remove())
  437. for rev in revisions:
  438. path = '/dev/' + volume.vid + rev
  439. self.assertFalse(os.path.exists(path), path)
  440. def test_012_migration3(self):
  441. '''VM started with old code, started again with new, stopped with new'''
  442. config = {
  443. 'name': 'root',
  444. 'pool': self.pool.name,
  445. 'save_on_stop': True,
  446. 'rw': True,
  447. 'revisions_to_keep': 1,
  448. 'size': qubes.config.defaults['root_img_size'],
  449. }
  450. vm = qubes.tests.storage.TestVM(self)
  451. volume = self.app.get_pool(self.pool.name).init_volume(vm, config)
  452. # mock logging, to not interfere with time.time() mock
  453. volume.log = unittest.mock.Mock()
  454. # do not call volume.create(), do it manually to have old LV naming
  455. revisions = ['', '-snap']
  456. orig_uuids = {}
  457. for rev in revisions:
  458. cmd = ['create', self.pool._pool_id,
  459. volume.vid.split('/')[1] + rev, str(config['size'])]
  460. qubes_lvm(cmd)
  461. orig_uuids[rev] = self._get_lv_uuid(volume.vid + rev)
  462. qubes.storage.lvm.reset_cache()
  463. path_snap = '/dev/' + volume._vid_snap
  464. self.assertTrue(os.path.exists(path_snap), path_snap)
  465. expected_revisions = {}
  466. self.assertEqual(volume.revisions, expected_revisions)
  467. self.assertTrue(volume.path, '/dev/' + volume.vid)
  468. self.assertTrue(volume.is_dirty())
  469. self.loop.run_until_complete(volume.start())
  470. self.assertEqual(volume.revisions, expected_revisions)
  471. self.assertEqual(volume.path, '/dev/' + volume.vid)
  472. # -snap LV should be unchanged
  473. self.assertEqual(self._get_lv_uuid(volume._vid_snap),
  474. orig_uuids['-snap'])
  475. self.loop.run_until_complete(volume.remove())
  476. for rev in revisions:
  477. path = '/dev/' + volume.vid + rev
  478. self.assertFalse(os.path.exists(path), path)
  479. def test_013_migration4(self):
  480. '''revisions_to_keep=0, VM started with old code, stopped with new'''
  481. config = {
  482. 'name': 'root',
  483. 'pool': self.pool.name,
  484. 'save_on_stop': True,
  485. 'rw': True,
  486. 'revisions_to_keep': 0,
  487. 'size': qubes.config.defaults['root_img_size'],
  488. }
  489. vm = qubes.tests.storage.TestVM(self)
  490. volume = self.app.get_pool(self.pool.name).init_volume(vm, config)
  491. # mock logging, to not interfere with time.time() mock
  492. volume.log = unittest.mock.Mock()
  493. # do not call volume.create(), do it manually to have old LV naming
  494. revisions = ['', '-snap']
  495. orig_uuids = {}
  496. for rev in revisions:
  497. cmd = ['create', self.pool._pool_id,
  498. volume.vid.split('/')[1] + rev, str(config['size'])]
  499. qubes_lvm(cmd)
  500. orig_uuids[rev] = self._get_lv_uuid(volume.vid + rev)
  501. qubes.storage.lvm.reset_cache()
  502. path_snap = '/dev/' + volume._vid_snap
  503. self.assertTrue(os.path.exists(path_snap), path_snap)
  504. expected_revisions = {}
  505. self.assertEqual(volume.revisions, expected_revisions)
  506. self.assertEqual(volume.path, '/dev/' + volume.vid)
  507. self.assertTrue(volume.is_dirty())
  508. with unittest.mock.patch('time.time') as mock_time:
  509. mock_time.side_effect = ('1521065906', '1521065907')
  510. self.loop.run_until_complete(volume.stop())
  511. expected_revisions = {}
  512. self.assertEqual(volume.revisions, expected_revisions)
  513. self.assertEqual(volume.path, '/dev/' + volume.vid)
  514. self.loop.run_until_complete(volume.remove())
  515. for rev in revisions:
  516. path = '/dev/' + volume.vid + rev
  517. self.assertFalse(os.path.exists(path), path)
  518. def test_014_commit_keep_0(self):
  519. ''' Test volume changes commit, with revisions_to_keep=0'''
  520. config = {
  521. 'name': 'root',
  522. 'pool': self.pool.name,
  523. 'save_on_stop': True,
  524. 'rw': True,
  525. 'revisions_to_keep': 0,
  526. 'size': qubes.config.defaults['root_img_size'],
  527. }
  528. vm = qubes.tests.storage.TestVM(self)
  529. volume = self.app.get_pool(self.pool.name).init_volume(vm, config)
  530. # mock logging, to not interfere with time.time() mock
  531. volume.log = unittest.mock.Mock()
  532. self.loop.run_until_complete(volume.create())
  533. self.assertFalse(volume.is_dirty())
  534. path = volume.path
  535. expected_revisions = {}
  536. self.assertEqual(volume.revisions, expected_revisions)
  537. self.loop.run_until_complete(volume.start())
  538. self.assertEqual(volume.revisions, expected_revisions)
  539. path_snap = '/dev/' + volume._vid_snap
  540. snap_uuid = self._get_lv_uuid(path_snap)
  541. self.assertTrue(volume.is_dirty())
  542. self.assertEqual(volume.path, path)
  543. with unittest.mock.patch('time.time') as mock_time:
  544. mock_time.side_effect = [521065906]
  545. self.loop.run_until_complete(volume.stop())
  546. self.assertFalse(volume.is_dirty())
  547. self.assertEqual(volume.revisions, {})
  548. self.assertEqual(volume.path, '/dev/' + volume.vid)
  549. self.assertEqual(snap_uuid, self._get_lv_uuid(volume.path))
  550. self.assertFalse(os.path.exists(path_snap), path_snap)
  551. self.loop.run_until_complete(volume.remove())
  552. def test_020_revert_last(self):
  553. ''' Test volume revert'''
  554. config = {
  555. 'name': 'root',
  556. 'pool': self.pool.name,
  557. 'save_on_stop': True,
  558. 'rw': True,
  559. 'revisions_to_keep': 2,
  560. 'size': qubes.config.defaults['root_img_size'],
  561. }
  562. vm = qubes.tests.storage.TestVM(self)
  563. volume = self.app.get_pool(self.pool.name).init_volume(vm, config)
  564. # mock logging, to not interfere with time.time() mock
  565. volume.log = unittest.mock.Mock()
  566. self.loop.run_until_complete(volume.create())
  567. self.loop.run_until_complete(volume.start())
  568. with unittest.mock.patch('time.time') as mock_time:
  569. mock_time.side_effect = [521065906]
  570. self.loop.run_until_complete(volume.stop())
  571. self.loop.run_until_complete(volume.start())
  572. with unittest.mock.patch('time.time') as mock_time:
  573. mock_time.side_effect = [521065907]
  574. self.loop.run_until_complete(volume.stop())
  575. self.assertEqual(len(volume.revisions), 2)
  576. revisions = volume.revisions
  577. revision_id = max(revisions.keys())
  578. current_path = volume.path
  579. current_uuid = self._get_lv_uuid(volume.path)
  580. rev_uuid = self._get_lv_uuid(volume.vid + '-' + revision_id)
  581. self.assertFalse(volume.is_dirty())
  582. self.assertNotEqual(current_uuid, rev_uuid)
  583. self.loop.run_until_complete(volume.revert())
  584. path_snap = '/dev/' + volume._vid_snap
  585. self.assertFalse(os.path.exists(path_snap), path_snap)
  586. self.assertEqual(current_path, volume.path)
  587. new_uuid = self._get_lv_origin_uuid(volume.path)
  588. self.assertEqual(new_uuid, rev_uuid)
  589. self.assertEqual(volume.revisions, revisions)
  590. self.loop.run_until_complete(volume.remove())
  591. def test_021_revert_earlier(self):
  592. ''' Test volume revert'''
  593. config = {
  594. 'name': 'root',
  595. 'pool': self.pool.name,
  596. 'save_on_stop': True,
  597. 'rw': True,
  598. 'revisions_to_keep': 2,
  599. 'size': qubes.config.defaults['root_img_size'],
  600. }
  601. vm = qubes.tests.storage.TestVM(self)
  602. volume = self.app.get_pool(self.pool.name).init_volume(vm, config)
  603. # mock logging, to not interfere with time.time() mock
  604. volume.log = unittest.mock.Mock()
  605. self.loop.run_until_complete(volume.create())
  606. self.loop.run_until_complete(volume.start())
  607. with unittest.mock.patch('time.time') as mock_time:
  608. mock_time.side_effect = [521065906]
  609. self.loop.run_until_complete(volume.stop())
  610. self.loop.run_until_complete(volume.start())
  611. with unittest.mock.patch('time.time') as mock_time:
  612. mock_time.side_effect = [521065907]
  613. self.loop.run_until_complete(volume.stop())
  614. self.assertEqual(len(volume.revisions), 2)
  615. revisions = volume.revisions
  616. revision_id = min(revisions.keys())
  617. current_path = volume.path
  618. current_uuid = self._get_lv_uuid(volume.path)
  619. rev_uuid = self._get_lv_uuid(volume.vid + '-' + revision_id)
  620. self.assertFalse(volume.is_dirty())
  621. self.assertNotEqual(current_uuid, rev_uuid)
  622. self.loop.run_until_complete(volume.revert(revision_id))
  623. path_snap = '/dev/' + volume._vid_snap
  624. self.assertFalse(os.path.exists(path_snap), path_snap)
  625. self.assertEqual(current_path, volume.path)
  626. new_uuid = self._get_lv_origin_uuid(volume.path)
  627. self.assertEqual(new_uuid, rev_uuid)
  628. self.assertEqual(volume.revisions, revisions)
  629. self.loop.run_until_complete(volume.remove())
  630. def test_030_import_data(self):
  631. ''' Test volume import'''
  632. config = {
  633. 'name': 'root',
  634. 'pool': self.pool.name,
  635. 'save_on_stop': True,
  636. 'rw': True,
  637. 'revisions_to_keep': 2,
  638. 'size': qubes.config.defaults['root_img_size'],
  639. }
  640. vm = qubes.tests.storage.TestVM(self)
  641. volume = self.app.get_pool(self.pool.name).init_volume(vm, config)
  642. self.loop.run_until_complete(volume.create())
  643. current_uuid = self._get_lv_uuid(volume.path)
  644. self.assertFalse(volume.is_dirty())
  645. import_path = self.loop.run_until_complete(
  646. volume.import_data(volume.size))
  647. import_uuid = self._get_lv_uuid(import_path)
  648. self.assertNotEqual(current_uuid, import_uuid)
  649. # success - commit data
  650. self.loop.run_until_complete(volume.import_data_end(True))
  651. new_current_uuid = self._get_lv_uuid(volume.path)
  652. self.assertEqual(new_current_uuid, import_uuid)
  653. revisions = volume.revisions
  654. self.assertEqual(len(revisions), 1)
  655. revision = revisions.popitem()[0]
  656. self.assertEqual(current_uuid,
  657. self._get_lv_uuid(volume.vid + '-' + revision))
  658. self.assertFalse(os.path.exists(import_path), import_path)
  659. self.loop.run_until_complete(volume.remove())
  660. def test_031_import_data_fail(self):
  661. ''' Test volume import'''
  662. config = {
  663. 'name': 'root',
  664. 'pool': self.pool.name,
  665. 'save_on_stop': True,
  666. 'rw': True,
  667. 'revisions_to_keep': 2,
  668. 'size': qubes.config.defaults['root_img_size'],
  669. }
  670. vm = qubes.tests.storage.TestVM(self)
  671. volume = self.app.get_pool(self.pool.name).init_volume(vm, config)
  672. self.loop.run_until_complete(volume.create())
  673. current_uuid = self._get_lv_uuid(volume.path)
  674. self.assertFalse(volume.is_dirty())
  675. import_path = self.loop.run_until_complete(
  676. volume.import_data(volume.size))
  677. import_uuid = self._get_lv_uuid(import_path)
  678. self.assertNotEqual(current_uuid, import_uuid)
  679. # fail - discard data
  680. self.loop.run_until_complete(volume.import_data_end(False))
  681. new_current_uuid = self._get_lv_uuid(volume.path)
  682. self.assertEqual(new_current_uuid, current_uuid)
  683. revisions = volume.revisions
  684. self.assertEqual(len(revisions), 0)
  685. self.assertFalse(os.path.exists(import_path), import_path)
  686. self.loop.run_until_complete(volume.remove())
  687. def test_032_import_volume_same_pool(self):
  688. '''Import volume from the same pool'''
  689. # source volume
  690. config = {
  691. 'name': 'root',
  692. 'pool': self.pool.name,
  693. 'save_on_stop': True,
  694. 'rw': True,
  695. 'revisions_to_keep': 2,
  696. 'size': qubes.config.defaults['root_img_size'],
  697. }
  698. vm = qubes.tests.storage.TestVM(self)
  699. source_volume = self.app.get_pool(self.pool.name).init_volume(vm, config)
  700. self.loop.run_until_complete(source_volume.create())
  701. source_uuid = self._get_lv_uuid(source_volume.path)
  702. # destination volume
  703. config = {
  704. 'name': 'root2',
  705. 'pool': self.pool.name,
  706. 'save_on_stop': True,
  707. 'rw': True,
  708. 'revisions_to_keep': 2,
  709. 'size': qubes.config.defaults['root_img_size'],
  710. }
  711. volume = self.app.get_pool(self.pool.name).init_volume(vm, config)
  712. volume.log = unittest.mock.Mock()
  713. with unittest.mock.patch('time.time') as mock_time:
  714. mock_time.side_effect = [1521065905]
  715. self.loop.run_until_complete(volume.create())
  716. self.assertEqual(volume.revisions, {})
  717. uuid_before = self._get_lv_uuid(volume.path)
  718. with unittest.mock.patch('time.time') as mock_time:
  719. mock_time.side_effect = [1521065906]
  720. self.loop.run_until_complete(
  721. volume.import_volume(source_volume))
  722. uuid_after = self._get_lv_uuid(volume.path)
  723. self.assertNotEqual(uuid_after, uuid_before)
  724. # also should be different than source volume (clone, not the same LV)
  725. self.assertNotEqual(uuid_after, source_uuid)
  726. self.assertEqual(self._get_lv_origin_uuid(volume.path), source_uuid)
  727. expected_revisions = {
  728. '1521065906-back': '2018-03-14T22:18:26',
  729. }
  730. self.assertEqual(volume.revisions, expected_revisions)
  731. self.loop.run_until_complete(volume.remove())
  732. self.loop.run_until_complete(source_volume.remove())
  733. def test_033_import_volume_different_pool(self):
  734. '''Import volume from a different pool'''
  735. source_volume = unittest.mock.Mock()
  736. # destination volume
  737. config = {
  738. 'name': 'root2',
  739. 'pool': self.pool.name,
  740. 'save_on_stop': True,
  741. 'rw': True,
  742. 'revisions_to_keep': 2,
  743. 'size': qubes.config.defaults['root_img_size'],
  744. }
  745. vm = qubes.tests.storage.TestVM(self)
  746. volume = self.app.get_pool(self.pool.name).init_volume(vm, config)
  747. volume.log = unittest.mock.Mock()
  748. with unittest.mock.patch('time.time') as mock_time:
  749. mock_time.side_effect = [1521065905]
  750. self.loop.run_until_complete(volume.create())
  751. self.assertEqual(volume.revisions, {})
  752. uuid_before = self._get_lv_uuid(volume.path)
  753. with tempfile.NamedTemporaryFile() as source_volume_file:
  754. source_volume_file.write(b'test-content')
  755. source_volume_file.flush()
  756. source_volume.size = 16 * 1024 * 1024 # 16MiB
  757. source_volume.export.return_value = source_volume_file.name
  758. with unittest.mock.patch('time.time') as mock_time:
  759. mock_time.side_effect = [1521065906]
  760. self.loop.run_until_complete(
  761. volume.import_volume(source_volume))
  762. uuid_after = self._get_lv_uuid(volume.path)
  763. self.assertNotEqual(uuid_after, uuid_before)
  764. self.assertEqual(volume.size, 16 * 1024 * 1024)
  765. volume_content = subprocess.check_output(['sudo', 'cat', volume.path])
  766. self.assertEqual(volume_content.rstrip(b'\0'), b'test-content')
  767. expected_revisions = {
  768. '1521065906-back': '2018-03-14T22:18:26',
  769. }
  770. self.assertEqual(volume.revisions, expected_revisions)
  771. self.loop.run_until_complete(volume.remove())
  772. def test_034_import_data_empty(self):
  773. config = {
  774. 'name': 'root',
  775. 'pool': self.pool.name,
  776. 'save_on_stop': True,
  777. 'rw': True,
  778. 'size': 1024 * 1024,
  779. }
  780. vm = qubes.tests.storage.TestVM(self)
  781. volume = self.app.get_pool(self.pool.name).init_volume(vm, config)
  782. with unittest.mock.patch('time.time') as mock_time:
  783. mock_time.side_effect = [1521065905]
  784. self.loop.run_until_complete(volume.create())
  785. p = self.loop.run_until_complete(asyncio.create_subprocess_exec(
  786. 'sudo', 'dd', 'if=/dev/urandom', 'of=' + volume.path, 'count=1', 'bs=1M'
  787. ))
  788. self.loop.run_until_complete(p.wait())
  789. import_path = self.loop.run_until_complete(
  790. volume.import_data(volume.size))
  791. self.assertNotEqual(volume.path, import_path)
  792. p = self.loop.run_until_complete(asyncio.create_subprocess_exec(
  793. 'sudo', 'touch', import_path))
  794. self.loop.run_until_complete(p.wait())
  795. self.loop.run_until_complete(volume.import_data_end(True))
  796. self.assertFalse(os.path.exists(import_path), import_path)
  797. p = self.loop.run_until_complete(asyncio.create_subprocess_exec(
  798. 'sudo', 'cat', volume.path,
  799. stdout=subprocess.PIPE
  800. ))
  801. volume_data, _ = self.loop.run_until_complete(p.communicate())
  802. self.assertEqual(volume_data.strip(b'\0'), b'')
  803. def test_035_import_data_new_size(self):
  804. ''' Test volume import'''
  805. config = {
  806. 'name': 'root',
  807. 'pool': self.pool.name,
  808. 'save_on_stop': True,
  809. 'rw': True,
  810. 'revisions_to_keep': 2,
  811. 'size': qubes.config.defaults['root_img_size'],
  812. }
  813. new_size = 2 * qubes.config.defaults['root_img_size']
  814. vm = qubes.tests.storage.TestVM(self)
  815. volume = self.app.get_pool(self.pool.name).init_volume(vm, config)
  816. self.loop.run_until_complete(volume.create())
  817. self.loop.run_until_complete(
  818. volume.import_data(new_size))
  819. self.loop.run_until_complete(volume.import_data_end(True))
  820. self.assertEqual(volume.size, new_size)
  821. self.loop.run_until_complete(volume.remove())
  822. def test_040_volatile(self):
  823. '''Volatile volume test'''
  824. config = {
  825. 'name': 'volatile',
  826. 'pool': self.pool.name,
  827. 'rw': True,
  828. 'size': qubes.config.defaults['root_img_size'],
  829. }
  830. vm = qubes.tests.storage.TestVM(self)
  831. volume = self.app.get_pool(self.pool.name).init_volume(vm, config)
  832. # volatile volume don't need any file, verify should succeed
  833. self.assertTrue(volume.verify())
  834. self.loop.run_until_complete(volume.create())
  835. self.assertTrue(volume.verify())
  836. self.assertFalse(volume.save_on_stop)
  837. self.assertFalse(volume.snap_on_start)
  838. path = volume.path
  839. self.assertEqual(path, '/dev/' + volume.vid)
  840. self.assertFalse(os.path.exists(path))
  841. self.loop.run_until_complete(volume.start())
  842. self.assertTrue(os.path.exists(path))
  843. vol_uuid = self._get_lv_uuid(path)
  844. self.loop.run_until_complete(volume.start())
  845. self.assertTrue(os.path.exists(path))
  846. vol_uuid2 = self._get_lv_uuid(path)
  847. self.assertNotEqual(vol_uuid, vol_uuid2)
  848. self.loop.run_until_complete(volume.stop())
  849. self.assertFalse(os.path.exists(path))
  850. def test_050_snapshot_volume(self):
  851. ''' Test snapshot volume creation '''
  852. config_origin = {
  853. 'name': 'root',
  854. 'pool': self.pool.name,
  855. 'save_on_stop': True,
  856. 'rw': True,
  857. 'size': qubes.config.defaults['root_img_size'],
  858. }
  859. vm = qubes.tests.storage.TestVM(self)
  860. volume_origin = self.app.get_pool(self.pool.name).init_volume(
  861. vm, config_origin)
  862. self.loop.run_until_complete(volume_origin.create())
  863. config_snapshot = {
  864. 'name': 'root2',
  865. 'pool': self.pool.name,
  866. 'snap_on_start': True,
  867. 'source': volume_origin,
  868. 'rw': True,
  869. 'size': qubes.config.defaults['root_img_size'],
  870. }
  871. volume = self.app.get_pool(self.pool.name).init_volume(
  872. vm, config_snapshot)
  873. self.assertIsInstance(volume, ThinVolume)
  874. self.assertEqual(volume.name, 'root2')
  875. self.assertEqual(volume.pool, self.pool.name)
  876. self.assertEqual(volume.size, qubes.config.defaults['root_img_size'])
  877. # only origin volume really needs to exist, verify should succeed
  878. # even before create
  879. self.assertTrue(volume.verify())
  880. self.loop.run_until_complete(volume.create())
  881. path = volume.path
  882. self.assertEqual(path, '/dev/' + volume.vid)
  883. self.assertFalse(os.path.exists(path), path)
  884. self.loop.run_until_complete(volume.start())
  885. # snapshot volume isn't considered dirty at any time
  886. self.assertFalse(volume.is_dirty())
  887. # not outdated yet
  888. self.assertFalse(volume.is_outdated())
  889. origin_uuid = self._get_lv_uuid(volume_origin.path)
  890. snap_origin_uuid = self._get_lv_origin_uuid(volume._vid_snap)
  891. self.assertEqual(origin_uuid, snap_origin_uuid)
  892. # now make it outdated
  893. self.loop.run_until_complete(volume_origin.start())
  894. self.loop.run_until_complete(volume_origin.stop())
  895. self.assertTrue(volume.is_outdated())
  896. origin_uuid = self._get_lv_uuid(volume_origin.path)
  897. self.assertNotEqual(origin_uuid, snap_origin_uuid)
  898. self.loop.run_until_complete(volume.stop())
  899. # stopped volume is never outdated
  900. self.assertFalse(volume.is_outdated())
  901. path = volume.path
  902. self.assertFalse(os.path.exists(path), path)
  903. path = '/dev/' + volume._vid_snap
  904. self.assertFalse(os.path.exists(path), path)
  905. self.loop.run_until_complete(volume.remove())
  906. self.loop.run_until_complete(volume_origin.remove())
  907. def test_100_pool_list_volumes(self):
  908. config = {
  909. 'name': 'root',
  910. 'pool': self.pool.name,
  911. 'save_on_stop': True,
  912. 'rw': True,
  913. 'revisions_to_keep': 2,
  914. 'size': qubes.config.defaults['root_img_size'],
  915. }
  916. config2 = config.copy()
  917. vm = qubes.tests.storage.TestVM(self)
  918. volume1 = self.app.get_pool(self.pool.name).init_volume(vm, config)
  919. self.loop.run_until_complete(volume1.create())
  920. config2['name'] = 'private'
  921. volume2 = self.app.get_pool(self.pool.name).init_volume(vm, config2)
  922. self.loop.run_until_complete(volume2.create())
  923. # create some revisions
  924. self.loop.run_until_complete(volume1.start())
  925. self.loop.run_until_complete(volume1.stop())
  926. # and have one in dirty state
  927. self.loop.run_until_complete(volume2.start())
  928. self.assertIn(volume1, list(self.pool.volumes))
  929. self.assertIn(volume2, list(self.pool.volumes))
  930. self.loop.run_until_complete(volume1.remove())
  931. self.assertNotIn(volume1, list(self.pool.volumes))
  932. self.assertIn(volume2, list(self.pool.volumes))
  933. self.loop.run_until_complete(volume2.remove())
  934. self.assertNotIn(volume1, list(self.pool.volumes))
  935. self.assertNotIn(volume1, list(self.pool.volumes))
  936. def test_110_metadata_size(self):
  937. with self.assertNotRaises(NotImplementedError):
  938. usage = self.pool.usage_details
  939. metadata_size = usage['metadata_size']
  940. environ = os.environ.copy()
  941. environ['LC_ALL'] = 'C.utf8'
  942. pool_size = subprocess.check_output(['sudo', 'lvs', '--noheadings',
  943. '-o', 'lv_metadata_size',
  944. '--units', 'b',
  945. self.pool.volume_group + '/' + self.pool.thin_pool],
  946. env=environ)
  947. self.assertEqual(metadata_size, int(pool_size.strip()[:-1]))
  948. def test_111_metadata_usage(self):
  949. with self.assertNotRaises(NotImplementedError):
  950. usage = self.pool.usage_details
  951. metadata_usage = usage['metadata_usage']
  952. environ = os.environ.copy()
  953. environ['LC_ALL'] = 'C.utf8'
  954. pool_info = subprocess.check_output(['sudo', 'lvs', '--noheadings',
  955. '-o', 'lv_metadata_size,metadata_percent',
  956. '--units', 'b', self.pool.volume_group + '/' + self.pool.thin_pool],
  957. env=environ)
  958. pool_size, pool_usage = pool_info.strip().split()
  959. pool_size = int(pool_size[:-1])
  960. pool_usage = float(pool_usage)
  961. self.assertEqual(metadata_usage, int(pool_size * pool_usage / 100))
  962. @skipUnlessLvmPoolExists
  963. class TC_01_ThinPool(ThinPoolBase, qubes.tests.SystemTestCase):
  964. ''' Sanity tests for :py:class:`qubes.storage.lvm.ThinPool` '''
  965. def setUp(self):
  966. super(TC_01_ThinPool, self).setUp()
  967. self.init_default_template()
  968. def test_004_import(self):
  969. template_vm = self.app.default_template
  970. name = self.make_vm_name('import')
  971. vm = self.app.add_new_vm(qubes.vm.templatevm.TemplateVM, name=name,
  972. label='red')
  973. vm.clone_properties(template_vm)
  974. self.loop.run_until_complete(
  975. vm.clone_disk_files(template_vm, pool=self.pool.name))
  976. for v_name, volume in vm.volumes.items():
  977. if volume.save_on_stop:
  978. expected = "/dev/{!s}/vm-{!s}-{!s}".format(
  979. DEFAULT_LVM_POOL.split('/')[0], vm.name, v_name)
  980. self.assertEqual(volume.path, expected)
  981. with self.assertNotRaises(qubes.exc.QubesException):
  982. self.loop.run_until_complete(vm.start())
  983. def test_005_create_appvm(self):
  984. vm = self.app.add_new_vm(cls=qubes.vm.appvm.AppVM,
  985. name=self.make_vm_name('appvm'), label='red')
  986. self.loop.run_until_complete(vm.create_on_disk(pool=self.pool.name))
  987. for v_name, volume in vm.volumes.items():
  988. if volume.save_on_stop:
  989. expected = "/dev/{!s}/vm-{!s}-{!s}".format(
  990. DEFAULT_LVM_POOL.split('/')[0], vm.name, v_name)
  991. self.assertEqual(volume.path, expected)
  992. with self.assertNotRaises(qubes.exc.QubesException):
  993. self.loop.run_until_complete(vm.start())
  994. def test_006_name_suffix_parse(self):
  995. '''Regression test for #4680'''
  996. vm1 = self.app.add_new_vm(cls=qubes.vm.appvm.AppVM,
  997. name=self.make_vm_name('appvm'), label='red')
  998. vm2 = self.app.add_new_vm(cls=qubes.vm.appvm.AppVM,
  999. name=self.make_vm_name('appvm-root'), label='red')
  1000. self.loop.run_until_complete(asyncio.wait([
  1001. vm1.create_on_disk(pool=self.pool.name),
  1002. vm2.create_on_disk(pool=self.pool.name)]))
  1003. self.loop.run_until_complete(vm2.start())
  1004. self.loop.run_until_complete(vm2.shutdown(wait=True))
  1005. with self.assertNotRaises(ValueError):
  1006. vm1.volumes['root'].size
  1007. @skipUnlessLvmPoolExists
  1008. class TC_02_StorageHelpers(ThinPoolBase):
  1009. def setUp(self):
  1010. xml_path = '/tmp/qubes-test.xml'
  1011. self.app = qubes.Qubes.create_empty_store(store=xml_path,
  1012. clockvm=None,
  1013. updatevm=None,
  1014. offline_mode=True,
  1015. )
  1016. os.environ['QUBES_XML_PATH'] = xml_path
  1017. super(TC_02_StorageHelpers, self).setUp()
  1018. # reset cache
  1019. qubes.storage.DirectoryThinPool._thin_pool = {}
  1020. self.thin_dir = tempfile.TemporaryDirectory()
  1021. subprocess.check_call(
  1022. ['sudo', 'lvcreate', '-q', '-V', '32M',
  1023. '-T', DEFAULT_LVM_POOL, '-n',
  1024. 'test-file-pool'], stdout=subprocess.DEVNULL)
  1025. self.thin_dev = '/dev/{}/test-file-pool'.format(
  1026. DEFAULT_LVM_POOL.split('/')[0])
  1027. subprocess.check_call(['udevadm', 'settle'])
  1028. subprocess.check_call(
  1029. ['sudo', 'mkfs.ext4', '-q', self.thin_dev])
  1030. subprocess.check_call(['sudo', 'mount', self.thin_dev,
  1031. self.thin_dir.name])
  1032. subprocess.check_call(['sudo', 'chmod', '777',
  1033. self.thin_dir.name])
  1034. def tearDown(self):
  1035. subprocess.check_call(['sudo', 'umount', self.thin_dir.name])
  1036. subprocess.check_call(
  1037. ['sudo', 'lvremove', '-q', '-f', self.thin_dev],
  1038. stdout = subprocess.DEVNULL)
  1039. self.thin_dir.cleanup()
  1040. super(TC_02_StorageHelpers, self).tearDown()
  1041. os.unlink(self.app.store)
  1042. self.app.close()
  1043. del self.app
  1044. for attr in dir(self):
  1045. if isinstance(getattr(self, attr), qubes.vm.BaseVM):
  1046. delattr(self, attr)
  1047. def test_000_search_thin_pool(self):
  1048. pool = qubes.storage.search_pool_containing_dir(
  1049. self.app.pools.values(), self.thin_dir.name)
  1050. self.assertEqual(pool, self.pool)
  1051. def test_001_search_none(self):
  1052. pool = qubes.storage.search_pool_containing_dir(
  1053. self.app.pools.values(), '/tmp')
  1054. self.assertIsNone(pool)
  1055. def test_002_search_subdir(self):
  1056. subdir = os.path.join(self.thin_dir.name, 'some-dir')
  1057. os.mkdir(subdir)
  1058. pool = qubes.storage.search_pool_containing_dir(
  1059. self.app.pools.values(), subdir)
  1060. self.assertEqual(pool, self.pool)
  1061. def test_003_search_file_pool(self):
  1062. subdir = os.path.join(self.thin_dir.name, 'some-dir')
  1063. file_pool_config = {
  1064. 'name': 'test-file-pool',
  1065. 'driver': 'file',
  1066. 'dir_path': subdir
  1067. }
  1068. pool2 = self.loop.run_until_complete(
  1069. self.app.add_pool(**file_pool_config))
  1070. pool = qubes.storage.search_pool_containing_dir(
  1071. self.app.pools.values(), subdir)
  1072. self.assertEqual(pool, pool2)
  1073. pool = qubes.storage.search_pool_containing_dir(
  1074. self.app.pools.values(), self.thin_dir.name)
  1075. self.assertEqual(pool, self.pool)