__init__.py 20 KB

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