backup.py 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658
  1. #
  2. # The Qubes OS Project, https://www.qubes-os.org/
  3. #
  4. # Copyright (C) 2014-2015
  5. # Marek Marczykowski-Górecki <marmarek@invisiblethingslab.com>
  6. # Copyright (C) 2015 Wojtek Porczyk <woju@invisiblethingslab.com>
  7. #
  8. # This library is free software; you can redistribute it and/or
  9. # modify it under the terms of the GNU Lesser General Public
  10. # License as published by the Free Software Foundation; either
  11. # version 2.1 of the License, or (at your option) any later version.
  12. #
  13. # This library is distributed in the hope that it will be useful,
  14. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  15. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  16. # Lesser General Public License for more details.
  17. #
  18. # You should have received a copy of the GNU Lesser General Public
  19. # License along with this library; if not, see <https://www.gnu.org/licenses/>.
  20. #
  21. import hashlib
  22. import logging
  23. import multiprocessing
  24. import os
  25. import shutil
  26. import sys
  27. import asyncio
  28. import qubes
  29. import qubes.backup
  30. import qubes.exc
  31. import qubes.storage.lvm
  32. import qubes.tests
  33. import qubes.tests.storage_lvm
  34. import qubes.vm
  35. import qubes.vm.appvm
  36. import qubes.vm.templatevm
  37. import qubes.vm.qubesvm
  38. try:
  39. import qubesadmin.backup.restore
  40. import qubesadmin.exc
  41. restore_available = True
  42. except ImportError:
  43. restore_available = False
  44. # noinspection PyAttributeOutsideInit
  45. class BackupTestsMixin(object):
  46. class BackupErrorHandler(logging.Handler):
  47. def __init__(self, errors_queue, level=logging.NOTSET):
  48. super(BackupTestsMixin.BackupErrorHandler, self).__init__(level)
  49. self.errors_queue = errors_queue
  50. def emit(self, record):
  51. self.errors_queue.put(record.getMessage())
  52. def setUp(self):
  53. super(BackupTestsMixin, self).setUp()
  54. try:
  55. self.init_default_template(self.template)
  56. except AttributeError:
  57. self.init_default_template()
  58. self.error_detected = multiprocessing.Queue()
  59. self.log.debug("Creating backupvm")
  60. self.backupdir = os.path.join(os.environ["HOME"], "test-backup")
  61. if os.path.exists(self.backupdir):
  62. shutil.rmtree(self.backupdir)
  63. os.mkdir(self.backupdir)
  64. self.error_handler = self.BackupErrorHandler(self.error_detected,
  65. level=logging.WARNING)
  66. backup_log = logging.getLogger('qubesadmin.backup')
  67. backup_log.addHandler(self.error_handler)
  68. def tearDown(self):
  69. shutil.rmtree(self.backupdir)
  70. backup_log = logging.getLogger('qubes.backup')
  71. backup_log.removeHandler(self.error_handler)
  72. super(BackupTestsMixin, self).tearDown()
  73. def fill_image(self, path, size=None, sparse=False):
  74. block_size = 4096
  75. self.log.debug("Filling %s" % path)
  76. f = open(path, 'wb+')
  77. if size is None:
  78. f.seek(0, 2)
  79. size = f.tell()
  80. f.seek(0)
  81. for block_num in range(int(size/block_size)):
  82. if sparse:
  83. f.seek(block_size, 1)
  84. f.write(b'a' * block_size)
  85. f.close()
  86. # NOTE: this was create_basic_vms
  87. def create_backup_vms(self, pool=None):
  88. template = self.app.default_template
  89. vms = []
  90. vmname = self.make_vm_name('test-net')
  91. self.log.debug("Creating %s" % vmname)
  92. testnet = self.app.add_new_vm(qubes.vm.appvm.AppVM,
  93. name=vmname, template=template, provides_network=True,
  94. label='red')
  95. self.loop.run_until_complete(
  96. testnet.create_on_disk(pool=pool))
  97. testnet.features['service.ntpd'] = True
  98. vms.append(testnet)
  99. self.fill_image(testnet.storage.export('private'), 20*1024*1024)
  100. vmname = self.make_vm_name('test1')
  101. self.log.debug("Creating %s" % vmname)
  102. testvm1 = self.app.add_new_vm(qubes.vm.appvm.AppVM,
  103. name=vmname, template=template, label='red')
  104. testvm1.netvm = testnet
  105. self.loop.run_until_complete(
  106. testvm1.create_on_disk(pool=pool))
  107. vms.append(testvm1)
  108. self.fill_image(testvm1.storage.export('private'), 100 * 1024 * 1024)
  109. vmname = self.make_vm_name('testhvm1')
  110. self.log.debug("Creating %s" % vmname)
  111. testvm2 = self.app.add_new_vm(qubes.vm.standalonevm.StandaloneVM,
  112. name=vmname,
  113. virt_mode='hvm',
  114. label='red')
  115. self.loop.run_until_complete(
  116. testvm2.create_on_disk(pool=pool))
  117. self.fill_image(testvm2.storage.export('root'), 1024 * 1024 * 1024, \
  118. True)
  119. vms.append(testvm2)
  120. vmname = self.make_vm_name('template')
  121. self.log.debug("Creating %s" % vmname)
  122. testvm3 = self.app.add_new_vm(qubes.vm.templatevm.TemplateVM,
  123. name=vmname, label='red')
  124. self.loop.run_until_complete(
  125. testvm3.create_on_disk(pool=pool))
  126. self.fill_image(testvm3.storage.export('root'), 100 * 1024 * 1024, True)
  127. vms.append(testvm3)
  128. vmname = self.make_vm_name('custom')
  129. self.log.debug("Creating %s" % vmname)
  130. testvm4 = self.app.add_new_vm(qubes.vm.appvm.AppVM,
  131. name=vmname, template=testvm3, label='red')
  132. self.loop.run_until_complete(
  133. testvm4.create_on_disk(pool=pool))
  134. vms.append(testvm4)
  135. self.app.save()
  136. return vms
  137. def make_backup(self, vms, target=None, expect_failure=False, **kwargs):
  138. if target is None:
  139. target = self.backupdir
  140. try:
  141. backup = qubes.backup.Backup(self.app, vms, **kwargs)
  142. except qubes.exc.QubesException as e:
  143. if not expect_failure:
  144. self.fail("QubesException during backup_prepare: %s" % str(e))
  145. else:
  146. raise
  147. if 'passphrase' not in kwargs:
  148. backup.passphrase = 'qubes'
  149. backup.target_dir = target
  150. try:
  151. self.loop.run_until_complete(backup.backup_do())
  152. except qubes.exc.QubesException as e:
  153. if not expect_failure:
  154. self.fail("QubesException during backup_do: %s" % str(e))
  155. else:
  156. raise
  157. def remove_vms(self, vms):
  158. vms = list(vms)
  159. for vm in vms:
  160. vm.netvm = None
  161. vm.default_dispvm = None
  162. super(BackupTestsMixin, self).remove_vms(vms)
  163. def restore_backup(self, source=None, appvm=None, options=None,
  164. expect_errors=None, manipulate_restore_info=None,
  165. passphrase='qubes'):
  166. if not restore_available:
  167. self.skipTest('qubesadmin module not available')
  168. if source is None:
  169. backupfile = os.path.join(self.backupdir,
  170. sorted(os.listdir(self.backupdir))[-1])
  171. else:
  172. backupfile = source
  173. client_app = qubesadmin.Qubes()
  174. if appvm:
  175. appvm = self.loop.run_until_complete(
  176. self.loop.run_in_executor(None,
  177. client_app.domains.__getitem__, appvm.name))
  178. with self.assertNotRaises(qubesadmin.exc.QubesException):
  179. restore_op = self.loop.run_until_complete(
  180. self.loop.run_in_executor(None,
  181. qubesadmin.backup.restore.BackupRestore,
  182. client_app, backupfile, appvm, passphrase))
  183. if options:
  184. for key, value in options.items():
  185. setattr(restore_op.options, key, value)
  186. restore_info = self.loop.run_until_complete(
  187. self.loop.run_in_executor(None,
  188. restore_op.get_restore_info))
  189. if callable(manipulate_restore_info):
  190. restore_info = manipulate_restore_info(restore_info)
  191. self.log.debug(restore_op.get_restore_summary(restore_info))
  192. with self.assertNotRaises(qubesadmin.exc.QubesException):
  193. self.loop.run_until_complete(
  194. self.loop.run_in_executor(None,
  195. restore_op.restore_do, restore_info))
  196. errors = []
  197. if expect_errors is None:
  198. expect_errors = []
  199. else:
  200. self.assertFalse(self.error_detected.empty(),
  201. "Restore errors expected, but none detected")
  202. while not self.error_detected.empty():
  203. current_error = self.error_detected.get()
  204. if any(map(current_error.startswith, expect_errors)):
  205. continue
  206. errors.append(current_error)
  207. self.assertTrue(len(errors) == 0,
  208. "Error(s) detected during backup_restore_do: %s" %
  209. '\n'.join(errors))
  210. if not appvm and not os.path.isdir(backupfile):
  211. os.unlink(backupfile)
  212. def create_sparse(self, path, size):
  213. f = open(path, "w")
  214. f.truncate(size)
  215. f.close()
  216. def vm_checksum(self, vms):
  217. hashes = {}
  218. for vm in vms:
  219. assert isinstance(vm, qubes.vm.qubesvm.QubesVM)
  220. hashes[vm.name] = {}
  221. for name, volume in vm.volumes.items():
  222. if not volume.rw or not volume.save_on_stop:
  223. continue
  224. vol_path = volume.export()
  225. hasher = hashlib.sha1()
  226. with open(vol_path, 'rb') as afile:
  227. for buf in iter(lambda: afile.read(4096000), b''):
  228. hasher.update(buf)
  229. hashes[vm.name][name] = hasher.hexdigest()
  230. return hashes
  231. def get_vms_info(self, vms):
  232. ''' Get VM metadata, for comparing VM later without holding actual
  233. reference to the old object.'''
  234. vms_info = {}
  235. for vm in vms:
  236. vm_info = {
  237. 'properties': {},
  238. 'default': {},
  239. 'devices': {},
  240. }
  241. for prop in ('name', 'kernel',
  242. 'memory', 'maxmem', 'kernelopts',
  243. 'services', 'vcpus', 'features'
  244. 'include_in_backups', 'default_user', 'qrexec_timeout',
  245. 'autostart', 'pci_strictreset', 'debug',
  246. 'internal', 'netvm', 'template', 'label'):
  247. if not hasattr(vm, prop):
  248. continue
  249. vm_info['properties'][prop] = str(getattr(vm, prop))
  250. vm_info['default'][prop] = vm.property_is_default(prop)
  251. for dev_class in vm.devices.keys():
  252. vm_info['devices'][dev_class] = {}
  253. for dev_ass in vm.devices[dev_class].assignments():
  254. vm_info['devices'][dev_class][str(dev_ass.device)] = \
  255. dev_ass.options
  256. vms_info[vm.name] = vm_info
  257. return vms_info
  258. def assertCorrectlyRestored(self, vms_info, orig_hashes):
  259. ''' Verify if restored VMs are identical to those before backup.
  260. :param orig_vms: collection of original QubesVM objects
  261. :param orig_hashes: result of :py:meth:`vm_checksum` on original VMs,
  262. before backup
  263. :return:
  264. '''
  265. for vm_name in vms_info:
  266. vm_info = vms_info[vm_name]
  267. self.assertIn(vm_name, self.app.domains)
  268. restored_vm = self.app.domains[vm_name]
  269. for prop in vm_info['properties']:
  270. self.assertEqual(
  271. vm_info['properties'][prop],
  272. str(getattr(restored_vm, prop)),
  273. "VM {} - property {} not properly restored".format(
  274. vm_name, prop))
  275. self.assertEqual(
  276. vm_info['default'][prop],
  277. restored_vm.property_is_default(prop),
  278. "VM {} - property {} differs in being default".format(
  279. vm_name, prop))
  280. for dev_class in vm_info['devices']:
  281. for dev in vm_info['devices'][dev_class]:
  282. found = False
  283. for restored_dev_ass in restored_vm.devices[
  284. dev_class].assignments():
  285. if str(restored_dev_ass.device) == dev:
  286. found = True
  287. self.assertEqual(vm_info['devices'][dev_class][dev],
  288. restored_dev_ass.options,
  289. 'VM {} - {} device {} options mismatch'.format(
  290. vm_name, dev_class, str(dev)))
  291. self.assertTrue(found,
  292. 'VM {} - {} device {} not restored'.format(
  293. vm_name, dev_class, dev))
  294. if orig_hashes:
  295. hashes = self.vm_checksum([restored_vm])[restored_vm.name]
  296. self.assertEqual(orig_hashes[vm_name], hashes,
  297. "VM {} - disk images are not properly restored".format(
  298. vm_name))
  299. class TC_00_Backup(BackupTestsMixin, qubes.tests.SystemTestCase):
  300. def test_000_basic_backup(self):
  301. vms = self.create_backup_vms()
  302. try:
  303. orig_hashes = self.vm_checksum(vms)
  304. vms_info = self.get_vms_info(vms)
  305. self.make_backup(vms)
  306. self.remove_vms(reversed(vms))
  307. finally:
  308. del vms
  309. self.restore_backup()
  310. self.assertCorrectlyRestored(vms_info, orig_hashes)
  311. def test_001_compressed_backup(self):
  312. vms = self.create_backup_vms()
  313. try:
  314. orig_hashes = self.vm_checksum(vms)
  315. vms_info = self.get_vms_info(vms)
  316. self.make_backup(vms, compressed=True)
  317. self.remove_vms(reversed(vms))
  318. finally:
  319. del vms
  320. self.restore_backup()
  321. self.assertCorrectlyRestored(vms_info, orig_hashes)
  322. def test_004_sparse_multipart(self):
  323. vms = []
  324. try:
  325. vmname = self.make_vm_name('testhvm2')
  326. self.log.debug("Creating %s" % vmname)
  327. self.hvmtemplate = self.app.add_new_vm(
  328. qubes.vm.templatevm.TemplateVM, name=vmname, virt_mode='hvm', label='red')
  329. self.loop.run_until_complete(self.hvmtemplate.create_on_disk())
  330. self.fill_image(
  331. os.path.join(self.hvmtemplate.dir_path, '00file'),
  332. 195 * 1024 * 1024 - 4096 * 3)
  333. self.fill_image(self.hvmtemplate.storage.export('private'),
  334. 195 * 1024 * 1024 - 4096 * 3)
  335. self.fill_image(self.hvmtemplate.storage.export('root'), 1024 * 1024 * 1024,
  336. sparse=True)
  337. vms.append(self.hvmtemplate)
  338. self.app.save()
  339. orig_hashes = self.vm_checksum(vms)
  340. vms_info = self.get_vms_info(vms)
  341. self.make_backup(vms)
  342. self.remove_vms(reversed(vms))
  343. self.restore_backup()
  344. self.assertCorrectlyRestored(vms_info, orig_hashes)
  345. # TODO check vm.backup_timestamp
  346. finally:
  347. del vms
  348. def test_005_compressed_custom(self):
  349. vms = self.create_backup_vms()
  350. try:
  351. orig_hashes = self.vm_checksum(vms)
  352. vms_info = self.get_vms_info(vms)
  353. self.make_backup(vms, compression_filter="bzip2")
  354. self.remove_vms(reversed(vms))
  355. self.restore_backup()
  356. self.assertCorrectlyRestored(vms_info, orig_hashes)
  357. finally:
  358. del vms
  359. def test_010_selective_restore(self):
  360. # create backup with internal dependencies (template, netvm etc)
  361. # try restoring only AppVMs (but not templates, netvms) - should
  362. # handle according to options set
  363. exclude = [
  364. self.make_vm_name('test-net'),
  365. self.make_vm_name('template')
  366. ]
  367. def exclude_some(restore_info):
  368. for name in exclude:
  369. restore_info.pop(name)
  370. return restore_info
  371. vms = self.create_backup_vms()
  372. try:
  373. orig_hashes = self.vm_checksum(vms)
  374. vms_info = self.get_vms_info(vms)
  375. self.make_backup(vms, compression_filter="bzip2")
  376. self.remove_vms(reversed(vms))
  377. self.restore_backup(manipulate_restore_info=exclude_some)
  378. for vm_name in vms_info:
  379. if vm_name == self.make_vm_name('test1'):
  380. # netvm was set to 'test-inst-test-net' - excluded
  381. vms_info[vm_name]['properties']['netvm'] = \
  382. str(self.app.default_netvm)
  383. vms_info[vm_name]['default']['netvm'] = True
  384. elif vm_name == self.make_vm_name('custom'):
  385. # template was set to 'test-inst-template' - excluded
  386. vms_info[vm_name]['properties']['template'] = \
  387. str(self.app.default_template)
  388. for excluded in exclude:
  389. vms_info.pop(excluded, None)
  390. self.assertCorrectlyRestored(vms_info, orig_hashes)
  391. finally:
  392. del vms
  393. def test_020_encrypted_backup_non_ascii(self):
  394. vms = self.create_backup_vms()
  395. try:
  396. orig_hashes = self.vm_checksum(vms)
  397. vms_info = self.get_vms_info(vms)
  398. self.make_backup(vms, passphrase=u'zażółć gęślą jaźń')
  399. self.remove_vms(reversed(vms))
  400. self.restore_backup(passphrase=u'zażółć gęślą jaźń')
  401. self.assertCorrectlyRestored(vms_info, orig_hashes)
  402. finally:
  403. del vms
  404. def test_100_backup_dom0_no_restore(self):
  405. # do not write it into dom0 home itself...
  406. os.mkdir('/var/tmp/test-backup')
  407. self.backupdir = '/var/tmp/test-backup'
  408. self.make_backup([self.app.domains[0]])
  409. # TODO: think of some safe way to test restore...
  410. def test_200_restore_over_existing_directory(self):
  411. """
  412. Regression test for #1386
  413. :return:
  414. """
  415. vms = self.create_backup_vms()
  416. try:
  417. orig_hashes = self.vm_checksum(vms)
  418. vms_info = self.get_vms_info(vms)
  419. self.make_backup(vms)
  420. test_dir = vms[0].dir_path
  421. self.remove_vms(reversed(vms))
  422. os.mkdir(test_dir)
  423. with open(os.path.join(test_dir, 'some-file.txt'), 'w') as f:
  424. f.write('test file\n')
  425. self.restore_backup(expect_errors=[
  426. 'Error restoring VM test-inst-test-net, skipping: Got empty '
  427. 'response from qubesd. See journalctl in dom0 for details.',
  428. 'Error setting test-inst-test1.netvm to test-inst-test-net: '
  429. '\'"No such domain: \\\'test-inst-test-net\\\'"\'',
  430. ])
  431. del vms_info['test-inst-test-net']
  432. vms_info['test-inst-test1']['properties']['netvm'] = \
  433. str(self.app.default_netvm)
  434. vms_info['test-inst-test1']['default']['netvm'] = True
  435. self.assertCorrectlyRestored(vms_info, orig_hashes)
  436. finally:
  437. del vms
  438. def test_210_auto_rename(self):
  439. """
  440. Test for #869
  441. :return:
  442. """
  443. vms = self.create_backup_vms()
  444. vms_info = self.get_vms_info(vms)
  445. try:
  446. self.make_backup(vms)
  447. self.restore_backup(options={
  448. 'rename_conflicting': True
  449. })
  450. for vm_name in vms_info:
  451. with self.assertNotRaises(
  452. (qubes.exc.QubesVMNotFoundError, KeyError)):
  453. restored_vm = self.app.domains[vm_name + '1']
  454. if vms_info[vm_name]['properties']['netvm'] and \
  455. not vms_info[vm_name]['default']['netvm']:
  456. self.assertEqual(restored_vm.netvm.name,
  457. vms_info[vm_name]['properties']['netvm'] + '1')
  458. finally:
  459. del vms
  460. def _find_pool(self, volume_group, thin_pool):
  461. ''' Returns the pool matching the specified ``volume_group`` &
  462. ``thin_pool``, or None.
  463. '''
  464. pools = [p for p in self.app.pools
  465. if issubclass(p.__class__, qubes.storage.lvm.ThinPool)]
  466. for pool in pools:
  467. if pool.volume_group == volume_group \
  468. and pool.thin_pool == thin_pool:
  469. return pool
  470. return None
  471. @qubes.tests.storage_lvm.skipUnlessLvmPoolExists
  472. def test_300_backup_lvm(self):
  473. volume_group, thin_pool = \
  474. qubes.tests.storage_lvm.DEFAULT_LVM_POOL.split('/', 1)
  475. self.pool = self._find_pool(volume_group, thin_pool)
  476. if not self.pool:
  477. self.pool = self.app.add_pool(
  478. **qubes.tests.storage_lvm.POOL_CONF)
  479. self.created_pool = True
  480. vms = self.create_backup_vms(pool=self.pool)
  481. try:
  482. orig_hashes = self.vm_checksum(vms)
  483. vms_info = self.get_vms_info(vms)
  484. self.make_backup(vms)
  485. self.remove_vms(reversed(vms))
  486. self.restore_backup()
  487. self.assertCorrectlyRestored(vms_info, orig_hashes)
  488. finally:
  489. del vms
  490. @qubes.tests.storage_lvm.skipUnlessLvmPoolExists
  491. def test_301_restore_to_lvm(self):
  492. volume_group, thin_pool = \
  493. qubes.tests.storage_lvm.DEFAULT_LVM_POOL.split('/', 1)
  494. self.pool = self._find_pool(volume_group, thin_pool)
  495. if not self.pool:
  496. self.pool = self.app.add_pool(
  497. **qubes.tests.storage_lvm.POOL_CONF)
  498. self.created_pool = True
  499. vms = self.create_backup_vms()
  500. try:
  501. orig_hashes = self.vm_checksum(vms)
  502. vms_info = self.get_vms_info(vms)
  503. self.make_backup(vms)
  504. self.remove_vms(reversed(vms))
  505. self.restore_backup(options={'override_pool': self.pool.name})
  506. self.assertCorrectlyRestored(vms_info, orig_hashes)
  507. for vm_name in vms_info:
  508. vm = self.app.domains[vm_name]
  509. for volume in vm.volumes.values():
  510. if volume.save_on_stop:
  511. self.assertEqual(volume.pool, self.pool.name)
  512. finally:
  513. del vms
  514. class TC_10_BackupVMMixin(BackupTestsMixin):
  515. def setUp(self):
  516. super(TC_10_BackupVMMixin, self).setUp()
  517. self.backupvm = self.app.add_new_vm(
  518. qubes.vm.appvm.AppVM,
  519. label='red',
  520. name=self.make_vm_name('backupvm'),
  521. template=self.template
  522. )
  523. self.loop.run_until_complete(self.backupvm.create_on_disk())
  524. def test_100_send_to_vm_file_with_spaces(self):
  525. vms = self.create_backup_vms()
  526. orig_hashes = self.vm_checksum(vms)
  527. vms_info = self.get_vms_info(vms)
  528. try:
  529. self.loop.run_until_complete(self.backupvm.start())
  530. self.loop.run_until_complete(self.backupvm.run_for_stdio(
  531. "mkdir '/var/tmp/backup directory'"))
  532. self.make_backup(vms, target_vm=self.backupvm,
  533. compressed=True,
  534. target='/var/tmp/backup directory')
  535. self.remove_vms(reversed(vms))
  536. (backup_path, _) = self.loop.run_until_complete(
  537. self.backupvm.run_for_stdio("ls /var/tmp/backup*/qubes-backup*"))
  538. backup_path = backup_path.decode().strip()
  539. self.restore_backup(source=backup_path,
  540. appvm=self.backupvm)
  541. self.assertCorrectlyRestored(vms_info, orig_hashes)
  542. finally:
  543. del vms
  544. def test_110_send_to_vm_command(self):
  545. vms = self.create_backup_vms()
  546. orig_hashes = self.vm_checksum(vms)
  547. vms_info = self.get_vms_info(vms)
  548. try:
  549. self.loop.run_until_complete(self.backupvm.start())
  550. self.make_backup(vms, target_vm=self.backupvm,
  551. compressed=True,
  552. target='dd of=/var/tmp/backup-test')
  553. self.remove_vms(reversed(vms))
  554. self.restore_backup(source='dd if=/var/tmp/backup-test',
  555. appvm=self.backupvm)
  556. self.assertCorrectlyRestored(vms_info, orig_hashes)
  557. finally:
  558. del vms
  559. def test_110_send_to_vm_no_space(self):
  560. """
  561. Check whether backup properly report failure when no enough space is
  562. available
  563. :return:
  564. """
  565. vms = self.create_backup_vms()
  566. try:
  567. self.loop.run_until_complete(self.backupvm.start())
  568. self.loop.run_until_complete(self.backupvm.run_for_stdio(
  569. # Debian 7 has too old losetup to handle loop-control device
  570. "mknod /dev/loop0 b 7 0;"
  571. "truncate -s 50M /home/user/backup.img && "
  572. "mkfs.ext4 -F /home/user/backup.img && "
  573. "mkdir /home/user/backup && "
  574. "mount /home/user/backup.img /home/user/backup -o loop &&"
  575. "chmod 777 /home/user/backup",
  576. user="root"))
  577. with self.assertRaises(qubes.exc.QubesException):
  578. self.make_backup(vms, target_vm=self.backupvm,
  579. compressed=False,
  580. target='/home/user/backup',
  581. expect_failure=True)
  582. finally:
  583. del vms
  584. def load_tests(loader, tests, pattern):
  585. for template in qubes.tests.list_templates():
  586. tests.addTests(loader.loadTestsFromTestCase(
  587. type(
  588. 'TC_10_BackupVM_' + template,
  589. (TC_10_BackupVMMixin, qubes.tests.SystemTestCase),
  590. {'template': template})))
  591. return tests