__init__.py 35 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985
  1. # pylint: disable=invalid-name
  2. #
  3. # The Qubes OS Project, https://www.qubes-os.org/
  4. #
  5. # Copyright (C) 2014-2015 Joanna Rutkowska <joanna@invisiblethingslab.com>
  6. # Copyright (C) 2014-2015
  7. # Marek Marczykowski-Górecki <marmarek@invisiblethingslab.com>
  8. # Copyright (C) 2014-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. import asyncio
  32. import collections
  33. import functools
  34. import logging
  35. import os
  36. import pathlib
  37. import shutil
  38. import subprocess
  39. import sys
  40. import tempfile
  41. import time
  42. import traceback
  43. import unittest
  44. import warnings
  45. from distutils import spawn
  46. import lxml.etree
  47. import pkg_resources
  48. import qubes.backup
  49. import qubes.config
  50. import qubes.devices
  51. import qubes.events
  52. import qubes.exc
  53. import qubes.vm.standalonevm
  54. XMLPATH = '/var/lib/qubes/qubes-test.xml'
  55. CLASS_XMLPATH = '/var/lib/qubes/qubes-class-test.xml'
  56. TEMPLATE = 'fedora-23'
  57. VMPREFIX = 'test-inst-'
  58. CLSVMPREFIX = 'test-cls-'
  59. if 'DEFAULT_LVM_POOL' in os.environ.keys():
  60. DEFAULT_LVM_POOL = os.environ['DEFAULT_LVM_POOL']
  61. else:
  62. DEFAULT_LVM_POOL = 'qubes_dom0/pool00'
  63. POOL_CONF = {'name': 'test-lvm',
  64. 'driver': 'lvm_thin',
  65. 'volume_group': DEFAULT_LVM_POOL.split('/')[0],
  66. 'thin_pool': DEFAULT_LVM_POOL.split('/')[1]}
  67. #: :py:obj:`True` if running in dom0, :py:obj:`False` otherwise
  68. in_dom0 = False
  69. #: :py:obj:`False` if outside of git repo,
  70. #: path to root of the directory otherwise
  71. in_git = False
  72. try:
  73. import libvirt
  74. libvirt.openReadOnly(qubes.config.defaults['libvirt_uri']).close()
  75. in_dom0 = True
  76. except libvirt.libvirtError:
  77. pass
  78. try:
  79. in_git = subprocess.check_output(
  80. ['git', 'rev-parse', '--show-toplevel']).decode().strip()
  81. qubes.log.LOGPATH = '/tmp'
  82. qubes.log.LOGFILE = '/tmp/qubes.log'
  83. except subprocess.CalledProcessError:
  84. # git returned nonzero, we are outside git repo
  85. pass
  86. except OSError:
  87. # command not found; let's assume we're outside
  88. pass
  89. def skipUnlessDom0(test_item):
  90. '''Decorator that skips test outside dom0.
  91. Some tests (especially integration tests) have to be run in more or less
  92. working dom0. This is checked by connecting to libvirt.
  93. '''
  94. return unittest.skipUnless(in_dom0, 'outside dom0')(test_item)
  95. def skipUnlessGit(test_item):
  96. '''Decorator that skips test outside git repo.
  97. There are very few tests that an be run only in git. One example is
  98. correctness of example code that won't get included in RPM.
  99. '''
  100. return unittest.skipUnless(in_git, 'outside git tree')(test_item)
  101. class TestEmitter(qubes.events.Emitter):
  102. '''Dummy event emitter which records events fired on it.
  103. Events are counted in :py:attr:`fired_events` attribute, which is
  104. :py:class:`collections.Counter` instance. For each event, ``(event, args,
  105. kwargs)`` object is counted. *event* is event name (a string), *args* is
  106. tuple with positional arguments and *kwargs* is sorted tuple of items from
  107. keyword arguments.
  108. >>> emitter = TestEmitter()
  109. >>> emitter.fired_events
  110. Counter()
  111. >>> emitter.fire_event('event', spam='eggs', foo='bar')
  112. >>> emitter.fired_events
  113. Counter({('event', (1, 2, 3), (('foo', 'bar'), ('spam', 'eggs'))): 1})
  114. '''
  115. def __init__(self, *args, **kwargs):
  116. super(TestEmitter, self).__init__(*args, **kwargs)
  117. #: :py:class:`collections.Counter` instance
  118. self.fired_events = collections.Counter()
  119. def fire_event(self, event, **kwargs):
  120. effects = super(TestEmitter, self).fire_event(event, **kwargs)
  121. ev_kwargs = frozenset(
  122. (key,
  123. frozenset(value.items()) if isinstance(value, dict) else value)
  124. for key, value in kwargs.items()
  125. )
  126. self.fired_events[(event, ev_kwargs)] += 1
  127. return effects
  128. def fire_event_pre(self, event, **kwargs):
  129. effects = super(TestEmitter, self).fire_event_pre(event, **kwargs)
  130. ev_kwargs = frozenset(
  131. (key,
  132. frozenset(value.items()) if isinstance(value, dict) else value)
  133. for key, value in kwargs.items()
  134. )
  135. self.fired_events[(event, ev_kwargs)] += 1
  136. return effects
  137. def expectedFailureIfTemplate(templates):
  138. """
  139. Decorator for marking specific test as expected to fail only for some
  140. templates. Template name is compared as substring, so 'whonix' will
  141. handle both 'whonix-ws' and 'whonix-gw'.
  142. templates can be either a single string, or an iterable
  143. """
  144. def decorator(func):
  145. @functools.wraps(func)
  146. def wrapper(self, *args, **kwargs):
  147. template = self.template
  148. if isinstance(templates, str):
  149. should_expect_fail = template in templates
  150. else:
  151. should_expect_fail = any([template in x for x in templates])
  152. if should_expect_fail:
  153. try:
  154. func(self, *args, **kwargs)
  155. except Exception:
  156. raise unittest.case._ExpectedFailure(sys.exc_info())
  157. raise unittest.case._UnexpectedSuccess()
  158. else:
  159. # Call directly:
  160. func(self, *args, **kwargs)
  161. return wrapper
  162. return decorator
  163. class _AssertNotRaisesContext(object):
  164. """A context manager used to implement TestCase.assertNotRaises methods.
  165. Stolen from unittest and hacked. Regexp support stripped.
  166. """ # pylint: disable=too-few-public-methods
  167. def __init__(self, expected, test_case, expected_regexp=None):
  168. if expected_regexp is not None:
  169. raise NotImplementedError('expected_regexp is unsupported')
  170. self.expected = expected
  171. self.exception = None
  172. self.failureException = test_case.failureException
  173. def __enter__(self):
  174. return self
  175. def __exit__(self, exc_type, exc_value, tb):
  176. if exc_type is None:
  177. return True
  178. if issubclass(exc_type, self.expected):
  179. raise self.failureException(
  180. "{!r} raised, traceback:\n{!s}".format(
  181. exc_value, ''.join(traceback.format_tb(tb))))
  182. else:
  183. # pass through
  184. return False
  185. self.exception = exc_value # store for later retrieval
  186. class _QrexecPolicyContext(object):
  187. '''Context manager for SystemTestsMixin.qrexec_policy'''
  188. def __init__(self, service, source, destination, allow=True):
  189. try:
  190. source = source.name
  191. except AttributeError:
  192. pass
  193. try:
  194. destination = destination.name
  195. except AttributeError:
  196. pass
  197. self._filename = pathlib.Path('/etc/qubes-rpc/policy') / service
  198. self._rule = '{} {} {}\n'.format(source, destination,
  199. 'allow' if allow else 'deny')
  200. def _change(self, add=True):
  201. with self._filename.open('r+') as policy:
  202. policy_rules = policy.readlines()
  203. if add:
  204. policy_rules.insert(0, self._rule)
  205. else:
  206. policy_rules.remove(self._rule)
  207. policy.truncate(0)
  208. policy.seek(0)
  209. policy.write(''.join(policy_rules))
  210. def __enter__(self):
  211. self._change(add=True)
  212. return self
  213. def __exit__(self, exc_type, exc_value, tb):
  214. self._change(add=False)
  215. class substitute_entry_points(object):
  216. '''Monkey-patch pkg_resources to substitute one group in iter_entry_points
  217. This is for testing plugins, like device classes.
  218. :param str group: The group that is to be overloaded.
  219. :param str tempgroup: The substitute group.
  220. Inside this context, if one iterates over entry points in overloaded group,
  221. the iteration actually happens over the other group.
  222. This context manager is stackable. To substitute more than one entry point
  223. group, just nest two contexts.
  224. ''' # pylint: disable=invalid-name
  225. def __init__(self, group, tempgroup):
  226. self.group = group
  227. self.tempgroup = tempgroup
  228. self._orig_iter_entry_points = None
  229. def _iter_entry_points(self, group, *args, **kwargs):
  230. if group == self.group:
  231. group = self.tempgroup
  232. return self._orig_iter_entry_points(group, *args, **kwargs)
  233. def __enter__(self):
  234. self._orig_iter_entry_points = pkg_resources.iter_entry_points
  235. pkg_resources.iter_entry_points = self._iter_entry_points
  236. return self
  237. def __exit__(self, exc_type, exc_value, tb):
  238. pkg_resources.iter_entry_points = self._orig_iter_entry_points
  239. self._orig_iter_entry_points = None
  240. class BeforeCleanExit(BaseException):
  241. '''Raised from :py:meth:`QubesTestCase.tearDown` when
  242. :py:attr:`qubes.tests.run.QubesDNCTestResult.do_not_clean` is set.'''
  243. pass
  244. class QubesTestCase(unittest.TestCase):
  245. '''Base class for Qubes unit tests.
  246. '''
  247. def __init__(self, *args, **kwargs):
  248. super(QubesTestCase, self).__init__(*args, **kwargs)
  249. self.longMessage = True
  250. self.log = logging.getLogger('{}.{}.{}'.format(
  251. self.__class__.__module__,
  252. self.__class__.__name__,
  253. self._testMethodName))
  254. self.addTypeEqualityFunc(qubes.devices.DeviceManager,
  255. self.assertDevicesEqual)
  256. self.loop = None
  257. def __str__(self):
  258. return '{}/{}/{}'.format(
  259. self.__class__.__module__,
  260. self.__class__.__name__,
  261. self._testMethodName)
  262. def setUp(self):
  263. super().setUp()
  264. self.loop = asyncio.new_event_loop()
  265. asyncio.set_event_loop(self.loop)
  266. def tearDown(self):
  267. super(QubesTestCase, self).tearDown()
  268. # The loop, when closing, throws a warning if there is
  269. # some unfinished bussiness. Let's catch that.
  270. with warnings.catch_warnings():
  271. warnings.simplefilter('error')
  272. self.loop.close()
  273. # TODO: find better way in py3
  274. try:
  275. result = self._outcome.result
  276. except:
  277. result = self._resultForDoCleanups
  278. failed_test_cases = result.failures \
  279. + result.errors \
  280. + [(tc, None) for tc in result.unexpectedSuccesses]
  281. if getattr(result, 'do_not_clean', False) \
  282. and any(tc is self for tc, exc in failed_test_cases):
  283. raise BeforeCleanExit()
  284. def assertNotRaises(self, excClass, callableObj=None, *args, **kwargs):
  285. """Fail if an exception of class excClass is raised
  286. by callableObj when invoked with arguments args and keyword
  287. arguments kwargs. If a different type of exception is
  288. raised, it will not be caught, and the test case will be
  289. deemed to have suffered an error, exactly as for an
  290. unexpected exception.
  291. If called with callableObj omitted or None, will return a
  292. context object used like this::
  293. with self.assertRaises(SomeException):
  294. do_something()
  295. The context manager keeps a reference to the exception as
  296. the 'exception' attribute. This allows you to inspect the
  297. exception after the assertion::
  298. with self.assertRaises(SomeException) as cm:
  299. do_something()
  300. the_exception = cm.exception
  301. self.assertEqual(the_exception.error_code, 3)
  302. """
  303. context = _AssertNotRaisesContext(excClass, self)
  304. if callableObj is None:
  305. return context
  306. with context:
  307. callableObj(*args, **kwargs)
  308. def assertXMLEqual(self, xml1, xml2):
  309. '''Check for equality of two XML objects.
  310. :param xml1: first element
  311. :param xml2: second element
  312. :type xml1: :py:class:`lxml.etree._Element`
  313. :type xml2: :py:class:`lxml.etree._Element`
  314. ''' # pylint: disable=invalid-name
  315. self.assertEqual(xml1.tag, xml2.tag)
  316. self.assertEqual(xml1.text, xml2.text)
  317. self.assertCountEqual(xml1.keys(), xml2.keys())
  318. for key in xml1.keys():
  319. self.assertEqual(xml1.get(key), xml2.get(key))
  320. def assertDevicesEqual(self, devices1, devices2, msg=None):
  321. self.assertEqual(devices1.keys(), devices2.keys(), msg)
  322. for dev_class in devices1.keys():
  323. self.assertEqual(
  324. [str(dev) for dev in devices1[dev_class]],
  325. [str(dev) for dev in devices2[dev_class]],
  326. "Devices of class {} differs{}".format(
  327. dev_class, (": " + msg) if msg else "")
  328. )
  329. def assertEventFired(self, subject, event, kwargs=None):
  330. '''Check whether event was fired on given emitter and fail if it did
  331. not.
  332. :param subject: emitter which is being checked
  333. :type emitter: :py:class:`TestEmitter`
  334. :param str event: event identifier
  335. :param list kwargs: when given, all items must appear in kwargs passed \
  336. to an event
  337. '''
  338. will_not_match = object()
  339. for ev, ev_kwargs in subject.fired_events:
  340. if ev != event:
  341. continue
  342. if kwargs is not None:
  343. ev_kwargs = dict(ev_kwargs)
  344. if any(ev_kwargs.get(k, will_not_match) != v
  345. for k, v in kwargs.items()):
  346. continue
  347. return
  348. self.fail('event {!r} {}did not fire on {!r}'.format(
  349. event, ('' if kwargs is None else '{!r} '.format(kwargs)), subject))
  350. def assertEventNotFired(self, subject, event, kwargs=None):
  351. '''Check whether event was fired on given emitter. Fail if it did.
  352. :param subject: emitter which is being checked
  353. :type emitter: :py:class:`TestEmitter`
  354. :param str event: event identifier
  355. :param list kwargs: when given, all items must appear in kwargs passed \
  356. to an event
  357. '''
  358. will_not_match = object()
  359. for ev, ev_kwargs in subject.fired_events:
  360. if ev != event:
  361. continue
  362. if kwargs is not None:
  363. ev_kwargs = dict(ev_kwargs)
  364. if any(ev_kwargs.get(k, will_not_match) != v
  365. for k, v in kwargs.items()):
  366. continue
  367. self.fail('event {!r} {}did fire on {!r}'.format(
  368. event,
  369. ('' if kwargs is None else '{!r} '.format(kwargs)),
  370. subject))
  371. return
  372. def assertXMLIsValid(self, xml, file=None, schema=None):
  373. '''Check whether given XML fulfills Relax NG schema.
  374. Schema can be given in a couple of ways:
  375. - As separate file. This is most common, and also the only way to
  376. handle file inclusion. Call with file name as second argument.
  377. - As string containing actual schema. Put that string in *schema*
  378. keyword argument.
  379. :param lxml.etree._Element xml: XML element instance to check
  380. :param str file: filename of Relax NG schema
  381. :param str schema: optional explicit schema string
  382. ''' # pylint: disable=redefined-builtin
  383. if schema is not None and file is None:
  384. relaxng = schema
  385. if isinstance(relaxng, str):
  386. relaxng = lxml.etree.XML(relaxng)
  387. # pylint: disable=protected-access
  388. if isinstance(relaxng, lxml.etree._Element):
  389. relaxng = lxml.etree.RelaxNG(relaxng)
  390. elif file is not None and schema is None:
  391. if not os.path.isabs(file):
  392. basedirs = ['/usr/share/doc/qubes/relaxng']
  393. if in_git:
  394. basedirs.insert(0, os.path.join(in_git, 'relaxng'))
  395. for basedir in basedirs:
  396. abspath = os.path.join(basedir, file)
  397. if os.path.exists(abspath):
  398. file = abspath
  399. break
  400. relaxng = lxml.etree.RelaxNG(file=file)
  401. else:
  402. raise TypeError("There should be excactly one of 'file' and "
  403. "'schema' arguments specified.")
  404. # We have to be extra careful here in case someone messed up with
  405. # self.failureException. It should by default be AssertionError, just
  406. # what is spewed by RelaxNG(), but who knows what might happen.
  407. try:
  408. relaxng.assert_(xml)
  409. except self.failureException:
  410. raise
  411. except AssertionError as e:
  412. self.fail(str(e))
  413. @staticmethod
  414. def make_vm_name(name, class_teardown=False):
  415. if class_teardown:
  416. return CLSVMPREFIX + name
  417. else:
  418. return VMPREFIX + name
  419. class SystemTestsMixin(object):
  420. """
  421. Mixin for integration tests. All the tests here should use self.app
  422. object and when need qubes.xml path - should use :py:data:`XMLPATH`
  423. defined in this file.
  424. Every VM created by test, must use :py:meth:`SystemTestsMixin.make_vm_name`
  425. for VM name.
  426. By default self.app represents empty collection, if anything is needed
  427. there from the real collection it can be imported from self.host_app in
  428. :py:meth:`SystemTestsMixin.setUp`. But *can not be modified* in any way -
  429. this include both changing attributes in
  430. :py:attr:`SystemTestsMixin.host_app` and modifying files of such imported
  431. VM. If test need to make some modification, it must clone the VM first.
  432. If some group of tests needs class-wide initialization, first of all the
  433. author should consider if it is really needed. But if so, setUpClass can
  434. be used to create Qubes(CLASS_XMLPATH) object and create/import required
  435. stuff there. VMs created in :py:meth:`TestCase.setUpClass` should
  436. use self.make_vm_name('...', class_teardown=True) for name creation.
  437. """
  438. # noinspection PyAttributeOutsideInit
  439. def setUp(self):
  440. if not in_dom0:
  441. self.skipTest('outside dom0')
  442. super(SystemTestsMixin, self).setUp()
  443. self.remove_test_vms()
  444. # need some information from the real qubes.xml - at least installed
  445. # templates; should not be used for testing, only to initialize self.app
  446. self.host_app = qubes.Qubes(os.path.join(
  447. qubes.config.system_path['qubes_base_dir'],
  448. qubes.config.system_path['qubes_store_filename']))
  449. if os.path.exists(CLASS_XMLPATH):
  450. shutil.copy(CLASS_XMLPATH, XMLPATH)
  451. self.app = qubes.Qubes(XMLPATH)
  452. else:
  453. self.app = qubes.Qubes.create_empty_store(qubes.tests.XMLPATH,
  454. default_kernel=self.host_app.default_kernel,
  455. clockvm=None,
  456. updatevm=None
  457. )
  458. os.environ['QUBES_XML_PATH'] = XMLPATH
  459. def init_default_template(self, template=None):
  460. if template is None:
  461. template = self.host_app.default_template
  462. elif isinstance(template, str):
  463. template = self.host_app.domains[template]
  464. used_pools = [vol.pool for vol in template.volumes.values()]
  465. for pool in used_pools:
  466. if pool in self.app.pools:
  467. continue
  468. self.app.add_pool(**self.host_app.pools[pool].config)
  469. template_vm = self.app.add_new_vm(qubes.vm.templatevm.TemplateVM,
  470. name=template.name,
  471. uuid=template.uuid,
  472. label='black')
  473. for name, volume in template_vm.volumes.items():
  474. if volume.pool != template.volumes[name].pool:
  475. template_vm.storage.init_volume(name,
  476. template.volumes[name].config)
  477. self.app.default_template = template_vm
  478. def init_networking(self):
  479. if not self.app.default_template:
  480. self.skipTest('Default template required for testing networking')
  481. default_netvm = self.host_app.default_netvm
  482. # if testing Whonix Workstation based VMs, try to use sys-whonix instead
  483. if self.app.default_template.name.startswith('whonix-ws'):
  484. if 'sys-whonix' in self.host_app.domains:
  485. default_netvm = self.host_app.domains['sys-whonix']
  486. if default_netvm is None:
  487. self.skipTest('Default netvm required')
  488. if not default_netvm.is_running():
  489. self.skipTest('VM {} required to be running'.format(
  490. default_netvm.name))
  491. # Add NetVM stub to qubes-test.xml matching the one on host.
  492. # Keeping 'qid' the same is critical because IP addresses are
  493. # calculated from it.
  494. # Intentionally don't copy template (use default), as it may be based
  495. # on a different one than actually testing.
  496. netvm_clone = self.app.add_new_vm(default_netvm.__class__,
  497. qid=default_netvm.qid,
  498. name=default_netvm.name,
  499. uuid=default_netvm.uuid,
  500. label=default_netvm.label,
  501. provides_network=True
  502. )
  503. self.app.default_netvm = netvm_clone
  504. def _find_pool(self, volume_group, thin_pool):
  505. ''' Returns the pool matching the specified ``volume_group`` &
  506. ``thin_pool``, or None.
  507. '''
  508. pools = [p for p in self.app.pools
  509. if issubclass(p.__class__, qubes.storage.lvm.ThinPool)]
  510. for pool in pools:
  511. if pool.volume_group == volume_group \
  512. and pool.thin_pool == thin_pool:
  513. return pool
  514. return None
  515. def init_lvm_pool(self):
  516. volume_group, thin_pool = DEFAULT_LVM_POOL.split('/', 1)
  517. path = "/dev/mapper/{!s}-{!s}".format(volume_group, thin_pool)
  518. if not os.path.exists(path):
  519. self.skipTest('LVM thin pool {!r} does not exist'.
  520. format(DEFAULT_LVM_POOL))
  521. self.pool = self._find_pool(volume_group, thin_pool)
  522. if not self.pool:
  523. self.pool = self.app.add_pool(**POOL_CONF)
  524. self.created_pool = True
  525. def reload_db(self):
  526. self.app = qubes.Qubes(qubes.tests.XMLPATH)
  527. def save_and_reload_db(self):
  528. self.app.save()
  529. self.reload_db()
  530. def tearDown(self):
  531. super(SystemTestsMixin, self).tearDown()
  532. self.remove_test_vms()
  533. # remove all references to VM objects, to release resources - most
  534. # importantly file descriptors; this object will live
  535. # during the whole test run, but all the file descriptors would be
  536. # depleted earlier
  537. del self.app
  538. del self.host_app
  539. for attr in dir(self):
  540. if isinstance(getattr(self, attr), qubes.vm.BaseVM):
  541. delattr(self, attr)
  542. @classmethod
  543. def tearDownClass(cls):
  544. super(SystemTestsMixin, cls).tearDownClass()
  545. if not in_dom0:
  546. return
  547. cls.remove_test_vms(xmlpath=CLASS_XMLPATH, prefix=CLSVMPREFIX)
  548. @classmethod
  549. def _remove_vm_qubes(cls, vm):
  550. vmname = vm.name
  551. app = vm.app
  552. try:
  553. # XXX .is_running() may throw libvirtError if undefined
  554. if vm.is_running():
  555. vm.force_shutdown()
  556. except: # pylint: disable=bare-except
  557. pass
  558. try:
  559. vm.remove_from_disk()
  560. except: # pylint: disable=bare-except
  561. pass
  562. del app.domains[vm.qid]
  563. del vm
  564. app.save()
  565. del app
  566. # Now ensure it really went away. This may not have happened,
  567. # for example if vm.libvirt_domain malfunctioned.
  568. try:
  569. conn = libvirt.open(qubes.config.defaults['libvirt_uri'])
  570. dom = conn.lookupByName(vmname)
  571. except: # pylint: disable=bare-except
  572. pass
  573. else:
  574. cls._remove_vm_libvirt(dom)
  575. cls._remove_vm_disk(vmname)
  576. @staticmethod
  577. def _remove_vm_libvirt(dom):
  578. try:
  579. dom.destroy()
  580. except libvirt.libvirtError: # not running
  581. pass
  582. dom.undefine()
  583. @staticmethod
  584. def _remove_vm_disk(vmname):
  585. for dirspec in (
  586. 'qubes_appvms_dir',
  587. 'qubes_servicevms_dir',
  588. 'qubes_templates_dir'):
  589. dirpath = os.path.join(qubes.config.system_path['qubes_base_dir'],
  590. qubes.config.system_path[dirspec], vmname)
  591. if os.path.exists(dirpath):
  592. if os.path.isdir(dirpath):
  593. shutil.rmtree(dirpath)
  594. else:
  595. os.unlink(dirpath)
  596. @staticmethod
  597. def _remove_vm_disk_lvm(prefix=VMPREFIX):
  598. ''' Remove LVM volumes with given prefix
  599. This is "a bit" drastic, as it removes volumes regardless of volume
  600. group, thin pool etc. But we assume no important data on test system.
  601. '''
  602. try:
  603. volumes = subprocess.check_output(
  604. ['sudo', 'lvs', '--noheadings', '-o', 'vg_name,name',
  605. '--separator', '/']).decode()
  606. if ('/' + prefix) not in volumes:
  607. return
  608. subprocess.check_call(['sudo', 'lvremove', '-f'] +
  609. [vol.strip() for vol in volumes.splitlines()
  610. if ('/' + prefix) in vol],
  611. stdout=open(os.devnull, 'w'))
  612. except subprocess.CalledProcessError:
  613. pass
  614. @classmethod
  615. def remove_vms(cls, vms):
  616. for vm in vms:
  617. cls._remove_vm_qubes(vm)
  618. @classmethod
  619. def remove_test_vms(cls, xmlpath=XMLPATH, prefix=VMPREFIX):
  620. '''Aggresively remove any domain that has name in testing namespace.
  621. '''
  622. # first, remove them Qubes-way
  623. if os.path.exists(xmlpath):
  624. try:
  625. cls.remove_vms(vm for vm in qubes.Qubes(xmlpath).domains
  626. if vm.name.startswith(prefix))
  627. except (qubes.exc.QubesException, lxml.etree.XMLSyntaxError):
  628. # If qubes-test.xml is broken that much it doesn't even load,
  629. # simply remove it. VMs will be cleaned up the hard way.
  630. # TODO logging?
  631. pass
  632. os.unlink(xmlpath)
  633. # now remove what was only in libvirt
  634. conn = libvirt.open(qubes.config.defaults['libvirt_uri'])
  635. for dom in conn.listAllDomains():
  636. if dom.name().startswith(prefix):
  637. cls._remove_vm_libvirt(dom)
  638. conn.close()
  639. # finally remove anything that is left on disk
  640. vmnames = set()
  641. for dirspec in (
  642. 'qubes_appvms_dir',
  643. 'qubes_servicevms_dir',
  644. 'qubes_templates_dir'):
  645. dirpath = os.path.join(qubes.config.system_path['qubes_base_dir'],
  646. qubes.config.system_path[dirspec])
  647. for name in os.listdir(dirpath):
  648. if name.startswith(prefix):
  649. vmnames.add(name)
  650. for vmname in vmnames:
  651. cls._remove_vm_disk(vmname)
  652. cls._remove_vm_disk_lvm(prefix)
  653. def qrexec_policy(self, service, source, destination, allow=True):
  654. """
  655. Allow qrexec calls for duration of the test
  656. :param service: service name
  657. :param source: source VM name
  658. :param destination: destination VM name
  659. :return:
  660. """
  661. return _QrexecPolicyContext(service, source, destination, allow=allow)
  662. def wait_for_window(self, title, timeout=30, show=True):
  663. """
  664. Wait for a window with a given title. Depending on show parameter,
  665. it will wait for either window to show or to disappear.
  666. :param title: title of the window to wait for
  667. :param timeout: timeout of the operation, in seconds
  668. :param show: if True - wait for the window to be visible,
  669. otherwise - to not be visible
  670. :return: None
  671. """
  672. wait_count = 0
  673. while subprocess.call(['xdotool', 'search', '--name', title],
  674. stdout=open(os.path.devnull, 'w'), stderr=subprocess.STDOUT) \
  675. == int(show):
  676. wait_count += 1
  677. if wait_count > timeout*10:
  678. self.fail("Timeout while waiting for {} window to {}".format(
  679. title, "show" if show else "hide")
  680. )
  681. time.sleep(0.1)
  682. def enter_keys_in_window(self, title, keys):
  683. """
  684. Search for window with given title, then enter listed keys there.
  685. The function will wait for said window to appear.
  686. :param title: title of window
  687. :param keys: list of keys to enter, as for `xdotool key`
  688. :return: None
  689. """
  690. # 'xdotool search --sync' sometimes crashes on some race when
  691. # accessing window properties
  692. self.wait_for_window(title)
  693. command = ['xdotool', 'search', '--name', title,
  694. 'windowactivate', '--sync',
  695. 'key'] + keys
  696. subprocess.check_call(command)
  697. def shutdown_and_wait(self, vm, timeout=60):
  698. vm.shutdown()
  699. while timeout > 0:
  700. if not vm.is_running():
  701. return
  702. time.sleep(1)
  703. timeout -= 1
  704. self.fail("Timeout while waiting for VM {} shutdown".format(vm.name))
  705. def prepare_hvm_system_linux(self, vm, init_script, extra_files=None):
  706. if not os.path.exists('/usr/lib/grub/i386-pc'):
  707. self.skipTest('grub2 not installed')
  708. if not spawn.find_executable('grub2-install'):
  709. self.skipTest('grub2-tools not installed')
  710. if not spawn.find_executable('dracut'):
  711. self.skipTest('dracut not installed')
  712. # create a single partition
  713. p = subprocess.Popen(['sfdisk', '-q', '-L', vm.storage.root_img],
  714. stdin=subprocess.PIPE,
  715. stdout=open(os.devnull, 'w'),
  716. stderr=subprocess.STDOUT)
  717. p.communicate('2048,\n')
  718. assert p.returncode == 0, 'sfdisk failed'
  719. # TODO: check if root_img is really file, not already block device
  720. p = subprocess.Popen(['sudo', 'losetup', '-f', '-P', '--show',
  721. vm.storage.root_img], stdout=subprocess.PIPE)
  722. (loopdev, _) = p.communicate()
  723. loopdev = loopdev.strip()
  724. looppart = loopdev + 'p1'
  725. assert p.returncode == 0, 'losetup failed'
  726. subprocess.check_call(['sudo', 'mkfs.ext2', '-q', '-F', looppart])
  727. mountpoint = tempfile.mkdtemp()
  728. subprocess.check_call(['sudo', 'mount', looppart, mountpoint])
  729. try:
  730. subprocess.check_call(['sudo', 'grub2-install',
  731. '--target', 'i386-pc',
  732. '--modules', 'part_msdos ext2',
  733. '--boot-directory', mountpoint, loopdev],
  734. stderr=open(os.devnull, 'w')
  735. )
  736. grub_cfg = '{}/grub2/grub.cfg'.format(mountpoint)
  737. subprocess.check_call(
  738. ['sudo', 'chown', '-R', os.getlogin(), mountpoint])
  739. with open(grub_cfg, 'w') as f:
  740. f.write(
  741. "set timeout=1\n"
  742. "menuentry 'Default' {\n"
  743. " linux /vmlinuz root=/dev/xvda1 "
  744. "rd.driver.blacklist=bochs_drm "
  745. "rd.driver.blacklist=uhci_hcd console=hvc0\n"
  746. " initrd /initrd\n"
  747. "}"
  748. )
  749. p = subprocess.Popen(['uname', '-r'], stdout=subprocess.PIPE)
  750. (kernel_version, _) = p.communicate()
  751. kernel_version = kernel_version.strip()
  752. kernel = '/boot/vmlinuz-{}'.format(kernel_version)
  753. shutil.copy(kernel, os.path.join(mountpoint, 'vmlinuz'))
  754. init_path = os.path.join(mountpoint, 'init')
  755. with open(init_path, 'w') as f:
  756. f.write(init_script)
  757. os.chmod(init_path, 0o755)
  758. dracut_args = [
  759. '--kver', kernel_version,
  760. '--include', init_path,
  761. '/usr/lib/dracut/hooks/pre-pivot/initscript.sh',
  762. '--no-hostonly', '--nolvmconf', '--nomdadmconf',
  763. ]
  764. if extra_files:
  765. dracut_args += ['--install', ' '.join(extra_files)]
  766. subprocess.check_call(
  767. ['dracut'] + dracut_args + [os.path.join(mountpoint,
  768. 'initrd')],
  769. stderr=open(os.devnull, 'w')
  770. )
  771. finally:
  772. subprocess.check_call(['sudo', 'umount', mountpoint])
  773. shutil.rmtree(mountpoint)
  774. subprocess.check_call(['sudo', 'losetup', '-d', loopdev])
  775. def load_tests(loader, tests, pattern): # pylint: disable=unused-argument
  776. # discard any tests from this module, because it hosts base classes
  777. tests = unittest.TestSuite()
  778. for modname in (
  779. # unit tests
  780. 'qubes.tests.events',
  781. 'qubes.tests.devices',
  782. 'qubes.tests.firewall',
  783. 'qubes.tests.init',
  784. 'qubes.tests.vm.init',
  785. 'qubes.tests.storage',
  786. 'qubes.tests.storage_file',
  787. 'qubes.tests.storage_lvm',
  788. 'qubes.tests.storage_kernels',
  789. 'qubes.tests.vm.qubesvm',
  790. 'qubes.tests.vm.mix.net',
  791. 'qubes.tests.vm.adminvm',
  792. 'qubes.tests.app',
  793. 'qubes.tests.tarwriter',
  794. 'qubes.tests.api_admin',
  795. 'qubespolicy.tests',
  796. 'qubes.tests.tools.qubesd',
  797. ):
  798. tests.addTests(loader.loadTestsFromName(modname))
  799. # GTK/Glib is way too old there
  800. if 'TRAVIS' not in os.environ:
  801. for modname in (
  802. 'qubespolicy.tests.gtkhelpers',
  803. 'qubespolicy.tests.rpcconfirmation',
  804. ):
  805. tests.addTests(loader.loadTestsFromName(modname))
  806. tests.addTests(loader.discover(
  807. os.path.join(os.path.dirname(__file__), 'tools')))
  808. if not in_dom0:
  809. return tests
  810. for modname in (
  811. # integration tests
  812. 'qubes.tests.integ.basic',
  813. 'qubes.tests.integ.storage',
  814. 'qubes.tests.integ.devices_pci',
  815. 'qubes.tests.integ.dom0_update',
  816. 'qubes.tests.integ.network',
  817. 'qubes.tests.integ.dispvm',
  818. 'qubes.tests.integ.vm_qrexec_gui',
  819. 'qubes.tests.integ.backup',
  820. 'qubes.tests.integ.backupcompatibility',
  821. # 'qubes.tests.regressions',
  822. # external modules
  823. # 'qubes.tests.extra',
  824. ):
  825. tests.addTests(loader.loadTestsFromName(modname))
  826. return tests