__init__.py 40 KB

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