__init__.py 39 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122
  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):
  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. self._rule = '{} {} {}\n'.format(source, destination,
  222. 'allow' if allow else 'deny')
  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 list 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. def cleanup_app(self):
  537. self.remove_test_vms()
  538. server = None
  539. for server in self.qubesd:
  540. for sock in server.sockets:
  541. os.unlink(sock.getsockname())
  542. server.close()
  543. del server
  544. # close all existing connections, especially this will interrupt
  545. # running admin.Events calls, which do keep reference to Qubes() and
  546. # libvirt connection
  547. conn = None
  548. for conn in qubes.api.QubesDaemonProtocol.connections:
  549. if conn.transport:
  550. conn.transport.abort()
  551. del conn
  552. self.loop.run_until_complete(asyncio.wait([
  553. server.wait_closed() for server in self.qubesd]))
  554. del self.qubesd
  555. # remove all references to any complex qubes objects, to release
  556. # resources - most importantly file descriptors; this object will live
  557. # during the whole test run, but all the file descriptors would be
  558. # depleted earlier
  559. self.app.close()
  560. self.host_app.close()
  561. del self.app
  562. del self.host_app
  563. for attr in dir(self):
  564. obj_type = type(getattr(self, attr))
  565. if obj_type.__module__.startswith('qubes'):
  566. delattr(self, attr)
  567. # then trigger garbage collector to really destroy those objects
  568. gc.collect()
  569. def init_default_template(self, template=None):
  570. if template is None:
  571. template = self.host_app.default_template
  572. elif isinstance(template, str):
  573. template = self.host_app.domains[template]
  574. self.app.default_template = str(template)
  575. def init_networking(self):
  576. if not self.app.default_template:
  577. self.skipTest('Default template required for testing networking')
  578. default_netvm = self.host_app.default_netvm
  579. # if testing Whonix Workstation based VMs, try to use sys-whonix instead
  580. if self.app.default_template.name.startswith('whonix-ws'):
  581. if 'sys-whonix' in self.host_app.domains:
  582. default_netvm = self.host_app.domains['sys-whonix']
  583. if default_netvm is None:
  584. self.skipTest('Default netvm required')
  585. if not default_netvm.is_running():
  586. self.skipTest('VM {} required to be running'.format(
  587. default_netvm.name))
  588. self.app.default_netvm = str(default_netvm)
  589. def _find_pool(self, volume_group, thin_pool):
  590. ''' Returns the pool matching the specified ``volume_group`` &
  591. ``thin_pool``, or None.
  592. '''
  593. pools = [p for p in self.app.pools
  594. if issubclass(p.__class__, qubes.storage.lvm.ThinPool)]
  595. for pool in pools:
  596. if pool.volume_group == volume_group \
  597. and pool.thin_pool == thin_pool:
  598. return pool
  599. return None
  600. def init_lvm_pool(self):
  601. volume_group, thin_pool = DEFAULT_LVM_POOL.split('/', 1)
  602. path = "/dev/mapper/{!s}-{!s}".format(volume_group, thin_pool)
  603. if not os.path.exists(path):
  604. self.skipTest('LVM thin pool {!r} does not exist'.
  605. format(DEFAULT_LVM_POOL))
  606. self.pool = self._find_pool(volume_group, thin_pool)
  607. if not self.pool:
  608. self.pool = self.app.add_pool(**POOL_CONF)
  609. self.created_pool = True
  610. def _remove_vm_qubes(self, vm):
  611. vmname = vm.name
  612. app = vm.app
  613. try:
  614. # XXX .is_running() may throw libvirtError if undefined
  615. if vm.is_running():
  616. self.loop.run_until_complete(vm.kill())
  617. except: # pylint: disable=bare-except
  618. pass
  619. try:
  620. self.loop.run_until_complete(vm.remove_from_disk())
  621. except: # pylint: disable=bare-except
  622. pass
  623. del app.domains[vm.qid]
  624. del vm
  625. app.save()
  626. del app
  627. # Now ensure it really went away. This may not have happened,
  628. # for example if vm.libvirt_domain malfunctioned.
  629. try:
  630. conn = libvirt.open(qubes.config.defaults['libvirt_uri'])
  631. except: # pylint: disable=bare-except
  632. pass
  633. else:
  634. try:
  635. dom = conn.lookupByName(vmname)
  636. except: # pylint: disable=bare-except
  637. pass
  638. else:
  639. self._remove_vm_libvirt(dom)
  640. conn.close()
  641. self._remove_vm_disk(vmname)
  642. @staticmethod
  643. def _remove_vm_libvirt(dom):
  644. try:
  645. dom.destroy()
  646. except libvirt.libvirtError: # not running
  647. pass
  648. dom.undefine()
  649. @staticmethod
  650. def _remove_vm_disk(vmname):
  651. for dirspec in (
  652. 'qubes_appvms_dir',
  653. 'qubes_servicevms_dir',
  654. 'qubes_templates_dir'):
  655. dirpath = os.path.join(qubes.config.qubes_base_dir,
  656. qubes.config.system_path[dirspec], vmname)
  657. if os.path.exists(dirpath):
  658. if os.path.isdir(dirpath):
  659. shutil.rmtree(dirpath)
  660. else:
  661. os.unlink(dirpath)
  662. @staticmethod
  663. def _remove_vm_disk_lvm(prefix=VMPREFIX):
  664. ''' Remove LVM volumes with given prefix
  665. This is "a bit" drastic, as it removes volumes regardless of volume
  666. group, thin pool etc. But we assume no important data on test system.
  667. '''
  668. try:
  669. volumes = subprocess.check_output(
  670. ['sudo', 'lvs', '--noheadings', '-o', 'vg_name,name',
  671. '--separator', '/']).decode()
  672. if ('/vm-' + prefix) not in volumes:
  673. return
  674. subprocess.check_call(['sudo', 'lvremove', '-f'] +
  675. [vol.strip() for vol in volumes.splitlines()
  676. if ('/vm-' + prefix) in vol],
  677. stdout=subprocess.DEVNULL)
  678. except subprocess.CalledProcessError:
  679. pass
  680. def remove_vms(self, vms):
  681. for vm in vms:
  682. self._remove_vm_qubes(vm)
  683. def remove_test_vms(self, xmlpath=XMLPATH, prefix=VMPREFIX):
  684. '''Aggresively remove any domain that has name in testing namespace.
  685. '''
  686. # first, remove them Qubes-way
  687. if os.path.exists(xmlpath):
  688. try:
  689. try:
  690. app = self.app
  691. except AttributeError:
  692. app = qubes.Qubes(xmlpath)
  693. self.remove_vms(vm for vm in app.domains
  694. if vm.name.startswith(prefix))
  695. del app
  696. except qubes.exc.QubesException:
  697. pass
  698. os.unlink(xmlpath)
  699. # now remove what was only in libvirt
  700. conn = libvirt.open(qubes.config.defaults['libvirt_uri'])
  701. for dom in conn.listAllDomains():
  702. if dom.name().startswith(prefix):
  703. self._remove_vm_libvirt(dom)
  704. conn.close()
  705. # finally remove anything that is left on disk
  706. vmnames = set()
  707. for dirspec in (
  708. 'qubes_appvms_dir',
  709. 'qubes_servicevms_dir',
  710. 'qubes_templates_dir'):
  711. dirpath = os.path.join(qubes.config.qubes_base_dir,
  712. qubes.config.system_path[dirspec])
  713. for name in os.listdir(dirpath):
  714. if name.startswith(prefix):
  715. vmnames.add(name)
  716. for vmname in vmnames:
  717. self._remove_vm_disk(vmname)
  718. self._remove_vm_disk_lvm(prefix)
  719. def qrexec_policy(self, service, source, destination, allow=True):
  720. """
  721. Allow qrexec calls for duration of the test
  722. :param service: service name
  723. :param source: source VM name
  724. :param destination: destination VM name
  725. :return:
  726. """
  727. return _QrexecPolicyContext(service, source, destination, allow=allow)
  728. def wait_for_window(self, title, timeout=30, show=True):
  729. """
  730. Wait for a window with a given title. Depending on show parameter,
  731. it will wait for either window to show or to disappear.
  732. :param title: title of the window to wait for
  733. :param timeout: timeout of the operation, in seconds
  734. :param show: if True - wait for the window to be visible,
  735. otherwise - to not be visible
  736. :return: None
  737. """
  738. wait_count = 0
  739. while subprocess.call(['xdotool', 'search', '--name', title],
  740. stdout=subprocess.DEVNULL, stderr=subprocess.STDOUT) \
  741. == int(show):
  742. wait_count += 1
  743. if wait_count > timeout*10:
  744. self.fail("Timeout while waiting for {} window to {}".format(
  745. title, "show" if show else "hide")
  746. )
  747. time.sleep(0.1)
  748. def enter_keys_in_window(self, title, keys):
  749. """
  750. Search for window with given title, then enter listed keys there.
  751. The function will wait for said window to appear.
  752. :param title: title of window
  753. :param keys: list of keys to enter, as for `xdotool key`
  754. :return: None
  755. """
  756. # 'xdotool search --sync' sometimes crashes on some race when
  757. # accessing window properties
  758. self.wait_for_window(title)
  759. command = ['xdotool', 'search', '--name', title,
  760. 'windowactivate', '--sync',
  761. 'key'] + keys
  762. subprocess.check_call(command)
  763. def shutdown_and_wait(self, vm, timeout=60):
  764. vm.shutdown()
  765. while timeout > 0:
  766. if not vm.is_running():
  767. return
  768. self.loop.run_until_complete(asyncio.sleep(1))
  769. timeout -= 1
  770. self.fail("Timeout while waiting for VM {} shutdown".format(vm.name))
  771. def prepare_hvm_system_linux(self, vm, init_script, extra_files=None):
  772. if not os.path.exists('/usr/lib/grub/i386-pc'):
  773. self.skipTest('grub2 not installed')
  774. if not spawn.find_executable('grub2-install'):
  775. self.skipTest('grub2-tools not installed')
  776. if not spawn.find_executable('dracut'):
  777. self.skipTest('dracut not installed')
  778. # create a single partition
  779. p = subprocess.Popen(['sfdisk', '-q', '-L', vm.storage.root_img],
  780. stdin=subprocess.PIPE,
  781. stdout=subprocess.DEVNULL,
  782. stderr=subprocess.STDOUT)
  783. p.communicate('2048,\n')
  784. assert p.returncode == 0, 'sfdisk failed'
  785. # TODO: check if root_img is really file, not already block device
  786. p = subprocess.Popen(['sudo', 'losetup', '-f', '-P', '--show',
  787. vm.storage.root_img], stdout=subprocess.PIPE)
  788. (loopdev, _) = p.communicate()
  789. loopdev = loopdev.strip()
  790. looppart = loopdev + 'p1'
  791. assert p.returncode == 0, 'losetup failed'
  792. subprocess.check_call(['sudo', 'mkfs.ext2', '-q', '-F', looppart])
  793. mountpoint = tempfile.mkdtemp()
  794. subprocess.check_call(['sudo', 'mount', looppart, mountpoint])
  795. try:
  796. subprocess.check_call(['sudo', 'grub2-install',
  797. '--target', 'i386-pc',
  798. '--modules', 'part_msdos ext2',
  799. '--boot-directory', mountpoint, loopdev],
  800. stderr=subprocess.DEVNULL
  801. )
  802. grub_cfg = '{}/grub2/grub.cfg'.format(mountpoint)
  803. subprocess.check_call(
  804. ['sudo', 'chown', '-R', os.getlogin(), mountpoint])
  805. with open(grub_cfg, 'w') as f:
  806. f.write(
  807. "set timeout=1\n"
  808. "menuentry 'Default' {\n"
  809. " linux /vmlinuz root=/dev/xvda1 "
  810. "rd.driver.blacklist=bochs_drm "
  811. "rd.driver.blacklist=uhci_hcd console=hvc0\n"
  812. " initrd /initrd\n"
  813. "}"
  814. )
  815. p = subprocess.Popen(['uname', '-r'], stdout=subprocess.PIPE)
  816. (kernel_version, _) = p.communicate()
  817. kernel_version = kernel_version.strip()
  818. kernel = '/boot/vmlinuz-{}'.format(kernel_version)
  819. shutil.copy(kernel, os.path.join(mountpoint, 'vmlinuz'))
  820. init_path = os.path.join(mountpoint, 'init')
  821. with open(init_path, 'w') as f:
  822. f.write(init_script)
  823. os.chmod(init_path, 0o755)
  824. dracut_args = [
  825. '--kver', kernel_version,
  826. '--include', init_path,
  827. '/usr/lib/dracut/hooks/pre-pivot/initscript.sh',
  828. '--no-hostonly', '--nolvmconf', '--nomdadmconf',
  829. ]
  830. if extra_files:
  831. dracut_args += ['--install', ' '.join(extra_files)]
  832. subprocess.check_call(
  833. ['dracut'] + dracut_args + [os.path.join(mountpoint,
  834. 'initrd')],
  835. stderr=subprocess.DEVNULL
  836. )
  837. finally:
  838. subprocess.check_call(['sudo', 'umount', mountpoint])
  839. shutil.rmtree(mountpoint)
  840. subprocess.check_call(['sudo', 'losetup', '-d', loopdev])
  841. def create_local_file(self, filename, content, mode='w'):
  842. with open(filename, mode) as file:
  843. file.write(content)
  844. self.addCleanup(os.unlink, filename)
  845. def create_remote_file(self, vm, filename, content):
  846. self.loop.run_until_complete(vm.run_for_stdio(
  847. 'cat > {}'.format(shlex.quote(filename)),
  848. user='root', input=content.encode('utf-8')))
  849. @asyncio.coroutine
  850. def wait_for_session(self, vm):
  851. yield from asyncio.wait_for(
  852. vm.run_service_for_stdio(
  853. 'qubes.WaitForSession', input=vm.default_user.encode()),
  854. timeout=30)
  855. _templates = None
  856. def list_templates():
  857. '''Returns tuple of template names available in the system.'''
  858. global _templates
  859. if _templates is None:
  860. try:
  861. app = qubes.Qubes()
  862. _templates = tuple(vm.name for vm in app.domains
  863. if isinstance(vm, qubes.vm.templatevm.TemplateVM))
  864. app.close()
  865. del app
  866. except OSError:
  867. _templates = ()
  868. return _templates
  869. def extra_info(obj):
  870. '''Return short info identifying object.
  871. For example, if obj is a qube, return its name. This is for use with
  872. :py:mod:`objgraph` package.
  873. '''
  874. # Feel free to extend to other cases.
  875. if isinstance(obj, qubes.vm.qubesvm.QubesVM):
  876. try:
  877. return obj.name
  878. except AttributeError:
  879. pass
  880. if isinstance(obj, unittest.TestCase):
  881. return obj.id()
  882. return ''
  883. def load_tests(loader, tests, pattern): # pylint: disable=unused-argument
  884. # discard any tests from this module, because it hosts base classes
  885. tests = unittest.TestSuite()
  886. for modname in (
  887. # unit tests
  888. 'qubes.tests.events',
  889. 'qubes.tests.devices',
  890. 'qubes.tests.devices_block',
  891. 'qubes.tests.firewall',
  892. 'qubes.tests.init',
  893. 'qubes.tests.vm.init',
  894. 'qubes.tests.storage',
  895. 'qubes.tests.storage_file',
  896. 'qubes.tests.storage_lvm',
  897. 'qubes.tests.storage_kernels',
  898. 'qubes.tests.ext',
  899. 'qubes.tests.vm.qubesvm',
  900. 'qubes.tests.vm.mix.net',
  901. 'qubes.tests.vm.adminvm',
  902. 'qubes.tests.vm.appvm',
  903. 'qubes.tests.vm.dispvm',
  904. 'qubes.tests.app',
  905. 'qubes.tests.tarwriter',
  906. 'qubes.tests.api',
  907. 'qubes.tests.api_admin',
  908. 'qubes.tests.api_misc',
  909. 'qubespolicy.tests',
  910. 'qubespolicy.tests.cli',
  911. ):
  912. tests.addTests(loader.loadTestsFromName(modname))
  913. # GTK/Glib is way too old there
  914. if 'TRAVIS' not in os.environ:
  915. for modname in (
  916. 'qubespolicy.tests.gtkhelpers',
  917. 'qubespolicy.tests.rpcconfirmation',
  918. ):
  919. tests.addTests(loader.loadTestsFromName(modname))
  920. tests.addTests(loader.discover(
  921. os.path.join(os.path.dirname(__file__), 'tools')))
  922. if not in_dom0:
  923. return tests
  924. for modname in (
  925. # integration tests
  926. 'qubes.tests.integ.basic',
  927. 'qubes.tests.integ.storage',
  928. 'qubes.tests.integ.devices_pci',
  929. 'qubes.tests.integ.dom0_update',
  930. 'qubes.tests.integ.network',
  931. 'qubes.tests.integ.dispvm',
  932. 'qubes.tests.integ.vm_qrexec_gui',
  933. 'qubes.tests.integ.backup',
  934. 'qubes.tests.integ.backupcompatibility',
  935. # 'qubes.tests.regressions',
  936. # external modules
  937. # 'qubes.tests.extra',
  938. ):
  939. tests.addTests(loader.loadTestsFromName(modname))
  940. return tests