__init__.py 37 KB

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