__init__.py 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768
  1. #!/usr/bin/python2 -O
  2. # vim: fileencoding=utf-8
  3. #
  4. # The Qubes OS Project, https://www.qubes-os.org/
  5. #
  6. # Copyright (C) 2014-2015
  7. # Marek Marczykowski-Górecki <marmarek@invisiblethingslab.com>
  8. # Copyright (C) 2015 Wojtek Porczyk <woju@invisiblethingslab.com>
  9. #
  10. # This program is free software; you can redistribute it and/or modify
  11. # it under the terms of the GNU General Public License as published by
  12. # the Free Software Foundation; either version 2 of the License, or
  13. # (at your option) any later version.
  14. #
  15. # This program is distributed in the hope that it will be useful,
  16. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  17. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  18. # GNU General Public License for more details.
  19. #
  20. # You should have received a copy of the GNU General Public License along
  21. # with this program; if not, write to the Free Software Foundation, Inc.,
  22. # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
  23. #
  24. """
  25. .. warning::
  26. The test suite hereby claims any domain whose name starts with
  27. :py:data:`VMPREFIX` as fair game. This is needed to enforce sane
  28. test executing environment. If you have domains named ``test-*``,
  29. don't run the tests.
  30. """
  31. from distutils import spawn
  32. import functools
  33. import multiprocessing
  34. import logging
  35. import os
  36. import shutil
  37. import subprocess
  38. import tempfile
  39. import unittest
  40. import unittest.case
  41. import lxml.etree
  42. import sys
  43. import pkg_resources
  44. import qubes.backup
  45. import qubes.qubes
  46. import time
  47. VMPREFIX = 'test-inst-'
  48. CLSVMPREFIX = 'test-cls-'
  49. #: :py:obj:`True` if running in dom0, :py:obj:`False` otherwise
  50. in_dom0 = False
  51. #: :py:obj:`False` if outside of git repo,
  52. #: path to root of the directory otherwise
  53. in_git = False
  54. try:
  55. import libvirt
  56. libvirt.openReadOnly(qubes.qubes.defaults['libvirt_uri']).close()
  57. in_dom0 = True
  58. except libvirt.libvirtError:
  59. pass
  60. try:
  61. in_git = subprocess.check_output(
  62. ['git', 'rev-parse', '--show-toplevel'],
  63. stderr=open(os.devnull, 'w')).strip()
  64. except subprocess.CalledProcessError:
  65. # git returned nonzero, we are outside git repo
  66. pass
  67. except OSError:
  68. # command not found; let's assume we're outside
  69. pass
  70. def skipUnlessDom0(test_item):
  71. '''Decorator that skips test outside dom0.
  72. Some tests (especially integration tests) have to be run in more or less
  73. working dom0. This is checked by connecting to libvirt.
  74. ''' # pylint: disable=invalid-name
  75. return unittest.skipUnless(in_dom0, 'outside dom0')(test_item)
  76. def skipUnlessGit(test_item):
  77. '''Decorator that skips test outside git repo.
  78. There are very few tests that an be run only in git. One example is
  79. correctness of example code that won't get included in RPM.
  80. ''' # pylint: disable=invalid-name
  81. return unittest.skipUnless(in_git, 'outside git tree')(test_item)
  82. def expectedFailureIfTemplate(templates):
  83. """
  84. Decorator for marking specific test as expected to fail only for some
  85. templates. Template name is compared as substring, so 'whonix' will
  86. handle both 'whonix-ws' and 'whonix-gw'.
  87. templates can be either a single string, or an iterable
  88. """
  89. def decorator(func):
  90. @functools.wraps(func)
  91. def wrapper(self, *args, **kwargs):
  92. template = self.template
  93. if isinstance(templates, basestring):
  94. should_expect_fail = template in templates
  95. else:
  96. should_expect_fail = any([template in x for x in templates])
  97. if should_expect_fail:
  98. try:
  99. func(self, *args, **kwargs)
  100. except Exception:
  101. raise unittest.case._ExpectedFailure(sys.exc_info())
  102. raise unittest.case._UnexpectedSuccess()
  103. else:
  104. # Call directly:
  105. func(self, *args, **kwargs)
  106. return wrapper
  107. return decorator
  108. class _AssertNotRaisesContext(object):
  109. """A context manager used to implement TestCase.assertNotRaises methods.
  110. Stolen from unittest and hacked. Regexp support stripped.
  111. """
  112. def __init__(self, expected, test_case, expected_regexp=None):
  113. self.expected = expected
  114. self.failureException = test_case.failureException
  115. def __enter__(self):
  116. return self
  117. def __exit__(self, exc_type, exc_value, tb):
  118. if exc_type is None:
  119. return True
  120. try:
  121. exc_name = self.expected.__name__
  122. except AttributeError:
  123. exc_name = str(self.expected)
  124. if issubclass(exc_type, self.expected):
  125. raise self.failureException(
  126. "{0} raised".format(exc_name))
  127. else:
  128. # pass through
  129. return False
  130. self.exception = exc_value # store for later retrieval
  131. class BeforeCleanExit(BaseException):
  132. pass
  133. class QubesTestCase(unittest.TestCase):
  134. '''Base class for Qubes unit tests.
  135. '''
  136. def __init__(self, *args, **kwargs):
  137. super(QubesTestCase, self).__init__(*args, **kwargs)
  138. self.longMessage = True
  139. self.log = logging.getLogger('{}.{}.{}'.format(
  140. self.__class__.__module__,
  141. self.__class__.__name__,
  142. self._testMethodName))
  143. def __str__(self):
  144. return '{}/{}/{}'.format(
  145. '.'.join(self.__class__.__module__.split('.')[2:]),
  146. self.__class__.__name__,
  147. self._testMethodName)
  148. def tearDown(self):
  149. super(QubesTestCase, self).tearDown()
  150. result = self._resultForDoCleanups
  151. l = result.failures \
  152. + result.errors \
  153. + [(tc, None) for tc in result.unexpectedSuccesses]
  154. if getattr(result, 'do_not_clean', False) \
  155. and filter((lambda (tc, exc): tc is self), l):
  156. raise BeforeCleanExit()
  157. def assertNotRaises(self, excClass, callableObj=None, *args, **kwargs):
  158. """Fail if an exception of class excClass is raised
  159. by callableObj when invoked with arguments args and keyword
  160. arguments kwargs. If a different type of exception is
  161. raised, it will not be caught, and the test case will be
  162. deemed to have suffered an error, exactly as for an
  163. unexpected exception.
  164. If called with callableObj omitted or None, will return a
  165. context object used like this::
  166. with self.assertRaises(SomeException):
  167. do_something()
  168. The context manager keeps a reference to the exception as
  169. the 'exception' attribute. This allows you to inspect the
  170. exception after the assertion::
  171. with self.assertRaises(SomeException) as cm:
  172. do_something()
  173. the_exception = cm.exception
  174. self.assertEqual(the_exception.error_code, 3)
  175. """
  176. context = _AssertNotRaisesContext(excClass, self)
  177. if callableObj is None:
  178. return context
  179. with context:
  180. callableObj(*args, **kwargs)
  181. def assertXMLEqual(self, xml1, xml2):
  182. """Check for equality of two XML objects.
  183. :param xml1: first element
  184. :param xml2: second element
  185. :type xml1: :py:class:`lxml.etree._Element`
  186. :type xml2: :py:class:`lxml.etree._Element`
  187. """ # pylint: disable=invalid-name
  188. self.assertEqual(xml1.tag, xml2.tag)
  189. self.assertEqual(xml1.text, xml2.text)
  190. self.assertItemsEqual(xml1.keys(), xml2.keys())
  191. for key in xml1.keys():
  192. self.assertEqual(xml1.get(key), xml2.get(key))
  193. class SystemTestsMixin(object):
  194. def setUp(self):
  195. """Set up the test.
  196. .. warning::
  197. This method instantiates QubesVmCollection acquires write lock for
  198. it. You can use is as :py:attr:`qc`. You can (and probably
  199. should) release the lock at the end of setUp in subclass
  200. """
  201. super(SystemTestsMixin, self).setUp()
  202. self.qc = qubes.qubes.QubesVmCollection()
  203. self.qc.lock_db_for_writing()
  204. self.qc.load()
  205. self.conn = libvirt.open(qubes.qubes.defaults['libvirt_uri'])
  206. self._remove_test_vms(self.qc, self.conn)
  207. def tearDown(self):
  208. super(SystemTestsMixin, self).tearDown()
  209. # release the lock, because we have no way to check whether it was
  210. # read or write lock
  211. try:
  212. self.qc.unlock_db()
  213. except qubes.qubes.QubesException:
  214. pass
  215. self._kill_test_vms(self.qc)
  216. self.qc.lock_db_for_writing()
  217. self.qc.load()
  218. self._remove_test_vms(self.qc, self.conn)
  219. self.qc.save()
  220. self.qc.unlock_db()
  221. del self.qc
  222. self.conn.close()
  223. @classmethod
  224. def tearDownClass(cls):
  225. super(SystemTestsMixin, cls).tearDownClass()
  226. qc = qubes.qubes.QubesVmCollection()
  227. qc.lock_db_for_reading()
  228. qc.load()
  229. qc.unlock_db()
  230. conn = libvirt.open(qubes.qubes.defaults['libvirt_uri'])
  231. cls._kill_test_vms(qc, prefix=CLSVMPREFIX)
  232. qc.lock_db_for_writing()
  233. qc.load()
  234. cls._remove_test_vms(qc, conn, prefix=CLSVMPREFIX)
  235. qc.save()
  236. qc.unlock_db()
  237. del qc
  238. conn.close()
  239. @staticmethod
  240. def make_vm_name(name, class_teardown=False):
  241. if class_teardown:
  242. return CLSVMPREFIX + name
  243. else:
  244. return VMPREFIX + name
  245. def save_and_reload_db(self):
  246. self.qc.save()
  247. self.qc.unlock_db()
  248. self.qc.lock_db_for_writing()
  249. self.qc.load()
  250. @staticmethod
  251. def _kill_test_vms(qc, prefix=VMPREFIX):
  252. # do not keep write lock while killing VMs, because that may cause a
  253. # deadlock with disk hotplug scripts (namely qvm-template-commit
  254. # called when shutting down TemplateVm)
  255. qc.lock_db_for_reading()
  256. qc.load()
  257. qc.unlock_db()
  258. for vm in qc.values():
  259. if vm.name.startswith(prefix):
  260. if vm.is_running():
  261. vm.force_shutdown()
  262. @classmethod
  263. def _remove_vm_qubes(cls, qc, conn, vm):
  264. vmname = vm.name
  265. try:
  266. # XXX .is_running() may throw libvirtError if undefined
  267. if vm.is_running():
  268. vm.force_shutdown()
  269. except:
  270. pass
  271. try:
  272. vm.remove_from_disk()
  273. except:
  274. pass
  275. try:
  276. vm.libvirt_domain.undefine()
  277. except libvirt.libvirtError:
  278. pass
  279. qc.pop(vm.qid)
  280. del vm
  281. # Now ensure it really went away. This may not have happened,
  282. # for example if vm.libvirtDomain malfunctioned.
  283. try:
  284. dom = conn.lookupByName(vmname)
  285. except:
  286. pass
  287. else:
  288. cls._remove_vm_libvirt(dom)
  289. cls._remove_vm_disk(vmname)
  290. @staticmethod
  291. def _remove_vm_libvirt(dom):
  292. try:
  293. dom.destroy()
  294. except libvirt.libvirtError: # not running
  295. pass
  296. dom.undefine()
  297. @staticmethod
  298. def _remove_vm_disk(vmname):
  299. for dirspec in (
  300. 'qubes_appvms_dir',
  301. 'qubes_servicevms_dir',
  302. 'qubes_templates_dir'):
  303. dirpath = os.path.join(qubes.qubes.system_path['qubes_base_dir'],
  304. qubes.qubes.system_path[dirspec], vmname)
  305. if os.path.exists(dirpath):
  306. if os.path.isdir(dirpath):
  307. shutil.rmtree(dirpath)
  308. else:
  309. os.unlink(dirpath)
  310. def remove_vms(self, vms):
  311. for vm in vms:
  312. self._remove_vm_qubes(self.qc, self.conn, vm)
  313. self.save_and_reload_db()
  314. @classmethod
  315. def _remove_test_vms(cls, qc, conn, prefix=VMPREFIX):
  316. """Aggresively remove any domain that has name in testing namespace.
  317. """
  318. # first, remove them Qubes-way
  319. something_removed = False
  320. for vm in qc.values():
  321. if vm.name.startswith(prefix):
  322. cls._remove_vm_qubes(qc, conn, vm)
  323. something_removed = True
  324. if something_removed:
  325. qc.save()
  326. qc.unlock_db()
  327. qc.lock_db_for_writing()
  328. qc.load()
  329. # now remove what was only in libvirt
  330. for dom in conn.listAllDomains():
  331. if dom.name().startswith(prefix):
  332. cls._remove_vm_libvirt(dom)
  333. # finally remove anything that is left on disk
  334. vmnames = set()
  335. for dirspec in (
  336. 'qubes_appvms_dir',
  337. 'qubes_servicevms_dir',
  338. 'qubes_templates_dir'):
  339. dirpath = os.path.join(qubes.qubes.system_path['qubes_base_dir'],
  340. qubes.qubes.system_path[dirspec])
  341. for name in os.listdir(dirpath):
  342. if name.startswith(prefix):
  343. vmnames.add(name)
  344. for vmname in vmnames:
  345. cls._remove_vm_disk(vmname)
  346. def qrexec_policy(self, service, source, destination, allow=True):
  347. """
  348. Allow qrexec calls for duration of the test
  349. :param service: service name
  350. :param source: source VM name
  351. :param destination: destination VM name
  352. :return:
  353. """
  354. def add_remove_rule(add=True):
  355. with open('/etc/qubes-rpc/policy/{}'.format(service), 'r+') as policy:
  356. policy_rules = policy.readlines()
  357. rule = "{} {} {}\n".format(source, destination,
  358. 'allow' if allow else 'deny')
  359. if add:
  360. policy_rules.insert(0, rule)
  361. else:
  362. policy_rules.remove(rule)
  363. policy.truncate(0)
  364. policy.seek(0)
  365. policy.write(''.join(policy_rules))
  366. add_remove_rule(add=True)
  367. self.addCleanup(add_remove_rule, add=False)
  368. def wait_for_window(self, title, timeout=30, show=True):
  369. """
  370. Wait for a window with a given title. Depending on show parameter,
  371. it will wait for either window to show or to disappear.
  372. :param title: title of the window to wait for
  373. :param timeout: timeout of the operation, in seconds
  374. :param show: if True - wait for the window to be visible,
  375. otherwise - to not be visible
  376. :return: None
  377. """
  378. wait_count = 0
  379. while subprocess.call(['xdotool', 'search', '--name', title],
  380. stdout=open(os.path.devnull, 'w'),
  381. stderr=subprocess.STDOUT) == int(show):
  382. wait_count += 1
  383. if wait_count > timeout*10:
  384. self.fail("Timeout while waiting for {} window to {}".format(
  385. title, "show" if show else "hide")
  386. )
  387. time.sleep(0.1)
  388. def enter_keys_in_window(self, title, keys):
  389. """
  390. Search for window with given title, then enter listed keys there.
  391. The function will wait for said window to appear.
  392. :param title: title of window
  393. :param keys: list of keys to enter, as for `xdotool key`
  394. :return: None
  395. """
  396. # 'xdotool search --sync' sometimes crashes on some race when
  397. # accessing window properties
  398. self.wait_for_window(title)
  399. command = ['xdotool', 'search', '--name', title,
  400. 'windowactivate',
  401. 'key'] + keys
  402. subprocess.check_call(command)
  403. def shutdown_and_wait(self, vm, timeout=60):
  404. """
  405. :param vm: VM object
  406. :param timeout: timeout after which fail the test
  407. :return:
  408. """
  409. vm.shutdown()
  410. while timeout > 0:
  411. if not vm.is_running():
  412. return
  413. time.sleep(1)
  414. timeout -= 1
  415. self.fail("Timeout while waiting for VM {} shutdown".format(vm.name))
  416. def prepare_hvm_system_linux(self, vm, init_script, extra_files=None):
  417. if not os.path.exists('/usr/lib/grub/i386-pc'):
  418. self.skipTest('grub2 not installed')
  419. if not spawn.find_executable('grub2-install'):
  420. self.skipTest('grub2-tools not installed')
  421. if not spawn.find_executable('dracut'):
  422. self.skipTest('dracut not installed')
  423. # create a single partition
  424. p = subprocess.Popen(['sfdisk', '-q', '-L', vm.storage.root_img],
  425. stdin=subprocess.PIPE,
  426. stdout=open(os.devnull, 'w'),
  427. stderr=subprocess.STDOUT)
  428. p.communicate('2048,\n')
  429. assert p.returncode == 0, 'sfdisk failed'
  430. # TODO: check if root_img is really file, not already block device
  431. p = subprocess.Popen(['sudo', 'losetup', '-f', '-P', '--show',
  432. vm.storage.root_img], stdout=subprocess.PIPE)
  433. (loopdev, _) = p.communicate()
  434. loopdev = loopdev.strip()
  435. looppart = loopdev + 'p1'
  436. assert p.returncode == 0, 'losetup failed'
  437. subprocess.check_call(['sudo', 'mkfs.ext2', '-q', '-F', looppart])
  438. mountpoint = tempfile.mkdtemp()
  439. subprocess.check_call(['sudo', 'mount', looppart, mountpoint])
  440. try:
  441. subprocess.check_call(['sudo', 'grub2-install',
  442. '--target', 'i386-pc',
  443. '--modules', 'part_msdos ext2',
  444. '--boot-directory', mountpoint, loopdev],
  445. stderr=open(os.devnull, 'w')
  446. )
  447. grub_cfg = '{}/grub2/grub.cfg'.format(mountpoint)
  448. subprocess.check_call(
  449. ['sudo', 'chown', '-R', os.getlogin(), mountpoint])
  450. with open(grub_cfg, 'w') as f:
  451. f.write(
  452. "set timeout=1\n"
  453. "menuentry 'Default' {\n"
  454. " linux /vmlinuz root=/dev/xvda1 "
  455. "rd.driver.blacklist=bochs_drm "
  456. "rd.driver.blacklist=uhci_hcd\n"
  457. " initrd /initrd\n"
  458. "}"
  459. )
  460. p = subprocess.Popen(['uname', '-r'], stdout=subprocess.PIPE)
  461. (kernel_version, _) = p.communicate()
  462. kernel_version = kernel_version.strip()
  463. kernel = '/boot/vmlinuz-{}'.format(kernel_version)
  464. shutil.copy(kernel, os.path.join(mountpoint, 'vmlinuz'))
  465. init_path = os.path.join(mountpoint, 'init')
  466. with open(init_path, 'w') as f:
  467. f.write(init_script)
  468. os.chmod(init_path, 0755)
  469. dracut_args = [
  470. '--kver', kernel_version,
  471. '--include', init_path,
  472. '/usr/lib/dracut/hooks/pre-pivot/initscript.sh',
  473. '--no-hostonly', '--nolvmconf', '--nomdadmconf',
  474. ]
  475. if extra_files:
  476. dracut_args += ['--install', ' '.join(extra_files)]
  477. subprocess.check_call(
  478. ['dracut'] + dracut_args + [os.path.join(mountpoint,
  479. 'initrd')],
  480. stderr=open(os.devnull, 'w')
  481. )
  482. finally:
  483. subprocess.check_call(['sudo', 'umount', mountpoint])
  484. shutil.rmtree(mountpoint)
  485. subprocess.check_call(['sudo', 'losetup', '-d', loopdev])
  486. class BackupTestsMixin(SystemTestsMixin):
  487. def setUp(self):
  488. super(BackupTestsMixin, self).setUp()
  489. self.error_detected = multiprocessing.Queue()
  490. self.verbose = False
  491. if self.verbose:
  492. print >>sys.stderr, "-> Creating backupvm"
  493. self.backupdir = os.path.join(os.environ["HOME"], "test-backup")
  494. if os.path.exists(self.backupdir):
  495. shutil.rmtree(self.backupdir)
  496. os.mkdir(self.backupdir)
  497. def tearDown(self):
  498. super(BackupTestsMixin, self).tearDown()
  499. shutil.rmtree(self.backupdir)
  500. def print_progress(self, progress):
  501. if self.verbose:
  502. print >> sys.stderr, "\r-> Backing up files: {0}%...".format(progress)
  503. def error_callback(self, message):
  504. self.error_detected.put(message)
  505. if self.verbose:
  506. print >> sys.stderr, "ERROR: {0}".format(message)
  507. def print_callback(self, msg):
  508. if self.verbose:
  509. print msg
  510. def fill_image(self, path, size=None, sparse=False):
  511. block_size = 4096
  512. if self.verbose:
  513. print >>sys.stderr, "-> Filling %s" % path
  514. f = open(path, 'w+')
  515. if size is None:
  516. f.seek(0, 2)
  517. size = f.tell()
  518. f.seek(0)
  519. for block_num in xrange(size/block_size):
  520. f.write('a' * block_size)
  521. if sparse:
  522. f.seek(block_size, 1)
  523. f.close()
  524. # NOTE: this was create_basic_vms
  525. def create_backup_vms(self):
  526. template=self.qc.get_default_template()
  527. vms = []
  528. vmname = self.make_vm_name('test-net')
  529. if self.verbose:
  530. print >>sys.stderr, "-> Creating %s" % vmname
  531. testnet = self.qc.add_new_vm('QubesNetVm',
  532. name=vmname, template=template)
  533. testnet.create_on_disk(verbose=self.verbose)
  534. vms.append(testnet)
  535. self.fill_image(testnet.private_img, 20*1024*1024)
  536. vmname = self.make_vm_name('test1')
  537. if self.verbose:
  538. print >>sys.stderr, "-> Creating %s" % vmname
  539. testvm1 = self.qc.add_new_vm('QubesAppVm',
  540. name=vmname, template=template)
  541. testvm1.uses_default_netvm = False
  542. testvm1.netvm = testnet
  543. testvm1.create_on_disk(verbose=self.verbose)
  544. vms.append(testvm1)
  545. self.fill_image(testvm1.private_img, 100*1024*1024)
  546. vmname = self.make_vm_name('testhvm1')
  547. if self.verbose:
  548. print >>sys.stderr, "-> Creating %s" % vmname
  549. testvm2 = self.qc.add_new_vm('QubesHVm', name=vmname)
  550. testvm2.create_on_disk(verbose=self.verbose)
  551. self.fill_image(testvm2.root_img, 1024*1024*1024, True)
  552. vms.append(testvm2)
  553. self.qc.save()
  554. return vms
  555. def make_backup(self, vms, prepare_kwargs=dict(), do_kwargs=dict(),
  556. target=None, expect_failure=False):
  557. # XXX: bakup_prepare and backup_do don't support host_collection
  558. self.qc.unlock_db()
  559. if target is None:
  560. target = self.backupdir
  561. try:
  562. files_to_backup = \
  563. qubes.backup.backup_prepare(vms,
  564. print_callback=self.print_callback,
  565. **prepare_kwargs)
  566. except qubes.qubes.QubesException as e:
  567. if not expect_failure:
  568. self.fail("QubesException during backup_prepare: %s" % str(e))
  569. else:
  570. raise
  571. try:
  572. qubes.backup.backup_do(target, files_to_backup, "qubes",
  573. progress_callback=self.print_progress,
  574. **do_kwargs)
  575. except qubes.qubes.QubesException as e:
  576. if not expect_failure:
  577. self.fail("QubesException during backup_do: %s" % str(e))
  578. else:
  579. raise
  580. self.qc.lock_db_for_writing()
  581. self.qc.load()
  582. def restore_backup(self, source=None, appvm=None, options=None,
  583. expect_errors=None):
  584. if source is None:
  585. backupfile = os.path.join(self.backupdir,
  586. sorted(os.listdir(self.backupdir))[-1])
  587. else:
  588. backupfile = source
  589. with self.assertNotRaises(qubes.qubes.QubesException):
  590. backup_info = qubes.backup.backup_restore_prepare(
  591. backupfile, "qubes",
  592. host_collection=self.qc,
  593. print_callback=self.print_callback,
  594. appvm=appvm,
  595. options=options or {})
  596. if self.verbose:
  597. qubes.backup.backup_restore_print_summary(backup_info)
  598. with self.assertNotRaises(qubes.qubes.QubesException):
  599. qubes.backup.backup_restore_do(
  600. backup_info,
  601. host_collection=self.qc,
  602. print_callback=self.print_callback if self.verbose else None,
  603. error_callback=self.error_callback)
  604. # maybe someone forgot to call .save()
  605. self.qc.load()
  606. errors = []
  607. if expect_errors is None:
  608. expect_errors = []
  609. while not self.error_detected.empty():
  610. current_error = self.error_detected.get()
  611. if any(map(current_error.startswith, expect_errors)):
  612. continue
  613. errors.append(current_error)
  614. self.assertTrue(len(errors) == 0,
  615. "Error(s) detected during backup_restore_do: %s" %
  616. '\n'.join(errors))
  617. if not appvm and not os.path.isdir(backupfile):
  618. os.unlink(backupfile)
  619. def create_sparse(self, path, size):
  620. f = open(path, "w")
  621. f.truncate(size)
  622. f.close()
  623. def load_tests(loader, tests, pattern):
  624. # discard any tests from this module, because it hosts base classes
  625. tests = unittest.TestSuite()
  626. for modname in (
  627. 'qubes.tests.basic',
  628. 'qubes.tests.dom0_update',
  629. 'qubes.tests.network',
  630. 'qubes.tests.vm_qrexec_gui',
  631. 'qubes.tests.backup',
  632. 'qubes.tests.backupcompatibility',
  633. 'qubes.tests.regressions',
  634. 'qubes.tests.storage',
  635. 'qubes.tests.storage_xen',
  636. 'qubes.tests.hardware',
  637. 'qubes.tests.extra',
  638. ):
  639. tests.addTests(loader.loadTestsFromName(modname))
  640. return tests
  641. # vim: ts=4 sw=4 et