__init__.py 41 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179
  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 library is free software; you can redistribute it and/or
  11. # modify it under the terms of the GNU Lesser General Public
  12. # License as published by the Free Software Foundation; either
  13. # version 2.1 of the License, or (at your option) any later version.
  14. #
  15. # This library 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 GNU
  18. # Lesser General Public License for more details.
  19. #
  20. # You should have received a copy of the GNU Lesser General Public
  21. # License along with this library; if not, see <https://www.gnu.org/licenses/>.
  22. #
  23. """
  24. .. warning::
  25. The test suite hereby claims any domain whose name starts with
  26. :py:data:`VMPREFIX` as fair game. This is needed to enforce sane
  27. test executing environment. If you have domains named ``test-*``,
  28. don't run the tests.
  29. """
  30. import asyncio
  31. import collections
  32. import functools
  33. import logging
  34. import os
  35. import pathlib
  36. import shlex
  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 gc
  47. import lxml.etree
  48. import pkg_resources
  49. import qubes
  50. import qubes.api
  51. import qubes.api.admin
  52. import qubes.api.internal
  53. import qubes.backup
  54. import qubes.config
  55. import qubes.devices
  56. import qubes.events
  57. import qubes.exc
  58. import qubes.vm.standalonevm
  59. import qubes.vm.templatevm
  60. XMLPATH = '/var/lib/qubes/qubes-test.xml'
  61. CLASS_XMLPATH = '/var/lib/qubes/qubes-class-test.xml'
  62. TEMPLATE = 'fedora-23'
  63. VMPREFIX = 'test-inst-'
  64. CLSVMPREFIX = 'test-cls-'
  65. if 'DEFAULT_LVM_POOL' in os.environ.keys():
  66. DEFAULT_LVM_POOL = os.environ['DEFAULT_LVM_POOL']
  67. else:
  68. DEFAULT_LVM_POOL = 'qubes_dom0/pool00'
  69. POOL_CONF = {'name': 'test-lvm',
  70. 'driver': 'lvm_thin',
  71. 'volume_group': DEFAULT_LVM_POOL.split('/')[0],
  72. 'thin_pool': DEFAULT_LVM_POOL.split('/')[1]}
  73. #: :py:obj:`True` if running in dom0, :py:obj:`False` otherwise
  74. in_dom0 = False
  75. #: :py:obj:`False` if outside of git repo,
  76. #: path to root of the directory otherwise
  77. in_git = False
  78. try:
  79. import libvirt
  80. libvirt.openReadOnly(qubes.config.defaults['libvirt_uri']).close()
  81. in_dom0 = True
  82. except libvirt.libvirtError:
  83. pass
  84. if in_dom0:
  85. import libvirtaio
  86. libvirt_event_impl = libvirtaio.virEventRegisterAsyncIOImpl()
  87. else:
  88. libvirt_event_impl = None
  89. try:
  90. in_git = subprocess.check_output(
  91. ['git', 'rev-parse', '--show-toplevel']).decode().strip()
  92. qubes.log.LOGPATH = '/tmp'
  93. qubes.log.LOGFILE = '/tmp/qubes.log'
  94. except subprocess.CalledProcessError:
  95. # git returned nonzero, we are outside git repo
  96. pass
  97. except OSError:
  98. # command not found; let's assume we're outside
  99. pass
  100. def skipUnlessDom0(test_item):
  101. '''Decorator that skips test outside dom0.
  102. Some tests (especially integration tests) have to be run in more or less
  103. working dom0. This is checked by connecting to libvirt.
  104. '''
  105. return unittest.skipUnless(in_dom0, 'outside dom0')(test_item)
  106. def skipUnlessGit(test_item):
  107. '''Decorator that skips test outside git repo.
  108. There are very few tests that an be run only in git. One example is
  109. correctness of example code that won't get included in RPM.
  110. '''
  111. return unittest.skipUnless(in_git, 'outside git tree')(test_item)
  112. def skipUnlessEnv(varname):
  113. '''Decorator generator for skipping tests without environment variable set.
  114. Some tests require working X11 display, like those using GTK library, which
  115. segfaults without connection to X.
  116. Other require their own, custom variables.
  117. '''
  118. return unittest.skipUnless(os.getenv(varname), 'no {} set'.format(varname))
  119. class TestEmitter(qubes.events.Emitter):
  120. '''Dummy event emitter which records events fired on it.
  121. Events are counted in :py:attr:`fired_events` attribute, which is
  122. :py:class:`collections.Counter` instance. For each event, ``(event, args,
  123. kwargs)`` object is counted. *event* is event name (a string), *args* is
  124. tuple with positional arguments and *kwargs* is sorted tuple of items from
  125. keyword arguments.
  126. >>> emitter = TestEmitter()
  127. >>> emitter.fired_events
  128. Counter()
  129. >>> emitter.fire_event('event', spam='eggs', foo='bar')
  130. >>> emitter.fired_events
  131. Counter({('event', (1, 2, 3), (('foo', 'bar'), ('spam', 'eggs'))): 1})
  132. '''
  133. def __init__(self, *args, **kwargs):
  134. super(TestEmitter, self).__init__(*args, **kwargs)
  135. #: :py:class:`collections.Counter` instance
  136. self.fired_events = collections.Counter()
  137. def fire_event(self, event, **kwargs):
  138. effects = super(TestEmitter, self).fire_event(event, **kwargs)
  139. ev_kwargs = frozenset(
  140. (key,
  141. frozenset(value.items()) if isinstance(value, dict)
  142. else tuple(value) if isinstance(value, list)
  143. else value)
  144. for key, value in kwargs.items()
  145. )
  146. self.fired_events[(event, ev_kwargs)] += 1
  147. return effects
  148. @asyncio.coroutine
  149. def fire_event_async(self, event, pre_event=False, **kwargs):
  150. effects = yield from super(TestEmitter, self).fire_event_async(
  151. event, pre_event=pre_event, **kwargs)
  152. ev_kwargs = frozenset(
  153. (key,
  154. frozenset(value.items()) if isinstance(value, dict) else value)
  155. for key, value in kwargs.items()
  156. )
  157. self.fired_events[(event, ev_kwargs)] += 1
  158. return effects
  159. def expectedFailureIfTemplate(templates):
  160. """
  161. Decorator for marking specific test as expected to fail only for some
  162. templates. Template name is compared as substring, so 'whonix' will
  163. handle both 'whonix-ws' and 'whonix-gw'.
  164. templates can be either a single string, or an iterable
  165. """
  166. def decorator(func):
  167. @functools.wraps(func)
  168. def wrapper(self, *args, **kwargs):
  169. template = self.template
  170. if isinstance(templates, str):
  171. should_expect_fail = template in templates
  172. else:
  173. should_expect_fail = any([template in x for x in templates])
  174. if should_expect_fail:
  175. try:
  176. func(self, *args, **kwargs)
  177. except Exception:
  178. raise unittest.case._ExpectedFailure(sys.exc_info())
  179. raise unittest.case._UnexpectedSuccess()
  180. else:
  181. # Call directly:
  182. func(self, *args, **kwargs)
  183. return wrapper
  184. return decorator
  185. class _AssertNotRaisesContext(object):
  186. """A context manager used to implement TestCase.assertNotRaises methods.
  187. Stolen from unittest and hacked. Regexp support stripped.
  188. """ # pylint: disable=too-few-public-methods
  189. def __init__(self, expected, test_case, expected_regexp=None):
  190. if expected_regexp is not None:
  191. raise NotImplementedError('expected_regexp is unsupported')
  192. self.expected = expected
  193. self.exception = None
  194. self.failureException = test_case.failureException
  195. def __enter__(self):
  196. return self
  197. def __exit__(self, exc_type, exc_value, tb):
  198. if exc_type is None:
  199. return True
  200. if issubclass(exc_type, self.expected):
  201. raise self.failureException(
  202. "{!r} raised, traceback:\n{!s}".format(
  203. exc_value, ''.join(traceback.format_tb(tb))))
  204. else:
  205. # pass through
  206. return False
  207. self.exception = exc_value # store for later retrieval
  208. class _QrexecPolicyContext(object):
  209. '''Context manager for SystemTestCase.qrexec_policy'''
  210. def __init__(self, service, source, destination, allow=True, action=None):
  211. try:
  212. source = source.name
  213. except AttributeError:
  214. pass
  215. try:
  216. destination = destination.name
  217. except AttributeError:
  218. pass
  219. self._filename = pathlib.Path('/etc/qubes-rpc/policy') / service
  220. if action is None:
  221. action = 'allow' if allow else 'deny'
  222. self._rule = '{} {} {}\n'.format(source, destination, action)
  223. self._did_create = False
  224. self._handle = None
  225. def load(self):
  226. if self._handle is None:
  227. try:
  228. self._handle = self._filename.open('r+')
  229. except FileNotFoundError:
  230. self._handle = self._filename.open('w+')
  231. self._did_create = True
  232. self._handle.seek(0)
  233. return self._handle.readlines()
  234. def save(self, rules):
  235. assert self._handle is not None
  236. self._handle.truncate(0)
  237. self._handle.seek(0)
  238. self._handle.write(''.join(rules))
  239. self._handle.flush()
  240. def close(self):
  241. assert self._handle is not None
  242. self._handle.close()
  243. self._handle = None
  244. def __enter__(self):
  245. rules = self.load()
  246. rules.insert(0, self._rule)
  247. self.save(self._rule)
  248. return self
  249. def __exit__(self, exc_type, exc_value, tb):
  250. if not self._did_create:
  251. try:
  252. rules = self.load()
  253. rules.remove(self._rule)
  254. self.save(rules)
  255. finally:
  256. self.close()
  257. else:
  258. self.close()
  259. self._filename.unlink()
  260. class substitute_entry_points(object):
  261. '''Monkey-patch pkg_resources to substitute one group in iter_entry_points
  262. This is for testing plugins, like device classes.
  263. :param str group: The group that is to be overloaded.
  264. :param str tempgroup: The substitute group.
  265. Inside this context, if one iterates over entry points in overloaded group,
  266. the iteration actually happens over the other group.
  267. This context manager is stackable. To substitute more than one entry point
  268. group, just nest two contexts.
  269. ''' # pylint: disable=invalid-name
  270. def __init__(self, group, tempgroup):
  271. self.group = group
  272. self.tempgroup = tempgroup
  273. self._orig_iter_entry_points = None
  274. def _iter_entry_points(self, group, *args, **kwargs):
  275. if group == self.group:
  276. group = self.tempgroup
  277. return self._orig_iter_entry_points(group, *args, **kwargs)
  278. def __enter__(self):
  279. self._orig_iter_entry_points = pkg_resources.iter_entry_points
  280. pkg_resources.iter_entry_points = self._iter_entry_points
  281. return self
  282. def __exit__(self, exc_type, exc_value, tb):
  283. pkg_resources.iter_entry_points = self._orig_iter_entry_points
  284. self._orig_iter_entry_points = None
  285. class QubesTestCase(unittest.TestCase):
  286. '''Base class for Qubes unit tests.
  287. '''
  288. def __init__(self, *args, **kwargs):
  289. super(QubesTestCase, self).__init__(*args, **kwargs)
  290. self.longMessage = True
  291. self.log = logging.getLogger('{}.{}.{}'.format(
  292. self.__class__.__module__,
  293. self.__class__.__name__,
  294. self._testMethodName))
  295. self.addTypeEqualityFunc(qubes.devices.DeviceManager,
  296. self.assertDevicesEqual)
  297. self.loop = None
  298. def __str__(self):
  299. return '{}/{}/{}'.format(
  300. self.__class__.__module__,
  301. self.__class__.__name__,
  302. self._testMethodName)
  303. def setUp(self):
  304. super().setUp()
  305. self.addCleanup(self.cleanup_gc)
  306. self.loop = asyncio.get_event_loop()
  307. self.addCleanup(self.cleanup_loop)
  308. def cleanup_gc(self):
  309. gc.collect()
  310. leaked = [obj for obj in gc.get_objects() + gc.garbage
  311. if isinstance(obj,
  312. (qubes.Qubes, qubes.vm.BaseVM,
  313. libvirt.virConnect, libvirt.virDomain))]
  314. if leaked:
  315. try:
  316. import objgraph
  317. objgraph.show_backrefs(leaked,
  318. max_depth=15, extra_info=extra_info,
  319. filename='/tmp/objgraph-{}.png'.format(self.id()))
  320. except ImportError:
  321. pass
  322. assert not leaked
  323. def cleanup_loop(self):
  324. '''Check if the loop is empty'''
  325. # XXX BEWARE this is touching undocumented, implementation-specific
  326. # attributes of the loop. This is most certainly unsupported and likely
  327. # will break when messing with: Python version, kernel family, loop
  328. # implementation, a combination thereof, or other things.
  329. # KEYWORDS for searching:
  330. # win32, SelectorEventLoop, ProactorEventLoop, uvloop, gevent
  331. global libvirt_event_impl
  332. # Check for unfinished libvirt business.
  333. if libvirt_event_impl is not None:
  334. try:
  335. self.loop.run_until_complete(asyncio.wait_for(
  336. libvirt_event_impl.drain(), timeout=4))
  337. except asyncio.TimeoutError:
  338. raise AssertionError('libvirt event impl drain timeout')
  339. # Check there are no Tasks left.
  340. assert not self.loop._ready
  341. assert not self.loop._scheduled
  342. # Check the loop watches no descriptors.
  343. # NOTE the loop has a pipe for self-interrupting, created once per
  344. # lifecycle, and it is unwatched only at loop.close(); so we cannot just
  345. # check selector for non-emptiness
  346. assert len(self.loop._selector.get_map()) \
  347. == int(self.loop._ssock is not None)
  348. del self.loop
  349. def assertNotRaises(self, excClass, callableObj=None, *args, **kwargs):
  350. """Fail if an exception of class excClass is raised
  351. by callableObj when invoked with arguments args and keyword
  352. arguments kwargs. If a different type of exception is
  353. raised, it will not be caught, and the test case will be
  354. deemed to have suffered an error, exactly as for an
  355. unexpected exception.
  356. If called with callableObj omitted or None, will return a
  357. context object used like this::
  358. with self.assertRaises(SomeException):
  359. do_something()
  360. The context manager keeps a reference to the exception as
  361. the 'exception' attribute. This allows you to inspect the
  362. exception after the assertion::
  363. with self.assertRaises(SomeException) as cm:
  364. do_something()
  365. the_exception = cm.exception
  366. self.assertEqual(the_exception.error_code, 3)
  367. """
  368. context = _AssertNotRaisesContext(excClass, self)
  369. if callableObj is None:
  370. return context
  371. with context:
  372. callableObj(*args, **kwargs)
  373. def assertXMLEqual(self, xml1, xml2, msg=''):
  374. '''Check for equality of two XML objects.
  375. :param xml1: first element
  376. :param xml2: second element
  377. :type xml1: :py:class:`lxml.etree._Element`
  378. :type xml2: :py:class:`lxml.etree._Element`
  379. '''
  380. self.assertEqual(xml1.tag, xml2.tag)
  381. msg += '/' + str(xml1.tag)
  382. if xml1.text is not None and xml2.text is not None:
  383. self.assertEqual(xml1.text.strip(), xml2.text.strip(), msg)
  384. else:
  385. self.assertEqual(xml1.text, xml2.text, msg)
  386. self.assertCountEqual(xml1.keys(), xml2.keys(), msg)
  387. for key in xml1.keys():
  388. self.assertEqual(xml1.get(key), xml2.get(key), msg)
  389. self.assertEqual(len(xml1), len(xml2), msg + ' children count')
  390. for child1, child2 in zip(xml1, xml2):
  391. self.assertXMLEqual(child1, child2, msg=msg)
  392. def assertDevicesEqual(self, devices1, devices2, msg=None):
  393. self.assertEqual(devices1.keys(), devices2.keys(), msg)
  394. for dev_class in devices1.keys():
  395. self.assertEqual(
  396. [str(dev) for dev in devices1[dev_class]],
  397. [str(dev) for dev in devices2[dev_class]],
  398. "Devices of class {} differs{}".format(
  399. dev_class, (": " + msg) if msg else "")
  400. )
  401. def assertEventFired(self, subject, event, kwargs=None):
  402. '''Check whether event was fired on given emitter and fail if it did
  403. not.
  404. :param subject: emitter which is being checked
  405. :type emitter: :py:class:`TestEmitter`
  406. :param str event: event identifier
  407. :param dict kwargs: when given, all items must appear in kwargs passed \
  408. to an event
  409. '''
  410. will_not_match = object()
  411. for ev, ev_kwargs in subject.fired_events:
  412. if ev != event:
  413. continue
  414. if kwargs is not None:
  415. ev_kwargs = dict(ev_kwargs)
  416. if any(ev_kwargs.get(k, will_not_match) != v
  417. for k, v in kwargs.items()):
  418. continue
  419. return
  420. self.fail('event {!r} {}did not fire on {!r}'.format(
  421. event, ('' if kwargs is None else '{!r} '.format(kwargs)), subject))
  422. def assertEventNotFired(self, subject, event, kwargs=None):
  423. '''Check whether event was fired on given emitter. Fail if it did.
  424. :param subject: emitter which is being checked
  425. :type emitter: :py:class:`TestEmitter`
  426. :param str event: event identifier
  427. :param list kwargs: when given, all items must appear in kwargs passed \
  428. to an event
  429. '''
  430. will_not_match = object()
  431. for ev, ev_kwargs in subject.fired_events:
  432. if ev != event:
  433. continue
  434. if kwargs is not None:
  435. ev_kwargs = dict(ev_kwargs)
  436. if any(ev_kwargs.get(k, will_not_match) != v
  437. for k, v in kwargs.items()):
  438. continue
  439. self.fail('event {!r} {}did fire on {!r}'.format(
  440. event,
  441. ('' if kwargs is None else '{!r} '.format(kwargs)),
  442. subject))
  443. return
  444. def assertXMLIsValid(self, xml, file=None, schema=None):
  445. '''Check whether given XML fulfills Relax NG schema.
  446. Schema can be given in a couple of ways:
  447. - As separate file. This is most common, and also the only way to
  448. handle file inclusion. Call with file name as second argument.
  449. - As string containing actual schema. Put that string in *schema*
  450. keyword argument.
  451. :param lxml.etree._Element xml: XML element instance to check
  452. :param str file: filename of Relax NG schema
  453. :param str schema: optional explicit schema string
  454. ''' # pylint: disable=redefined-builtin
  455. if schema is not None and file is None:
  456. relaxng = schema
  457. if isinstance(relaxng, str):
  458. relaxng = lxml.etree.XML(relaxng)
  459. # pylint: disable=protected-access
  460. if isinstance(relaxng, lxml.etree._Element):
  461. relaxng = lxml.etree.RelaxNG(relaxng)
  462. elif file is not None and schema is None:
  463. if not os.path.isabs(file):
  464. basedirs = ['/usr/share/doc/qubes/relaxng']
  465. if in_git:
  466. basedirs.insert(0, os.path.join(in_git, 'relaxng'))
  467. for basedir in basedirs:
  468. abspath = os.path.join(basedir, file)
  469. if os.path.exists(abspath):
  470. file = abspath
  471. break
  472. relaxng = lxml.etree.RelaxNG(file=file)
  473. else:
  474. raise TypeError("There should be excactly one of 'file' and "
  475. "'schema' arguments specified.")
  476. # We have to be extra careful here in case someone messed up with
  477. # self.failureException. It should by default be AssertionError, just
  478. # what is spewed by RelaxNG(), but who knows what might happen.
  479. try:
  480. relaxng.assert_(xml)
  481. except self.failureException:
  482. raise
  483. except AssertionError as e:
  484. self.fail(str(e))
  485. @staticmethod
  486. def make_vm_name(name, class_teardown=False):
  487. if class_teardown:
  488. return CLSVMPREFIX + name
  489. else:
  490. return VMPREFIX + name
  491. class SystemTestCase(QubesTestCase):
  492. """
  493. Mixin for integration tests. All the tests here should use self.app
  494. object and when need qubes.xml path - should use :py:data:`XMLPATH`
  495. defined in this file.
  496. Every VM created by test, must use :py:meth:`SystemTestCase.make_vm_name`
  497. for VM name.
  498. By default self.app represents empty collection, if anything is needed
  499. there from the real collection it can be imported from self.host_app in
  500. :py:meth:`SystemTestCase.setUp`. But *can not be modified* in any way -
  501. this include both changing attributes in
  502. :py:attr:`SystemTestCase.host_app` and modifying files of such imported
  503. VM. If test need to make some modification, it must clone the VM first.
  504. If some group of tests needs class-wide initialization, first of all the
  505. author should consider if it is really needed. But if so, setUpClass can
  506. be used to create Qubes(CLASS_XMLPATH) object and create/import required
  507. stuff there. VMs created in :py:meth:`TestCase.setUpClass` should
  508. use self.make_vm_name('...', class_teardown=True) for name creation.
  509. Such (group of) test need to take care about
  510. :py:meth:`TestCase.tearDownClass` implementation itself.
  511. """
  512. # noinspection PyAttributeOutsideInit
  513. def setUp(self):
  514. if not in_dom0:
  515. self.skipTest('outside dom0')
  516. super(SystemTestCase, self).setUp()
  517. self.remove_test_vms()
  518. # need some information from the real qubes.xml - at least installed
  519. # templates; should not be used for testing, only to initialize self.app
  520. self.host_app = qubes.Qubes(os.path.join(
  521. qubes.config.qubes_base_dir,
  522. qubes.config.system_path['qubes_store_filename']))
  523. if os.path.exists(CLASS_XMLPATH):
  524. shutil.copy(CLASS_XMLPATH, XMLPATH)
  525. else:
  526. shutil.copy(self.host_app.store, XMLPATH)
  527. self.app = qubes.Qubes(XMLPATH)
  528. os.environ['QUBES_XML_PATH'] = XMLPATH
  529. self.app.register_event_handlers()
  530. self.qubesd = self.loop.run_until_complete(
  531. qubes.api.create_servers(
  532. qubes.api.admin.QubesAdminAPI,
  533. qubes.api.internal.QubesInternalAPI,
  534. app=self.app, debug=True))
  535. self.addCleanup(self.cleanup_app)
  536. self.app.add_handler('domain-delete', self.close_qdb_on_remove)
  537. def close_qdb_on_remove(self, app, event, vm, **kwargs):
  538. # only close QubesDB connection, do not perform other (destructive)
  539. # actions of vm.close()
  540. if vm._qdb_connection_watch is not None:
  541. asyncio.get_event_loop().remove_reader(
  542. vm._qdb_connection_watch.watch_fd())
  543. vm._qdb_connection_watch.close()
  544. vm._qdb_connection_watch = None
  545. def cleanup_app(self):
  546. self.remove_test_vms()
  547. server = None
  548. for server in self.qubesd:
  549. for sock in server.sockets:
  550. os.unlink(sock.getsockname())
  551. server.close()
  552. del server
  553. # close all existing connections, especially this will interrupt
  554. # running admin.Events calls, which do keep reference to Qubes() and
  555. # libvirt connection
  556. conn = None
  557. for conn in qubes.api.QubesDaemonProtocol.connections:
  558. if conn.transport:
  559. conn.transport.abort()
  560. del conn
  561. self.loop.run_until_complete(asyncio.wait([
  562. server.wait_closed() for server in self.qubesd]))
  563. del self.qubesd
  564. # remove all references to any complex qubes objects, to release
  565. # resources - most importantly file descriptors; this object will live
  566. # during the whole test run, but all the file descriptors would be
  567. # depleted earlier
  568. self.app.close()
  569. self.host_app.close()
  570. del self.app
  571. del self.host_app
  572. for attr in dir(self):
  573. obj_type = type(getattr(self, attr))
  574. if obj_type.__module__.startswith('qubes'):
  575. delattr(self, attr)
  576. # then trigger garbage collector to really destroy those objects
  577. gc.collect()
  578. def init_default_template(self, template=None):
  579. if template is None:
  580. template = self.host_app.default_template
  581. elif isinstance(template, str):
  582. template = self.host_app.domains[template]
  583. self.app.default_template = str(template)
  584. def init_networking(self):
  585. if not self.app.default_template:
  586. self.skipTest('Default template required for testing networking')
  587. default_netvm = self.host_app.default_netvm
  588. # if testing Whonix Workstation based VMs, try to use sys-whonix instead
  589. if self.app.default_template.name.startswith('whonix-ws'):
  590. if 'sys-whonix' in self.host_app.domains:
  591. default_netvm = self.host_app.domains['sys-whonix']
  592. if default_netvm is None:
  593. self.skipTest('Default netvm required')
  594. if not default_netvm.is_running():
  595. self.skipTest('VM {} required to be running'.format(
  596. default_netvm.name))
  597. self.app.default_netvm = str(default_netvm)
  598. def _find_pool(self, volume_group, thin_pool):
  599. ''' Returns the pool matching the specified ``volume_group`` &
  600. ``thin_pool``, or None.
  601. '''
  602. pools = [p for p in self.app.pools
  603. if issubclass(p.__class__, qubes.storage.lvm.ThinPool)]
  604. for pool in pools:
  605. if pool.volume_group == volume_group \
  606. and pool.thin_pool == thin_pool:
  607. return pool
  608. return None
  609. def init_lvm_pool(self):
  610. volume_group, thin_pool = DEFAULT_LVM_POOL.split('/', 1)
  611. path = "/dev/mapper/{!s}-{!s}".format(volume_group, thin_pool)
  612. if not os.path.exists(path):
  613. self.skipTest('LVM thin pool {!r} does not exist'.
  614. format(DEFAULT_LVM_POOL))
  615. self.pool = self._find_pool(volume_group, thin_pool)
  616. if not self.pool:
  617. self.pool = self.app.add_pool(**POOL_CONF)
  618. self.created_pool = True
  619. def _remove_vm_qubes(self, vm):
  620. vmname = vm.name
  621. app = vm.app
  622. # avoid race with DispVM.auto_cleanup=True
  623. try:
  624. self.loop.run_until_complete(
  625. asyncio.wait_for(vm.startup_lock.acquire(), 10))
  626. except asyncio.TimeoutError:
  627. pass
  628. try:
  629. # XXX .is_running() may throw libvirtError if undefined
  630. if vm.is_running():
  631. self.loop.run_until_complete(vm.kill())
  632. except: # pylint: disable=bare-except
  633. pass
  634. try:
  635. self.loop.run_until_complete(vm.remove_from_disk())
  636. except: # pylint: disable=bare-except
  637. pass
  638. try:
  639. del app.domains[vm.qid]
  640. except KeyError:
  641. pass
  642. vm.close()
  643. del vm
  644. app.save()
  645. del app
  646. # Now ensure it really went away. This may not have happened,
  647. # for example if vm.libvirt_domain malfunctioned.
  648. try:
  649. conn = libvirt.open(qubes.config.defaults['libvirt_uri'])
  650. except: # pylint: disable=bare-except
  651. pass
  652. else:
  653. try:
  654. dom = conn.lookupByName(vmname)
  655. except: # pylint: disable=bare-except
  656. pass
  657. else:
  658. self._remove_vm_libvirt(dom)
  659. conn.close()
  660. self._remove_vm_disk(vmname)
  661. @staticmethod
  662. def _remove_vm_libvirt(dom):
  663. try:
  664. dom.destroy()
  665. except libvirt.libvirtError: # not running
  666. pass
  667. dom.undefine()
  668. @staticmethod
  669. def _remove_vm_disk(vmname):
  670. for dirspec in (
  671. 'qubes_appvms_dir',
  672. 'qubes_servicevms_dir',
  673. 'qubes_templates_dir'):
  674. dirpath = os.path.join(qubes.config.qubes_base_dir,
  675. qubes.config.system_path[dirspec], vmname)
  676. if os.path.exists(dirpath):
  677. if os.path.isdir(dirpath):
  678. shutil.rmtree(dirpath)
  679. else:
  680. os.unlink(dirpath)
  681. @staticmethod
  682. def _remove_vm_disk_lvm(prefix=VMPREFIX):
  683. ''' Remove LVM volumes with given prefix
  684. This is "a bit" drastic, as it removes volumes regardless of volume
  685. group, thin pool etc. But we assume no important data on test system.
  686. '''
  687. try:
  688. volumes = subprocess.check_output(
  689. ['sudo', 'lvs', '--noheadings', '-o', 'vg_name,name',
  690. '--separator', '/']).decode()
  691. if ('/vm-' + prefix) not in volumes:
  692. return
  693. subprocess.check_call(['sudo', 'lvremove', '-f'] +
  694. [vol.strip() for vol in volumes.splitlines()
  695. if ('/vm-' + prefix) in vol],
  696. stdout=subprocess.DEVNULL)
  697. except subprocess.CalledProcessError:
  698. pass
  699. def remove_vms(self, vms):
  700. vms = list(vms)
  701. if not vms:
  702. return
  703. # break dependencies
  704. for vm in vms:
  705. vm.default_dispvm = None
  706. # then remove in reverse topological order (wrt netvm), using naive
  707. # algorithm
  708. # this heavily depends on lack of netvm loops
  709. while vms:
  710. vm = vms.pop(0)
  711. # make sure that all connected VMs are going to be removed,
  712. # otherwise this will loop forever
  713. assert all(x in vms for x in vm.connected_vms)
  714. if list(vm.connected_vms):
  715. # if still something use this VM, put it at the end of queue
  716. # and try next one
  717. vms.append(vm)
  718. continue
  719. self._remove_vm_qubes(vm)
  720. def remove_test_vms(self, xmlpath=XMLPATH, prefix=VMPREFIX):
  721. '''Aggresively remove any domain that has name in testing namespace.
  722. '''
  723. # first, remove them Qubes-way
  724. if os.path.exists(xmlpath):
  725. try:
  726. try:
  727. app = self.app
  728. except AttributeError:
  729. app = qubes.Qubes(xmlpath)
  730. try:
  731. host_app = self.host_app
  732. except AttributeError:
  733. host_app = qubes.Qubes()
  734. self.remove_vms([vm for vm in app.domains
  735. if vm.name.startswith(prefix) or
  736. (isinstance(vm, qubes.vm.dispvm.DispVM) and vm.name
  737. not in host_app.domains)])
  738. if not hasattr(self, 'host_app'):
  739. host_app.close()
  740. del host_app
  741. if not hasattr(self, 'app'):
  742. app.close()
  743. del app
  744. except qubes.exc.QubesException:
  745. pass
  746. os.unlink(xmlpath)
  747. # now remove what was only in libvirt
  748. conn = libvirt.open(qubes.config.defaults['libvirt_uri'])
  749. for dom in conn.listAllDomains():
  750. if dom.name().startswith(prefix):
  751. self._remove_vm_libvirt(dom)
  752. conn.close()
  753. # finally remove anything that is left on disk
  754. vmnames = set()
  755. for dirspec in (
  756. 'qubes_appvms_dir',
  757. 'qubes_servicevms_dir',
  758. 'qubes_templates_dir'):
  759. dirpath = os.path.join(qubes.config.qubes_base_dir,
  760. qubes.config.system_path[dirspec])
  761. if not os.path.exists(dirpath):
  762. continue
  763. for name in os.listdir(dirpath):
  764. if name.startswith(prefix):
  765. vmnames.add(name)
  766. for vmname in vmnames:
  767. self._remove_vm_disk(vmname)
  768. self._remove_vm_disk_lvm(prefix)
  769. def qrexec_policy(self, service, source, destination, allow=True,
  770. action=None):
  771. """
  772. Allow qrexec calls for duration of the test
  773. :param service: service name
  774. :param source: source VM name
  775. :param destination: destination VM name
  776. :param allow: add rule with 'allow' action, otherwise 'deny'
  777. :param action: custom action, if specified *allow* argument is ignored
  778. :return:
  779. """
  780. return _QrexecPolicyContext(service, source, destination,
  781. allow=allow, action=action)
  782. def wait_for_window(self, title, timeout=30, show=True):
  783. """
  784. Wait for a window with a given title. Depending on show parameter,
  785. it will wait for either window to show or to disappear.
  786. :param title: title of the window to wait for
  787. :param timeout: timeout of the operation, in seconds
  788. :param show: if True - wait for the window to be visible,
  789. otherwise - to not be visible
  790. :return: None
  791. """
  792. wait_count = 0
  793. while subprocess.call(['xdotool', 'search', '--name', title],
  794. stdout=subprocess.DEVNULL, stderr=subprocess.STDOUT) \
  795. != int(not show):
  796. wait_count += 1
  797. if wait_count > timeout*10:
  798. self.fail("Timeout while waiting for {} window to {}".format(
  799. title, "show" if show else "hide")
  800. )
  801. self.loop.run_until_complete(asyncio.sleep(0.1))
  802. def enter_keys_in_window(self, title, keys):
  803. """
  804. Search for window with given title, then enter listed keys there.
  805. The function will wait for said window to appear.
  806. :param title: title of window
  807. :param keys: list of keys to enter, as for `xdotool key`
  808. :return: None
  809. """
  810. # 'xdotool search --sync' sometimes crashes on some race when
  811. # accessing window properties
  812. self.wait_for_window(title)
  813. command = ['xdotool', 'search', '--name', title,
  814. 'windowactivate', '--sync',
  815. 'key'] + keys
  816. subprocess.check_call(command)
  817. def shutdown_and_wait(self, vm, timeout=60):
  818. self.loop.run_until_complete(vm.shutdown())
  819. while timeout > 0:
  820. if not vm.is_running():
  821. return
  822. self.loop.run_until_complete(asyncio.sleep(1))
  823. timeout -= 1
  824. name = vm.name
  825. del vm
  826. self.fail("Timeout while waiting for VM {} shutdown".format(name))
  827. def prepare_hvm_system_linux(self, vm, init_script, extra_files=None):
  828. if not os.path.exists('/usr/lib/grub/i386-pc'):
  829. self.skipTest('grub2 not installed')
  830. if not spawn.find_executable('grub2-install'):
  831. self.skipTest('grub2-tools not installed')
  832. if not spawn.find_executable('dracut'):
  833. self.skipTest('dracut not installed')
  834. # create a single partition
  835. p = subprocess.Popen(['sfdisk', '-q', '-L', vm.storage.root_img],
  836. stdin=subprocess.PIPE,
  837. stdout=subprocess.DEVNULL,
  838. stderr=subprocess.STDOUT)
  839. p.communicate('2048,\n')
  840. assert p.returncode == 0, 'sfdisk failed'
  841. # TODO: check if root_img is really file, not already block device
  842. p = subprocess.Popen(['sudo', 'losetup', '-f', '-P', '--show',
  843. vm.storage.root_img], stdout=subprocess.PIPE)
  844. (loopdev, _) = p.communicate()
  845. loopdev = loopdev.strip()
  846. looppart = loopdev + 'p1'
  847. assert p.returncode == 0, 'losetup failed'
  848. subprocess.check_call(['sudo', 'mkfs.ext2', '-q', '-F', looppart])
  849. mountpoint = tempfile.mkdtemp()
  850. subprocess.check_call(['sudo', 'mount', looppart, mountpoint])
  851. try:
  852. subprocess.check_call(['sudo', 'grub2-install',
  853. '--target', 'i386-pc',
  854. '--modules', 'part_msdos ext2',
  855. '--boot-directory', mountpoint, loopdev],
  856. stderr=subprocess.DEVNULL
  857. )
  858. grub_cfg = '{}/grub2/grub.cfg'.format(mountpoint)
  859. subprocess.check_call(
  860. ['sudo', 'chown', '-R', os.getlogin(), mountpoint])
  861. with open(grub_cfg, 'w') as f:
  862. f.write(
  863. "set timeout=1\n"
  864. "menuentry 'Default' {\n"
  865. " linux /vmlinuz root=/dev/xvda1 "
  866. "rd.driver.blacklist=bochs_drm "
  867. "rd.driver.blacklist=uhci_hcd console=hvc0\n"
  868. " initrd /initrd\n"
  869. "}"
  870. )
  871. p = subprocess.Popen(['uname', '-r'], stdout=subprocess.PIPE)
  872. (kernel_version, _) = p.communicate()
  873. kernel_version = kernel_version.strip()
  874. kernel = '/boot/vmlinuz-{}'.format(kernel_version)
  875. shutil.copy(kernel, os.path.join(mountpoint, 'vmlinuz'))
  876. init_path = os.path.join(mountpoint, 'init')
  877. with open(init_path, 'w') as f:
  878. f.write(init_script)
  879. os.chmod(init_path, 0o755)
  880. dracut_args = [
  881. '--kver', kernel_version,
  882. '--include', init_path,
  883. '/usr/lib/dracut/hooks/pre-pivot/initscript.sh',
  884. '--no-hostonly', '--nolvmconf', '--nomdadmconf',
  885. ]
  886. if extra_files:
  887. dracut_args += ['--install', ' '.join(extra_files)]
  888. subprocess.check_call(
  889. ['dracut'] + dracut_args + [os.path.join(mountpoint,
  890. 'initrd')],
  891. stderr=subprocess.DEVNULL
  892. )
  893. finally:
  894. subprocess.check_call(['sudo', 'umount', mountpoint])
  895. shutil.rmtree(mountpoint)
  896. subprocess.check_call(['sudo', 'losetup', '-d', loopdev])
  897. def create_local_file(self, filename, content, mode='w'):
  898. with open(filename, mode) as file:
  899. file.write(content)
  900. self.addCleanup(os.unlink, filename)
  901. def create_remote_file(self, vm, filename, content):
  902. self.loop.run_until_complete(vm.run_for_stdio(
  903. 'cat > {}'.format(shlex.quote(filename)),
  904. user='root', input=content.encode('utf-8')))
  905. @asyncio.coroutine
  906. def wait_for_session(self, vm):
  907. yield from asyncio.wait_for(
  908. vm.run_service_for_stdio(
  909. 'qubes.WaitForSession', input=vm.default_user.encode()),
  910. timeout=30)
  911. _templates = None
  912. def list_templates():
  913. '''Returns tuple of template names available in the system.'''
  914. global _templates
  915. if _templates is None:
  916. try:
  917. app = qubes.Qubes()
  918. _templates = tuple(vm.name for vm in app.domains
  919. if isinstance(vm, qubes.vm.templatevm.TemplateVM))
  920. app.close()
  921. del app
  922. except OSError:
  923. _templates = ()
  924. return _templates
  925. def extra_info(obj):
  926. '''Return short info identifying object.
  927. For example, if obj is a qube, return its name. This is for use with
  928. :py:mod:`objgraph` package.
  929. '''
  930. # Feel free to extend to other cases.
  931. if isinstance(obj, qubes.vm.qubesvm.QubesVM):
  932. try:
  933. return obj.name
  934. except AttributeError:
  935. pass
  936. if isinstance(obj, unittest.TestCase):
  937. return obj.id()
  938. return ''
  939. def load_tests(loader, tests, pattern): # pylint: disable=unused-argument
  940. # discard any tests from this module, because it hosts base classes
  941. tests = unittest.TestSuite()
  942. for modname in (
  943. # unit tests
  944. 'qubes.tests.events',
  945. 'qubes.tests.devices',
  946. 'qubes.tests.devices_block',
  947. 'qubes.tests.firewall',
  948. 'qubes.tests.init',
  949. 'qubes.tests.vm.init',
  950. 'qubes.tests.storage',
  951. 'qubes.tests.storage_file',
  952. 'qubes.tests.storage_lvm',
  953. 'qubes.tests.storage_kernels',
  954. 'qubes.tests.ext',
  955. 'qubes.tests.vm.qubesvm',
  956. 'qubes.tests.vm.mix.net',
  957. 'qubes.tests.vm.adminvm',
  958. 'qubes.tests.vm.appvm',
  959. 'qubes.tests.vm.dispvm',
  960. 'qubes.tests.app',
  961. 'qubes.tests.tarwriter',
  962. 'qubes.tests.api',
  963. 'qubes.tests.api_admin',
  964. 'qubes.tests.api_misc',
  965. 'qubespolicy.tests',
  966. 'qubespolicy.tests.cli',
  967. ):
  968. tests.addTests(loader.loadTestsFromName(modname))
  969. # GTK/Glib is way too old there
  970. if 'TRAVIS' not in os.environ:
  971. for modname in (
  972. 'qubespolicy.tests.gtkhelpers',
  973. 'qubespolicy.tests.rpcconfirmation',
  974. ):
  975. tests.addTests(loader.loadTestsFromName(modname))
  976. tests.addTests(loader.discover(
  977. os.path.join(os.path.dirname(__file__), 'tools')))
  978. if not in_dom0:
  979. return tests
  980. for modname in (
  981. # integration tests
  982. 'qubes.tests.integ.basic',
  983. 'qubes.tests.integ.storage',
  984. 'qubes.tests.integ.devices_pci',
  985. 'qubes.tests.integ.dom0_update',
  986. 'qubes.tests.integ.network',
  987. 'qubes.tests.integ.dispvm',
  988. 'qubes.tests.integ.vm_qrexec_gui',
  989. 'qubes.tests.integ.backup',
  990. 'qubes.tests.integ.backupcompatibility',
  991. # 'qubes.tests.regressions',
  992. # external modules
  993. # 'qubes.tests.extra',
  994. ):
  995. tests.addTests(loader.loadTestsFromName(modname))
  996. return tests