__init__.py 37 KB

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