__init__.py 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519
  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. import multiprocessing
  25. import logging
  26. import os
  27. import shutil
  28. import subprocess
  29. import unittest
  30. import lxml.etree
  31. import sys
  32. import qubes.backup
  33. import qubes.qubes
  34. VMPREFIX = 'test-'
  35. #: :py:obj:`True` if running in dom0, :py:obj:`False` otherwise
  36. in_dom0 = False
  37. #: :py:obj:`False` if outside of git repo,
  38. #: path to root of the directory otherwise
  39. in_git = False
  40. try:
  41. import libvirt
  42. libvirt.openReadOnly(qubes.qubes.defaults['libvirt_uri']).close()
  43. in_dom0 = True
  44. except libvirt.libvirtError:
  45. pass
  46. try:
  47. in_git = subprocess.check_output(
  48. ['git', 'rev-parse', '--show-toplevel'],
  49. stderr=open(os.devnull, 'w')).strip()
  50. except subprocess.CalledProcessError:
  51. # git returned nonzero, we are outside git repo
  52. pass
  53. except OSError:
  54. # command not found; let's assume we're outside
  55. pass
  56. def skipUnlessDom0(test_item):
  57. '''Decorator that skips test outside dom0.
  58. Some tests (especially integration tests) have to be run in more or less
  59. working dom0. This is checked by connecting to libvirt.
  60. ''' # pylint: disable=invalid-name
  61. return unittest.skipUnless(in_dom0, 'outside dom0')(test_item)
  62. def skipUnlessGit(test_item):
  63. '''Decorator that skips test outside git repo.
  64. There are very few tests that an be run only in git. One example is
  65. correctness of example code that won't get included in RPM.
  66. ''' # pylint: disable=invalid-name
  67. return unittest.skipUnless(in_git, 'outside git tree')(test_item)
  68. class _AssertNotRaisesContext(object):
  69. """A context manager used to implement TestCase.assertNotRaises methods.
  70. Stolen from unittest and hacked. Regexp support stripped.
  71. """
  72. def __init__(self, expected, test_case, expected_regexp=None):
  73. self.expected = expected
  74. self.failureException = test_case.failureException
  75. def __enter__(self):
  76. return self
  77. def __exit__(self, exc_type, exc_value, tb):
  78. if exc_type is None:
  79. return True
  80. try:
  81. exc_name = self.expected.__name__
  82. except AttributeError:
  83. exc_name = str(self.expected)
  84. if issubclass(exc_type, self.expected):
  85. raise self.failureException(
  86. "{0} raised".format(exc_name))
  87. else:
  88. # pass through
  89. return False
  90. self.exception = exc_value # store for later retrieval
  91. class BeforeCleanExit(BaseException):
  92. pass
  93. class QubesTestCase(unittest.TestCase):
  94. '''Base class for Qubes unit tests.
  95. '''
  96. def __init__(self, *args, **kwargs):
  97. super(QubesTestCase, self).__init__(*args, **kwargs)
  98. self.longMessage = True
  99. self.log = logging.getLogger('{}.{}.{}'.format(
  100. self.__class__.__module__,
  101. self.__class__.__name__,
  102. self._testMethodName))
  103. def __str__(self):
  104. return '{}/{}/{}'.format(
  105. '.'.join(self.__class__.__module__.split('.')[2:]),
  106. self.__class__.__name__,
  107. self._testMethodName)
  108. def tearDown(self):
  109. super(QubesTestCase, self).tearDown()
  110. result = self._resultForDoCleanups
  111. l = result.failures \
  112. + result.errors \
  113. + [(tc, None) for tc in result.unexpectedSuccesses]
  114. if getattr(result, 'do_not_clean', False) \
  115. and filter((lambda (tc, exc): tc is self), l):
  116. raise BeforeCleanExit()
  117. def assertNotRaises(self, excClass, callableObj=None, *args, **kwargs):
  118. """Fail if an exception of class excClass is raised
  119. by callableObj when invoked with arguments args and keyword
  120. arguments kwargs. If a different type of exception is
  121. raised, it will not be caught, and the test case will be
  122. deemed to have suffered an error, exactly as for an
  123. unexpected exception.
  124. If called with callableObj omitted or None, will return a
  125. context object used like this::
  126. with self.assertRaises(SomeException):
  127. do_something()
  128. The context manager keeps a reference to the exception as
  129. the 'exception' attribute. This allows you to inspect the
  130. exception after the assertion::
  131. with self.assertRaises(SomeException) as cm:
  132. do_something()
  133. the_exception = cm.exception
  134. self.assertEqual(the_exception.error_code, 3)
  135. """
  136. context = _AssertNotRaisesContext(excClass, self)
  137. if callableObj is None:
  138. return context
  139. with context:
  140. callableObj(*args, **kwargs)
  141. def assertXMLEqual(self, xml1, xml2):
  142. '''Check for equality of two XML objects.
  143. :param xml1: first element
  144. :param xml2: second element
  145. :type xml1: :py:class:`lxml.etree._Element`
  146. :type xml2: :py:class:`lxml.etree._Element`
  147. ''' # pylint: disable=invalid-name
  148. self.assertEqual(xml1.tag, xml2.tag)
  149. self.assertEqual(xml1.text, xml2.text)
  150. self.assertItemsEqual(xml1.keys(), xml2.keys())
  151. for key in xml1.keys():
  152. self.assertEqual(xml1.get(key), xml2.get(key))
  153. class SystemTestsMixin(object):
  154. def setUp(self):
  155. '''Set up the test.
  156. .. warning::
  157. This method instantiates QubesVmCollection acquires write lock for
  158. it. You can use is as :py:attr:`qc`. You can (and probably
  159. should) release the lock at the end of setUp in subclass
  160. '''
  161. super(SystemTestsMixin, self).setUp()
  162. self.qc = qubes.qubes.QubesVmCollection()
  163. self.qc.lock_db_for_writing()
  164. self.qc.load()
  165. self.conn = libvirt.open(qubes.qubes.defaults['libvirt_uri'])
  166. self.remove_test_vms()
  167. def tearDown(self):
  168. super(SystemTestsMixin, self).tearDown()
  169. try: self.qc.lock_db_for_writing()
  170. except qubes.qubes.QubesException: pass
  171. self.qc.load()
  172. self.remove_test_vms()
  173. self.qc.save()
  174. self.qc.unlock_db()
  175. del self.qc
  176. self.conn.close()
  177. def make_vm_name(self, name):
  178. return VMPREFIX + name
  179. def save_and_reload_db(self):
  180. self.qc.save()
  181. self.qc.unlock_db()
  182. self.qc.lock_db_for_writing()
  183. self.qc.load()
  184. def _remove_vm_qubes(self, vm):
  185. vmname = vm.name
  186. try:
  187. # XXX .is_running() may throw libvirtError if undefined
  188. if vm.is_running():
  189. vm.force_shutdown()
  190. except: pass
  191. try: vm.remove_from_disk()
  192. except: pass
  193. try: vm.libvirt_domain.undefine()
  194. except libvirt.libvirtError: pass
  195. self.qc.pop(vm.qid)
  196. del vm
  197. # Now ensure it really went away. This may not have happened,
  198. # for example if vm.libvirtDomain malfunctioned.
  199. try:
  200. dom = self.conn.lookupByName(vmname)
  201. except: pass
  202. else:
  203. self._remove_vm_libvirt(dom)
  204. self._remove_vm_disk(vmname)
  205. def _remove_vm_libvirt(self, dom):
  206. try:
  207. dom.destroy()
  208. except libvirt.libvirtError: # not running
  209. pass
  210. dom.undefine()
  211. def _remove_vm_disk(self, vmname):
  212. for dirspec in (
  213. 'qubes_appvms_dir',
  214. 'qubes_servicevms_dir',
  215. 'qubes_templates_dir'):
  216. dirpath = os.path.join(qubes.qubes.system_path['qubes_base_dir'],
  217. qubes.qubes.system_path[dirspec], vmname)
  218. if os.path.exists(dirpath):
  219. if os.path.isdir(dirpath):
  220. shutil.rmtree(dirpath)
  221. else:
  222. os.unlink(dirpath)
  223. def remove_vms(self, vms):
  224. for vm in vms: self._remove_vm_qubes(vm)
  225. self.save_and_reload_db()
  226. def remove_test_vms(self):
  227. '''Aggresively remove any domain that has name in testing namespace.
  228. .. warning::
  229. The test suite hereby claims any domain whose name starts with
  230. :py:data:`VMPREFIX` as fair game. This is needed to enforce sane
  231. test executing environment. If you have domains named ``test-*``,
  232. don't run the tests.
  233. '''
  234. # first, remove them Qubes-way
  235. something_removed = False
  236. for vm in self.qc.values():
  237. if vm.name.startswith(VMPREFIX):
  238. self._remove_vm_qubes(vm)
  239. something_removed = True
  240. if something_removed:
  241. self.save_and_reload_db()
  242. # now remove what was only in libvirt
  243. for dom in self.conn.listAllDomains():
  244. if dom.name().startswith(VMPREFIX):
  245. self._remove_vm_libvirt(dom)
  246. # finally remove anything that is left on disk
  247. vmnames = set()
  248. for dirspec in (
  249. 'qubes_appvms_dir',
  250. 'qubes_servicevms_dir',
  251. 'qubes_templates_dir'):
  252. dirpath = os.path.join(qubes.qubes.system_path['qubes_base_dir'],
  253. qubes.qubes.system_path[dirspec])
  254. for name in os.listdir(dirpath):
  255. if name.startswith(VMPREFIX):
  256. vmnames.add(name)
  257. for vmname in vmnames:
  258. self._remove_vm_disk(vmname)
  259. class BackupTestsMixin(SystemTestsMixin):
  260. def setUp(self):
  261. super(BackupTestsMixin, self).setUp()
  262. self.error_detected = multiprocessing.Queue()
  263. self.verbose = False
  264. if self.verbose:
  265. print >>sys.stderr, "-> Creating backupvm"
  266. # TODO: allow non-default template
  267. self.backupvm = self.qc.add_new_vm("QubesAppVm",
  268. name=self.make_vm_name('backupvm'),
  269. template=self.qc.get_default_template())
  270. self.backupvm.create_on_disk(verbose=self.verbose)
  271. self.backupdir = os.path.join(os.environ["HOME"], "test-backup")
  272. if os.path.exists(self.backupdir):
  273. shutil.rmtree(self.backupdir)
  274. os.mkdir(self.backupdir)
  275. def tearDown(self):
  276. super(BackupTestsMixin, self).tearDown()
  277. shutil.rmtree(self.backupdir)
  278. def print_progress(self, progress):
  279. if self.verbose:
  280. print >> sys.stderr, "\r-> Backing up files: {0}%...".format(progress)
  281. def error_callback(self, message):
  282. self.error_detected.put(message)
  283. if self.verbose:
  284. print >> sys.stderr, "ERROR: {0}".format(message)
  285. def print_callback(self, msg):
  286. if self.verbose:
  287. print msg
  288. def fill_image(self, path, size=None, sparse=False):
  289. block_size = 4096
  290. if self.verbose:
  291. print >>sys.stderr, "-> Filling %s" % path
  292. f = open(path, 'w+')
  293. if size is None:
  294. f.seek(0, 2)
  295. size = f.tell()
  296. f.seek(0)
  297. for block_num in xrange(size/block_size):
  298. f.write('a' * block_size)
  299. if sparse:
  300. f.seek(block_size, 1)
  301. f.close()
  302. # NOTE: this was create_basic_vms
  303. def create_backup_vms(self):
  304. template=self.qc.get_default_template()
  305. vms = []
  306. vmname = self.make_vm_name('test1')
  307. if self.verbose:
  308. print >>sys.stderr, "-> Creating %s" % vmname
  309. testvm1 = self.qc.add_new_vm('QubesAppVm',
  310. name=vmname, template=template)
  311. testvm1.create_on_disk(verbose=self.verbose)
  312. vms.append(testvm1)
  313. self.fill_image(testvm1.private_img, 100*1024*1024)
  314. vmname = self.make_vm_name('testhvm1')
  315. if self.verbose:
  316. print >>sys.stderr, "-> Creating %s" % vmname
  317. testvm2 = self.qc.add_new_vm('QubesHVm', name=vmname)
  318. testvm2.create_on_disk(verbose=self.verbose)
  319. self.fill_image(testvm2.root_img, 1024*1024*1024, True)
  320. vms.append(testvm2)
  321. self.qc.save()
  322. return vms
  323. def make_backup(self, vms, prepare_kwargs=dict(), do_kwargs=dict(),
  324. target=None):
  325. # XXX: bakup_prepare and backup_do don't support host_collection
  326. self.qc.unlock_db()
  327. if target is None:
  328. target = self.backupdir
  329. try:
  330. files_to_backup = \
  331. qubes.backup.backup_prepare(vms,
  332. print_callback=self.print_callback,
  333. **prepare_kwargs)
  334. except qubes.qubes.QubesException as e:
  335. self.fail("QubesException during backup_prepare: %s" % str(e))
  336. try:
  337. qubes.backup.backup_do(target, files_to_backup, "qubes",
  338. progress_callback=self.print_progress,
  339. **do_kwargs)
  340. except qubes.qubes.QubesException as e:
  341. self.fail("QubesException during backup_do: %s" % str(e))
  342. self.qc.lock_db_for_writing()
  343. self.qc.load()
  344. def restore_backup(self, source=None, appvm=None, options=None):
  345. if source is None:
  346. backupfile = os.path.join(self.backupdir,
  347. sorted(os.listdir(self.backupdir))[-1])
  348. else:
  349. backupfile = source
  350. with self.assertNotRaises(qubes.qubes.QubesException):
  351. backup_info = qubes.backup.backup_restore_prepare(
  352. backupfile, "qubes",
  353. host_collection=self.qc,
  354. print_callback=self.print_callback,
  355. appvm=appvm,
  356. options=options or {})
  357. if self.verbose:
  358. qubes.backup.backup_restore_print_summary(backup_info)
  359. with self.assertNotRaises(qubes.qubes.QubesException):
  360. qubes.backup.backup_restore_do(
  361. backup_info,
  362. host_collection=self.qc,
  363. print_callback=self.print_callback if self.verbose else None,
  364. error_callback=self.error_callback)
  365. # maybe someone forgot to call .save()
  366. self.qc.load()
  367. errors = []
  368. while not self.error_detected.empty():
  369. errors.append(self.error_detected.get())
  370. self.assertTrue(len(errors) == 0,
  371. "Error(s) detected during backup_restore_do: %s" %
  372. '\n'.join(errors))
  373. if not appvm and not os.path.isdir(backupfile):
  374. os.unlink(backupfile)
  375. def create_sparse(self, path, size):
  376. f = open(path, "w")
  377. f.truncate(size)
  378. f.close()
  379. def load_tests(loader, tests, pattern):
  380. # discard any tests from this module, because it hosts base classes
  381. tests = unittest.TestSuite()
  382. for modname in (
  383. 'qubes.tests.basic',
  384. 'qubes.tests.dom0_update',
  385. 'qubes.tests.network',
  386. 'qubes.tests.vm_qrexec_gui',
  387. 'qubes.tests.backup',
  388. 'qubes.tests.backupcompatibility',
  389. 'qubes.tests.regressions',
  390. ):
  391. tests.addTests(loader.loadTestsFromName(modname))
  392. return tests
  393. # vim: ts=4 sw=4 et