__init__.py 19 KB

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