backup.py 25 KB

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